Python subprocess.call使用linux源命令[duplicate]引发OSError

问题描述 投票:0回答:1

这个问题在这里已有答案:

在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(答案):这个问题和答案有足够的信息(但我会在这里留下我的问题..)Calling the "source" command from subprocess.Popen

python subprocess
1个回答
0
投票

source is a shell builtin command。 Python的subprocess module用于生成新进程,而不是运行适当的Bourne shell(或zsh或ksh等)。你不能从subprocess.call访问shel builtins。

要确定是否可以使用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
© www.soinside.com 2019 - 2024. All rights reserved.