从 Python 文件运行多个终端命令

时间:2021-05-28 15:17:04

标签: python linux macos terminal

所以我一直在我的 MacOS 上尝试从 Python 文件中运行终端命令。以下是我目前使用的代码:

#!/usr/bin/env python3
import os
import subprocess

print("IP Configuration for Machine")
cmd = ['ifconfig']
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

o, e = proc.communicate()
print('OUTPUT: ' + o.decode('ascii'))
print('ERROR: '  + e.decode('ascii'))
print('CODE: ' + str(proc.returncode))

当我打算只运行一个终端命令时,它工作得很好。现在我打算运行多个一个,但到目前为止它一直给我错误。我尝试的一个例子:

print("IP Configuration for Machine & List Directory")
cmd = ['ifconfig', 'ls']
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

我想知道是否有办法解决我的困境

1 个答案:

答案 0 :(得分:0)

Popen 的参数是要执行的一个命令的名称。要运行 reveral,请运行多个子进程(或运行一个运行多个子进程,即一个 shell)。

顺便说一下,如果您只需要运行一个进程并等待它完成,则可能避免使用裸 Popen

for cmd in ['ifconfig', 'ls']:
    p = subprocess.run(cmd, capture_output=True, check=True, text=True)
    print('output:', p.stdout)
    print('error:', p.stderr)
    print('result code:', p.returncode)

p = subprocess.run('ifconfig; ls', shell=True, check=True, capture_output=True, text=True)
print(p.stdout, p.stderr, p.returncode)

但通常avoid a shell if you can, too.