Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
499 views
in Technique[技术] by (71.8m points)

subprocess - 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]

question from:https://stackoverflow.com/questions/65642923/python-shell-execution-programatically

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
")
res.stdin.write(b"print(a)")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...