2

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

ok, its work for my, BUT why when i run proc = subprocess.Popen(['casperjs',os.path.join(basedir,'casper_script.js')], stdout=subprocess.PIPE) its return error
capserjs is install

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.