繁体   English   中英

python子进程并传入shell参数

[英]python subprocess and passing in shell arguments

我正在尝试利用python的子进程来运行下载文件的命令,但是它需要一个参数才能继续。 如果我单独运行命令,它将提示您,如下所示:

./goro-new export --branch=testing --file=corp/goro.sites/test/meta.json

Finding pages .........
The following pages will be exported from Goro to your local filesystem:

  /goro.sites/test/meta.json -> /usr/local/home/$user/schools/goro.sites/test/meta.json

Export pages? [y/N]: y
Exporting 1 pages ..............................................................................................................   0%  0:00:03

Exported 1 pages in 3.66281s.

我的问题是,如何回答“导出页面”部分中的“是/否”? 我怀疑我需要将参数传递给子进程,但是我相对来说是python的新手,所以我希望获得一些帮助。 下面是我在python环境中测试的打印输出:

>>> import subprocess
>>> cmd = ['goro-new export --branch=test --file=corp/goro.sites/test/meta.json']
>>> p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,stderr=subprocess.PIPE, stdin=subprocess.PIPE)
>>> out, err = p.communicate()
>>> print out
Finding pages .... 
The following pages will be exported from Goro to your local filesystem:
/goro.sites/test/meta.json -> /var/www/html/goro.sites/test/meta.json
Export pages? [y/N]: 

如何传递“ y / N”以便继续进行?

您可以使用已在使用的函数communicate() -函数,并将所需的内容作为input参数传递。 我无法验证此方法是否有效,但应该可以给您一个提示:

>>> import subprocess
>>> cmd = ['goro-new export --branch=test --file=corp/goro.sites/test/meta.json']
>>> p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,stderr=subprocess.PIPE, stdin=subprocess.PIPE)
>>> out, err = p.communicate(input="y")
>>> print out

最简单的方式做到这一点,如果你总是想是的(这我假设你这样做)是一些bash的回答: yes | python myscript.py yes | python myscript.py 要直接在python中执行此操作,可以使用stdout=subprocess.PIPE yes.stdout创建一个新的subprocess.Popen (例如,称为yes ),并将pstdin设置为yes.stdout 参考: 带管道的Python子过程命令

暂无
暂无

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

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