Using a Python subprocess call to invoke a Python

2019-01-08 20:49发布

I have a Python script that needs to invoke another Python script in the same directory. I did this:

from subprocess import call
call('somescript.py')

I get the following error:

call('somescript.py')
File "/usr/lib/python2.6/subprocess.py", line 480, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.6/subprocess.py", line 633, in __init__
errread, errwrite)
File "/usr/lib/python2.6/subprocess.py", line 1139, in _execute_child

raise child_exception
OSError: [Errno 2] No such file or directory

I have the script somescript.py in the same folder though. Am I missing something here?

9条回答
Bombasti
2楼-- · 2019-01-08 21:18

First, check if somescript.py is executable and starts with something along the lines of #!/usr/bin/python. If this is done, then you can use subprocess.call('./somescript.py').

Or as another answer points out, you could do subprocess.call(['python', 'somescript.py']).

查看更多
▲ chillily
3楼-- · 2019-01-08 21:19

subprocess.call expects the same arguments as subprocess.Popen - that is a list of strings (the argv in C) rather than a single string.

It's quite possible that your child process attempted to run "s" with the parameters "o", "m", "e", ...

查看更多
我想做一个坏孩纸
4楼-- · 2019-01-08 21:21

Check out this.

from subprocess import call 
with open('directory_of_logfile/logfile.txt', 'w') as f:
   call(['python', 'directory_of_called_python_file/called_python_file.py'], stdout=f)
查看更多
登录 后发表回答