Search code examples
pythonsubprocesscommand-line-interfaceread-eval-print-loop

Python shell execution programatically


I have a requirement to run python commands at run on shell programmatically, its almost replicating REPL but programmatically, I tried below code which worked for the first line but it's not carrying the session the way CLI does, kindly help

enter image description here

import subprocess as s
import sys
res=s.run([sys.executable, "-c", "a=5"])
s.run([sys.executable, "-c", "print(a)"])

Error:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
NameError: name 'a' is not defined

I am getting the error as those 2 commands are being executed in 2 different processes, is there any way to run in one process but in different lines(Similar to what we do in python interpreter(REPL)), I am working on the requirement to capture python commands from some external files and run them on the shell, so I won't know what command I will be executed until it actually appears in an external file.

[![enter image description here][2]][2]


Solution

  • You can use Popen of subprocess. stdin is waiting your commands.

    import subprocess as s
    import sys
    res=s.Popen(sys.executable, stdin=s.PIPE)
    res.stdin.write(b"a=5\n")
    res.stdin.write(b"print(a)")