【问题标题】:Running multiple Terminal commands from Python File从 Python 文件运行多个终端命令
【发布时间】:2021-08-16 20:35:29
【问题描述】:

所以我一直在搞乱我的 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 采用命令的名称及其参数,而不是两个单独的命令按顺序运行。您需要使用subprocess.Popen 两次,cmd 的每个元素一次。

标签: python linux macos terminal


【解决方案1】:

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.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-13
    • 2018-02-12
    • 2018-05-04
    • 1970-01-01
    • 2019-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多