Is there any way to pass values to input prompt to the python script which was called by other python script?

Viewed 1489

For better understanding,

example2.py

    a = raw_input("Enter 1st number: ")
    b = raw_input("Enter 2nd number: ")
    *some code here*
    c = raw_input("Enter 3rd number: ")
    s = a+b+c
    print(s)

example1.py

    import os
    os.system('python example2.py')
    <need logic to address the input prompts in example2.py>
    <something to pass like **python example2.py 1 2 3**>

I guess by looking at these scripts you can get it what I'm looking for? Let me explain it once for a better understanding. There are two files example1.py and example2.py. Now, I called example1.py from my shell, which in turn called the other script and waiting for the input.

Notes:

  • I can't do anything on example2.py, which is not owned by me.
  • I'm limited to do changes on example1.py and pass arguments to example1.py
  • I know there will be a process created for example2.py, but not sure about passing these arguments to process IO.
  • Actual code was different, I crafted example1.py and example2.py for the sake of understanding.

I couldn't grasp any ideas from these links:

Launch a python script from another script, with parameters in subprocess argument

how to execute a python script file with an argument from inside another python script file

Please share your thoughts on this and help me to resolve this. Please don't mind editing the question if it requires. I'm completely new to the module os, subprocess.

3 Answers

Consider the file to run:

a = int(input("Enter 1st number: "))
b = int(input("Enter 2nd number: "))
# code
c = int(input("Enter 3rd number: "))
s = a+b+c
print(s)

You can run this file from python using the subprocess module.

import subprocess

proc = subprocess.Popen(['python', 'a.py'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
out, _ = proc.communicate(bytes("1\n2\n3\n", "utf-8"))
print(out.decode('utf-8'))

Which results in:

Enter 1st number: Enter 2nd number: Enter 3rd number: 6

Read the docs & examples here for more details.

I've upgraded the code to python3 since python2 is EOL.

P.S: I've used shell=True here for convenience - but you probably shouldn't

Starting with Python 3, raw_input() was renamed to input().

you can use int ( input ( ) ) in example 2

One simple way is to use stdout from one script to feed values into another. Here is an example using python, the pipe "|" command and stdout. The pipe command redirects output from a file and uses it as input to the next file in the chain

python example1.py | example2.py

Output from code:

Enter 1st number: number is 1
Enter 2nd number: number is 2

example1.py code:

print(1)
print(2)

example2.py code:

a = input("Enter 1st number: ")
print("number is",a)

b = input("Enter 2nd number: ")
print("number is",b)

Reference: https://www.geeksforgeeks.org/piping-in-unix-or-linux/

Related