'How do I make the code which execute the python file (not itself) with input redirection?
I want to make call.py which execute main.py with input redirection of input.txt.
In addition to that,I don't want to change the code of main.py.
What I want to do is like below.
call.py
exec(open("./main.py").read() < input.txt)
Of course I know that this code doesn't work.
main.py
name=input()
x=int(input())
print(name +" has chosen "+str(x)+".")
input.txt
Alice
2
Please give me the advice for it.
Solution 1:[1]
You can use the subprocess
module for this. A sample usage is shown below.
In call.py:
proc = subprocess.Popen( "main.py input.txt", stdout = subprocess.PIPE, stderr = subprocess.PIPE )
All you have to do in main.py is read the contents of input.txt by using the sys
module. To fetch input.txt from the command line, use sys.argv[1]
.
Solution 2:[2]
Just writing this is enough:
os.system('main.py < input.txt')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Joeypencil |
Solution 2 | vinzee |