简体   繁体   中英

Subprocess to open python file and return data

I am trying to use Python to open another file. This file is going to start up a socket and create threads for listening for additional connections, and threads for sending/receiving data. The main thread will not return.

However, if the setup of sockets fail, I want to return a error code to the other python script that executed the subprocess.

main.py

py3output = subprocess.check_output(['python3', 'py3.py'])
print('py3 said:' + str(py3output))

py3.py

def returnme():
    return 10

returnme()

When I run this, it prints:

py3 said:b''

I am just trying to figure out how to get the return value back to the main calling program.

To return an exit code n back to the OS, you need sys.exit(n) . But seems like you do not want to check the exit code but the stdout otput. So your program might need to rewrite to:

def returnme():
    return 10

print(returnme())

You should only return a string as a standard output using following code:

sample.py


import sys

def returnme():
      sys.stdout.write(str(10))
      sys.stdout.flush()

returnme()

main.py


from subprocess import check_output

output = check_output(['python','sample.py'])
print('Sample.py says :' + output)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM