ivan
ivan

Reputation: 31

Python run command line

I'm trying to run a command line script. I have : command.py

import subprocess
proc = subprocess.Popen('python3 hello.py', stdout=subprocess.PIPE)
tmp = proc.stdout.read()
print(tmp)

and hello.py

print("hello")

but it returns error

FileNotFoundError: [WinError 2]

How can I run command and print result?

Upvotes: 2

Views: 742

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140287

The problem is that Popen cannot find python3 in your path.

If the primary error was that hello.py wasn't found, you would have this error instead in stderr (that is not read)

python: can't open file 'hello.py': [Errno 2] No such file or directory

You would not get an exception in subprocess because python3 has run but failed to find the python file to execute.

First, if you want to run a python file, it's better to avoid running it in another process.

But, if you still want to do that, it is better to run it with an argument list like this so spaces are handled properly and provide full path to all files.

import subprocess
proc = subprocess.Popen([r'c:\some_dir\python3',r'd:\full_path_to\hello.py'], stdout=subprocess.PIPE)
tmp = proc.stdout.read()
print(tmp)

To go further:

  • For python3, it would be good to put it in the system path to avoid specifying the full path.
  • as for the script, if it is located, say, in the same directory and the current script, you could avoid to hardcode the path

improved snippet:

import subprocess,os
basedir = os.path.dirname(__file__)
proc = subprocess.Popen(['python3',os.path.join(basedir,'hello.py')], stdout=subprocess.PIPE)
tmp = proc.stdout.read()
print(tmp)

Also: Popen performs a kind of execvp of the first argument passed. If the first argument passed is, say, a .bat file, you need to add the cmd /c prefix or shell=True to tell Popen to create process in a shell instead that executing it directly.

Upvotes: 2

Related Questions