1

Recently , i wrote the following code to run a python file 'file1.py' from another python code. I am working on raspberry pi (with raspian )

Python code:

    import subprocess
    subprocess.Popen(['python','./file1.py'])
    print 'Done'

Output:

    Done

file1.py does not executed,No other response on screen

file1.py

    a=5
    a=a+5
    print(a)

I have searched for the somewhat same question ,but it's not working for me. Please help!

Running multiple Python scripts

Community
  • 1
  • 1
AMG
  • 11
  • 3
  • 1
    Why are you using `subprocess.Popen()` to run the other script? Can you not just import and run it normally – SiHa Jul 06 '16 at 08:02
  • Possible duplicate of [python getoutput() equivalent in subprocess](http://stackoverflow.com/questions/6657690/python-getoutput-equivalent-in-subprocess) – SiHa Jul 06 '16 at 08:15
  • Hi @amratansh-gupta, why don't you use a shebang inside of the file `file1.py`? – Andy K Jul 06 '16 at 08:44
  • what happens if you replace `subprocess.Popen` with `subprocess.check_call`? – jfs Jul 08 '16 at 01:07

2 Answers2

1

Popen forks the current process, which means you won't see its output simply by printing in the executed script.

You will need to redirect its output:

p = subprocess.Popen(['python','./file1.py'], stdout=subprocess.PIPE)
print(p.stdout.read())
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
  • thank you very much, it's working. However if my file1.py needs input values from the user , in that case how can i modify this so that i will be able to input the required data? – AMG Jul 06 '16 at 09:53
0
p=subprocess.Popen(["python","1st.py"],stdin=PIPE,stdout=PIPE)
print p.communicate()[0]

OR

print(p.stdout.read())

Communicate() will retrieve the last processed process output that will help to see the results

sathish
  • 149
  • 9