欢迎访问宙启技术站
智能推送

使用Python脚本批量执行SH命令

发布时间:2024-01-19 20:54:42

在Python中,可以使用subprocess模块来执行Shell命令。subprocess模块提供了一个run()函数,可以方便地执行外部命令。下面是一个使用Python脚本批量执行Shell命令的例子:

import subprocess

# 定义一个函数来执行Shell命令
def execute_shell_command(command):
    # 使用subprocess.run函数执行Shell命令
    result = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    # 返回命令的执行结果
    return result.returncode, result.stdout.decode('utf-8'), result.stderr.decode('utf-8')

# 定义一个要执行的Shell命令列表
commands = [
    'echo "hello, world"',
    'ls',
    'pwd',
    # 可以执行复杂的Shell命令
    'for i in {1..10}; do echo $i; sleep 1; done'
]

# 遍历命令列表,依次执行每个命令
for command in commands:
    returncode, stdout, stderr = execute_shell_command(command)
    # 输出命令的执行结果
    print(f'Return code: {returncode}')
    print(f'Stdout: {stdout}')
    print(f'Stderr: {stderr}')
    print('---------------------')

上述例子中,首先定义了一个execute_shell_command()函数来执行Shell命令。然后定义了一个要执行的Shell命令列表commands,包含了一些简单的和复杂的Shell命令。接着,使用for循环遍历命令列表,并调用execute_shell_command()函数来执行每个命令,获取命令的执行结果并输出。

你也可以根据需要修改上述例子来适应实际情况。需要注意的是,由于subprocess.run()函数默认将shell参数设为False,因此在Linux或macOS系统中,如果要执行复杂的Shell命令(例如使用通配符或管道等),需要将shell参数设为True。在Windows系统中,由于使用的是cmd.exe作为默认的Shell,因此可以直接执行复杂的Shell命令,无需额外设置。

使用上述例子,你可以轻松地在Python脚本中批量执行Shell命令,并获取命令的执行结果。