Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a Python subprocess call to invoke a Python script

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?

like image 491
user514946 Avatar asked Aug 22 '11 19:08

user514946


People also ask

What does subprocess call do in Python?

The Python subprocess call() function returns the executed code of the program. If there is no program output, the function will return the code that it executed successfully. It may also raise a CalledProcessError exception.

What is the difference between subprocess call and run?

I can say that you use subprocess. call() when you want the program to wait for the process to complete before moving onto the next process. In the case of subprocess. run() , the program will attempt to run all the processes at once, inevitably causing the program to crash.

How do I run a Python script from a program?

To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World!


1 Answers

If 'somescript.py' isn't something you could normally execute directly from the command line (I.e., $: somescript.py works), then you can't call it directly using call.

Remember that the way Popen works is that the first argument is the program that it executes, and the rest are the arguments passed to that program. In this case, the program is actually python, not your script. So the following will work as you expect:

subprocess.call(['python', 'somescript.py', somescript_arg1, somescript_val1,...]). 

This correctly calls the Python interpreter and tells it to execute your script with the given arguments.

Note that this is different from the above suggestion:

subprocess.call(['python somescript.py']) 

That will try to execute the program called python somscript.py, which clearly doesn't exist.

call('python somescript.py', shell=True) 

Will also work, but using strings as input to call is not cross platform, is dangerous if you aren't the one building the string, and should generally be avoided if at all possible.

like image 171
aruisdante Avatar answered Oct 09 '22 06:10

aruisdante