繁体   English   中英

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

[英]Running multiple Terminal commands from Python File

所以我一直在搞乱我的 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)

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

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)

如果可以的话,通常也要避免使用 shell。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM