Rohit Kumar Singh
Rohit Kumar Singh

Reputation: 669

How to pass python commands after opening a python console from a python script?

What I need here is opening a python console from python script and then pass commands to that python console.

enter image description here

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

Answers (1)

Rohit Kumar Singh
Rohit Kumar Singh

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.

  1. Prints Test
  2. Prints Test1
  3. Imports OS
  4. Get the current working directory.

enter image description here

Reference : How do I pass a string into subprocess.Popen (using the stdin argument)?

Upvotes: 2

Related Questions