在python2.7中,我们可以使用子进程包执行外部linux命令。
import subprocess
subprocess.call(["ls", "-l"]) // or
subprocess.call("ls -l".split())
两者都有效。我在当前工作目录中有一个文件test.sh,其中仅包含
date
所以我尝试了
>>> subprocess.call("pwd".split())
/home/ckim
0
>>> subprocess.call("cat test.sh".split())
date
0
>>> subprocess.call("source test.sh".split())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/subprocess.py", line 523, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.7/subprocess.py", line 711, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1343, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
怎么了?
ADD(ANSWER):此问题和答案具有足够的信息(但我将在此处保留我的问题。)Calling the "source" command from subprocess.Popen
答案 0 :(得分:0)
source
is a shell builtin command。提供Python的subprocess module是为了产生新进程,而不是运行适当的Bourne shell(或zsh或ksh等)。您无法从subprocess.call
访问shel内置函数。
要确定是否可以使用subprocess
模块运行特定命令,可能需要使用which
来获取有关需要使用的命令的信息:
user@machine: ~
$ which source [7:41:38]
source: shell built-in command
user@machine: ~
$ which cat [7:41:42]
/bin/cat
user@machine: ~
$ which ls [7:41:47]
ls: aliased to ls --color=tty