以编程方式执行 Python shell

问题描述

我需要以编程方式在 shell 上运行时运行 python 命令,它几乎是复制 REPL 但以编程方式,我尝试了下面的代码,该代码适用于第一行,但它不像 CLI 那样承载会话,请帮忙

enter image description here

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

错误

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

我收到错误,因为这 2 个命令正在 2 个不同的进程中执行,有什么方法可以在一个进程中运行但在不同的行中运行(类似于我们在 python 解释器(REPL)中所做的),我正在工作关于从一些外部文件捕获python命令并在shell上运行它们的要求,所以在它实际出现在外部文件中之前我不知道我将执行什么命令。

[![在此处输入图片描述][2]][2]

解决方法

您可以使用 Popensubprocessstdin 正在等待您的命令。

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