【发布时间】:2023-03-24 12:48:01
【问题描述】:
我有这个 bash 行:
$ printf ' Number of xml files: %s\n' `find . -name '*.xml' | wc -l`
Number of xml files: 4
$
当我以这种方式从 python 运行它时 python 解释器停止 并且我的终端 不再有标准输出::
$ ls
input aa bb
$ python
Python 3.6.7 (default, Oct 22 2018, 11:32:17)
>>>
>>> import subprocess
>>> cmd = "printf 'xml files: %s\n' `find . -name '*.xml' | wc -l`"
>>> subprocess.check_output(['/bin/bash', cmd], shell=True)
$ ls # stdout is not seen any more I have to kill this terminal
$
显然这里的问题不是如何让这个 bash 从 python:: 中工作。
>>> import subprocess
>>> cmd = "printf 'xml files: %s\n' `find . -name '*.xml' | wc -l`"
>>> out = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE)
>>> print(str(out.stdout, 'utf8'))
xml files: 4
>>>
以下两个问题No output from subprocess.check_output()和Why is terminal blank after running python executable?不回答问题
【问题讨论】:
-
试过原始输出?
cmd = r"printf 'xml files: ...\n"。因为这个\nchar 可能会阻塞shell -
为什么是
['/bin/bash', cmd]而不是['/bin/bash', '-c', cmd]?bash期望它的参数是一个文件。-c选项使其从参数中读取脚本。 -
为什么要 bash?这可以使用带有过滤器的
os.walk的纯python 来完成,然后打开文件并在行列表中使用len... -
另外,在有效的命令中,您根本没有使用
bash前缀。这两个是不等价的。 -
谢谢Jean-François,但问题不是 - 两个 cmd 是否等效,如何使 subprocess.check_output 行工作,但如何解释 1. python 退出到终端的事实2.终端没有插入任何标准输出
标签: python bash subprocess