![](/img/trans.png)
[英]Open a terminal in Python script and execute terminal commands in that newly opened terminal
[英]Send commands to the opened python terminal
目标是通过预先执行一些命令来打开python终端。 在现实生活中,它加载了一些模块并定义了一些变量,但这是一个简化版本:
from subprocess import Popen, CREATE_NEW_CONSOLE
r=Popen("python",creationflags=CREATE_NEW_CONSOLE)
r.communicate(input=b"print(2+2)")
使用 CREATE_NEW_CONSOLE,因为否则不会出现终端窗口(我从 IDE 运行代码)。 上面的代码打开了一个 python 终端窗口,但输入没有到达那里。 尝试一些变体会阻止窗口出现,例如:
r=Popen(["python","print(2+2)"],creationflags=CREATE_NEW_CONSOLE)
或者
r=Popen("python",creationflags=CREATE_NEW_CONSOLE, stdin=PIPE)
r.communicate(input=b"print(2+2)")
那么可以做些什么来解决这个问题呢?
这就是环境变量PYTHONSTARTUP
的作用......
请参阅: https : //docs.python.org/2/using/cmdline.html#envvar-PYTHONSTARTUP
另一种选择是使用-c
-i
开关
C:\>python -i -c "x = 2+2;y=3+3"
>>> x
4
>>> y
6
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.