我正在使用 python 执行一行 shell 脚本。它不能与 which
一起使用来测试自制软件的存在
#!/usr/bin/python
import sys, subprocess
subprocess.call(["which python"])
抛出长错误
Traceback (most recent call last):
File "installations.py", line 5, in <module>
subprocess.call(["which python"])
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 522, in call
return Popen(*popenargs, **kwargs).wait()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 709, in __init__
errread, errwrite)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1326, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
但我知道 shell 执行在某种程度上是正确的
#!/usr/bin/python
import sys, subprocess
subprocess.call(["whoami])
打印我的用户名就好了。我做错了什么,还是出于某种原因不受支持。是否有更好的支持方法来检测安装的存在?
最佳答案
失败的调用试图找到一个名为“which python”的可执行文件,它没有运行 which
,参数为 python
,这可能是您想要的。您传递给 call 的列表(除非设置了 shell=True
)是命令和所有参数的列表。做
subprocess.call(['which', 'python'])
可能会给你想要的东西。
关于执行shell脚本时出现Python错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30058650/