如何使用 python 在一个管道中执行一堆命令?
How to execute bunch of commands in one pipe using python?
我在 python 中执行命令时遇到问题。
问题是:
在我们公司,我们购买了可以使用 GUI 或命令行界面的商业软件。我被分配了一项尽可能自动化的任务。首先,我考虑使用 CLI 而不是 GUI。但是后来我遇到了执行多个命令的问题。
现在,我想使用参数执行该软件的 CLI 版本,并继续在其菜单中执行命令(我不是说使用参数 again.I 执行脚本想要,一旦执行初始命令,它将打开菜单,我想执行软件的后台 Soft 菜单中的命令)。然后将输出重定向到变量。
我知道,我必须将 subprocess 与 PIPE 一起使用,但我没有管理它。
import subprocess
proc=subprocess.Popen('./Goldbackup -s -I -U', shell=True, stdout=subprocess.PIPE)
output=proc.communicate()[0]
proc_2 = subprocess.Popen('yes\r\n/dir/blabla/\r\nyes', shell=True, stdout=subprocess.PIPE)
# This one i want to execute inside first subprocess
如果您想通过标准输入将命令传递给子进程,请设置 stdin=PIPE
:
#!/usr/bin/env python
from subprocess import Popen, PIPE
proc = Popen('./Goldbackup -s -I -U'.split(), stdin=PIPE, stdout=PIPE,
universal_newlines=True)
output = proc.communicate('yes\n/dir/blabla/\nyes')[0]
见Python - How do I pass a string into subprocess.Popen (using the stdin argument)?
我在 python 中执行命令时遇到问题。 问题是: 在我们公司,我们购买了可以使用 GUI 或命令行界面的商业软件。我被分配了一项尽可能自动化的任务。首先,我考虑使用 CLI 而不是 GUI。但是后来我遇到了执行多个命令的问题。 现在,我想使用参数执行该软件的 CLI 版本,并继续在其菜单中执行命令(我不是说使用参数 again.I 执行脚本想要,一旦执行初始命令,它将打开菜单,我想执行软件的后台 Soft 菜单中的命令)。然后将输出重定向到变量。 我知道,我必须将 subprocess 与 PIPE 一起使用,但我没有管理它。
import subprocess
proc=subprocess.Popen('./Goldbackup -s -I -U', shell=True, stdout=subprocess.PIPE)
output=proc.communicate()[0]
proc_2 = subprocess.Popen('yes\r\n/dir/blabla/\r\nyes', shell=True, stdout=subprocess.PIPE)
# This one i want to execute inside first subprocess
如果您想通过标准输入将命令传递给子进程,请设置 stdin=PIPE
:
#!/usr/bin/env python
from subprocess import Popen, PIPE
proc = Popen('./Goldbackup -s -I -U'.split(), stdin=PIPE, stdout=PIPE,
universal_newlines=True)
output = proc.communicate('yes\n/dir/blabla/\nyes')[0]
见Python - How do I pass a string into subprocess.Popen (using the stdin argument)?