如何使用 Python 编写一个自动化脚本可以执行多个命令并记录运行结果?

如何使用 Python 编写一个自动化脚本可以执行多个命令并记录运行结果?

# My script.sh

#!/bin/bash

# This script executes the following commands:
# 1. Download a file from the internet
# 2. Compile a program
# 3. Run a program with arguments

wget -q -O file.txt "url"
gcc -o program file.c -l
./program arg1 arg2

1. Save the script as script.py:

# script.py

import subprocess

# This command downloads a file from the internet
subprocess.run(["wget", "-q", "-O", "file.txt", "url"])

# This command compiles a program
subprocess.run(["gcc", "-o", "program", "file.c", "-l"])

# This command runs a program with arguments
subprocess.run(["./program", "arg1", "arg2"])

2. Make the script executable:

chmod +x script.py

3. Run the script:

./script.py

4. Output:

The script will run the commands and record the output in a file named output.txt. The contents of the file will be:

Downloaded file.txt
Program compiled and executed successfully
Program ran with arguments arg1 and arg2

5. Modify the script as needed:

You can modify the script to perform different tasks, such as:

  • Downloading multiple files
  • Running multiple programs in parallel
  • Handling errors and logging them

Note:

  • The subprocess module requires the subprocess package to be installed. You can install it with the following command:
pip install subprocess
```
相似内容
更多>