运行 subprocess.call 来自 python 脚本
Running subprocess.call from python script
我有一个功能,我需要在 python 脚本中 运行 命令。从另一个答案来看,我认为 call from subprocess module
是最安全的方法。但是,我无法解决它。我正在使用 python 2.7
这是我正在尝试的较小版本:
import subprocess
a = "echo hello"
subprocess.call([a])
它给我以下错误:
subprocess.call([a])
File "/usr/lib/python2.7/subprocess.py", line 522, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.7/subprocess.py", line 710, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1327, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
我想不通为什么!
您编写的代码有问题,subprocess.call 接受一个列表,其中列表的第一个元素是命令。在您的情况下,它是 echo
并且 hello
是您的参数,它应该是列表中的下一个值。所以你的代码应该是这样的。
import subprocess
a = [ "echo","hello"]
subprocess.call(a)
您可以将命令作为 string 或 list 传递,但不能作为列表中的字符串传递,否则系统会尝试运行 echo hello
进程(显然不存在,这解释了 OSError: [Errno 2] No such file or directory
错误消息)。在某些系统上将其作为字符串传递需要 shell=True
。
并且 shell=True
也需要 shell 内置命令,例如 echo
命令(在某些系统上 /bin
中有非内置版本,只是为了增加混乱)
import subprocess
subprocess.call(["echo","hello"],shell=True)
对于非内置命令(我假设 echo
只是一个测试),避免 shell=True
,因为它添加了一个不必要的 shell 层,这会降低启动性能,并且容易代码注入(echo hello; rm -rf everything_on_disk)
例如运行你最喜欢的编辑器,你可以这样做:
subprocess.call(["emacs","readme.txt"])
我有一个功能,我需要在 python 脚本中 运行 命令。从另一个答案来看,我认为 call from subprocess module
是最安全的方法。但是,我无法解决它。我正在使用 python 2.7
这是我正在尝试的较小版本:
import subprocess
a = "echo hello"
subprocess.call([a])
它给我以下错误:
subprocess.call([a])
File "/usr/lib/python2.7/subprocess.py", line 522, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.7/subprocess.py", line 710, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1327, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
我想不通为什么!
您编写的代码有问题,subprocess.call 接受一个列表,其中列表的第一个元素是命令。在您的情况下,它是 echo
并且 hello
是您的参数,它应该是列表中的下一个值。所以你的代码应该是这样的。
import subprocess
a = [ "echo","hello"]
subprocess.call(a)
您可以将命令作为 string 或 list 传递,但不能作为列表中的字符串传递,否则系统会尝试运行 echo hello
进程(显然不存在,这解释了 OSError: [Errno 2] No such file or directory
错误消息)。在某些系统上将其作为字符串传递需要 shell=True
。
并且 shell=True
也需要 shell 内置命令,例如 echo
命令(在某些系统上 /bin
中有非内置版本,只是为了增加混乱)
import subprocess
subprocess.call(["echo","hello"],shell=True)
对于非内置命令(我假设 echo
只是一个测试),避免 shell=True
,因为它添加了一个不必要的 shell 层,这会降低启动性能,并且容易代码注入(echo hello; rm -rf everything_on_disk)
例如运行你最喜欢的编辑器,你可以这样做:
subprocess.call(["emacs","readme.txt"])