Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to output to command line when running one python script from another python script

Tags:

python-2.7

I have multiple python scripts, each with print statements and prompts for input. I run these scripts from a single python script as below.

os.system('python script1.py ' + sys.argv[1])
os.system('python script2.py ' + sys.argv[1]).....

The run is completed successfully, however, when I run all the scripts from a single file, I no longer see any print statements or prompts for input on the run console. Have researched and attempted many different ways to get this to work w/o success. Help would be much appreciated. Thanks.

like image 628
O. Patel Avatar asked Jul 02 '26 08:07

O. Patel


1 Answers

If I understand correctly you want to run multiple python scripts synchronously, i.e. one after another.

You could use a bash script instead of python, but to answer your question of starting them from python...

Checkout out the subprocess module: https://docs.python.org/3.4/library/subprocess.html

In particular the call method, it accepts a stdin and stdout which you can pass sys.stdin and sys.stdout to.

import sys
import subprocess

subprocess.call(['python', 'script1.py', sys.argv[1]], stdin=sys.stdin, stdout=sys.stdout)
subprocess.call(['python', 'script2.py', sys.argv[1]], stdin=sys.stdin, stdout=sys.stdout)

^ This will work in python 2.7 and 3, another way of doing this is by importing your file (module) and calling the methods in it. The difference here is that you're no longer running the code in a separate process.

subroutine.py

def run_subroutine():
    name = input('Enter a name: ')
    print(name)

master.py

import subroutine
subroutine.run_subroutine()
like image 81
Steve Avatar answered Jul 05 '26 17:07

Steve



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!