【问题标题】:How to execute bunch of commands in one pipe using python?如何使用 python 在一个管道中执行一堆命令?
【发布时间】:2015-09-13 03:48:44
【问题描述】:

我有关于在 python 中执行命令的问题。 问题是: 在我们公司,我们购买了可以使用 GUI 或命令行界面的商业软件。我被分配了一项尽可能自动化的任务。首先,我考虑使用 CLI 而不是 GUI。但是后来我遇到了关于执行多个命令的问题。 现在,我想使用参数执行该软件的 CLI 版本并继续在其菜单中执行命令(我不是说再次使用 args 执行脚本。我想,一旦执行初始命令,它将打开菜单,我想在里面执行软件的命令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

【问题讨论】:

    标签: shell python-2.7 command-line command subprocess


    【解决方案1】:

    如果您想通过子进程的标准输入将命令传递给子进程,请设置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)?

    【讨论】:

    • 谢谢你兄弟!它帮助了我!
    猜你喜欢
    • 2017-05-05
    • 2013-06-17
    • 2019-01-16
    • 1970-01-01
    • 2020-03-08
    • 2018-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多