0

In python2.7 we can execute external linux commands using subprocess package.

import subprocess   
subprocess.call(["ls", "-l"]) // or  
subprocess.call("ls -l".split())

both works. I have a file test.sh in current work directory which contains just

date

so I tried

>>> 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

What's wrong?
ADD(ANSWER) : This question and answer has enough information (but I'll leave my question here..) Calling the "source" command from subprocess.Popen

Chan Kim
  • 5,177
  • 12
  • 57
  • 112

1 Answers1

0

source is a shell builtin command. Python's subprocess module is provided to spawn new process, not running a proper Bourne shell (or zsh or ksh or etc.). You cannot access shel builtins from subprocess.call.

To determine if you can or not run a specific command with subprocess module, you may want to use which to get information about the command you need to use:

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
Antwane
  • 20,760
  • 7
  • 51
  • 84