Reputation: 669
What I need here is opening a python console from python script and then pass commands to that python console.
I need to automate this process. Currntly I am using os.system and subprocess to open the python console but after that I am totally stuck with passing print("Test")
to python console.
Here is the sample code which I am working on.
import os
os.system("python")
#os.system("print('Hello World'))
# or
import subprocess
subprocess.run("python", shell = True)
Please help me to understand how I can pass the nested commands. Thanks
Upvotes: 1
Views: 351
Reputation: 669
I have found a very helpful answer from another thread and applied to my use case.
from subprocess import run, PIPE
p = run(['python'], stdout=PIPE,
input='print("Test")\nprint("Test1")\nimport os\nprint(os.getcwd())', encoding='ascii')
print(p.returncode)
# -> 0
print(p.stdout)
It starts the python shell and then executes the following commands separated by \n
.
Reference : How do I pass a string into subprocess.Popen (using the stdin argument)?
Upvotes: 2