mino
mino

Reputation: 7298

Python Subprocess - Doesn't return anything

I've seen on here a few other issues running subprocesses with Python, but none have solved the issue I'm having at the moment. Relatively new to Python, so just playing around and I'm sure it's a simple solution.. But I just can't make it work!

I want a subprocess to return some data, and it isn't. So I wrote this basic example to try and get it working but it still isn't. Where am I going wrong? I'm getting no errors or anything, it's just not doing anything.

sp_test.py

import os
import subprocess

def main():
    subp = subprocess.check_call(['python', 'sp.py'])
    print subp


if __name__ == '__main__':
    main()

and...

sp.py

def do_something():
    return "Hello World!"


do_something()

exit()

Upvotes: 0

Views: 431

Answers (1)

Gohn67
Gohn67

Reputation: 10648

There are two issues with your implementation.

1.

check_call only returns the returncode of 0 or throws an exception otherwise. (See https://docs.python.org/2/library/subprocess.html#subprocess.call)

2.

Also you are trying to capture the the value of Hello World! by simply returning a value. That won't work using subprocess. If you want to do that, you may want to look into something like Pyro4 (https://pythonhosted.org/Pyro4/intro.html)


Here is one solution if you want to use subprocess still.

First you can use check_output (https://docs.python.org/2/library/subprocess.html#subprocess.check_output). This will capture any output from your subprocess.

Then in your sp.py program, you will need to print the result do_something.

sp_test.py

import os
import subprocess

def main():
    subp = subprocess.check_output(['python', 'sp.py'])
    print subp

if __name__ == '__main__':
    main()

sp.py

def do_something():
    return "Hello World!"


print do_something()

exit()

Upvotes: 1

Related Questions