2

Say I have a Python 3 program like this:

print("Addition program")
num1 = int(input(">>> "))
num2 = int(input(">>> "))
print(num1 + num2)

I'm running it in the terminal and displaying the output with:

import subprocess

def run_command(command):
  p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  return iter(p.stdout.readline, b'')

for i in run_command(["python", "file.py"]): print(i)

How can I pass inputs to the program, either in the command itself, or while its running? Thanks in advance!

Edit: I found a solution that allows me to use pipes stdin and stdout. So I can pass input with stdin.write(b'. . . .'). However, once I use this command, I have to use the .communicate() method to obtain output or else the process hangs. Right now my code is:


import subprocess
from subprocess import PIPE
import shlex

p=subprocess.Popen(["python", "file.py"], stdin=PIPE, stdout=PIPE)


one_line_output = p.stdout.readline()
print(one_line_output.decode(), end = "")

p.stdin.write(b'a line\n')

one_line_output = p.communicate()[0] # end the process
print(one_line_output.decode(), end = "")

one_line_output = p.stdout.readline()
print(one_line_output.decode(), end = "")
'''
When this line of code runs, it raises an error:
Traceback (most recent call last):
  File ". . . .", line 27, in <module>
    one_line_output = p.stdout.readline()
ValueError: readline of closed file
'''

Is there a way I can continue to pass inputs and read lines?

1 Answer 1

1

Use the sys module:

import sys
print("Addition program")

num1 = sys.argv[0]
num2 = sys.argv[1]

print(num + num2)

Then you can execute the script passing the number arguments simply by:

python file.py 3 4
Sign up to request clarification or add additional context in comments.

1 Comment

No, I'm afraid that wont work. I dont want the input() to be removed, I'm trying to write a code editor, and I want the user to be able to either provide the inputs at the start of the program or provide inputs while the program is running

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.