1

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

Rohit Kumar Singh
  • 647
  • 1
  • 7
  • 17
  • Why do you need to start an interactive console and type commands in an automated way, instead just executing a Python script? – mkrieger1 Feb 08 '21 at 20:18
  • This way I can use another shell like vivado which can run TCL scripts automatically. Like open the vivado shell from python and then pass TCL commands to vivado shell for execution. – Rohit Kumar Singh Feb 08 '21 at 20:19
  • So you want to start another Python session and send commands to that to start Vivado and then send commands to that? Why not start Vivado directly? – mkrieger1 Feb 08 '21 at 20:21
  • And why write a Python script to send Tcl commands instead of writing a Tcl script? – mkrieger1 Feb 08 '21 at 20:23
  • I have to execute 100s of files and doing that manually would be cumbersome, so just wanted to check out this automation as a possibility. In this case, I would open vivado console from python script and pass TCL commands via python only. – Rohit Kumar Singh Feb 08 '21 at 20:23

1 Answers1

2

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)?

Rohit Kumar Singh
  • 647
  • 1
  • 7
  • 17