我想在Python脚本中检查Bash命令的结果。我在用subprocess.check_output()。
在此之前,我手动检查了shell中两个命令的结果:
user@something:~$ hostname
> something
user@something:~$ command -v apt
> /usr/bin/apt它如预期的那样工作。现在,我试图在Python解释器中运行subprocess.check_output()函数:
>>> import subprocess
>>> subprocess.check_output(['hostname'], shell=True, stderr=subprocess.STDOUT)
b'something\n'
>>> subprocess.check_output(['command', '-v', 'apt'], shell=True, stderr=subprocess.STDOUT)
b''如您所见,第一个命令按预期工作,但第二个命令不工作(因为它返回一个空字符串)。为什么会这样呢?
编辑
我已经尝试删除shell=True,它返回一个错误:
>>> subprocess.check_output(['command', '-v', 'apt'], stderr=subprocess.STDOUT)
Traceback (most recent call last):
[...]
FileNotFoundError: [Errno 2] No such file or directory: 'command'发布于 2017-10-17 08:42:38
从参数中删除shell=True:
>>> subprocess.check_output(['command', '-v', 'apt'], stderr=subprocess.STDOUT)
'/usr/bin/apt\n'见Actual meaning of 'shell=True' in subprocess。
如果
shell是True,则建议将args作为字符串而不是序列传递。
这可以确保命令的格式正确,就像在shell中直接键入命令一样:
>>> subprocess.check_output('command -v apt', shell=True, stderr=subprocess.STDOUT)
'/usr/bin/apt\n'但是,通常不鼓励使用shell。
https://stackoverflow.com/questions/46785924
复制相似问题