简体   繁体   English

向打开的python终端发送命令

[英]Send commands to the opened python terminal

The goal is to open python terminal with pre-execution of some commands.目标是通过预先执行一些命令来打开python终端。 In real life it's loading some modules and defines some variables, but here is a simplified version:在现实生活中,它加载了一些模块并定义了一些变量,但这是一个简化版本:

from subprocess import Popen, CREATE_NEW_CONSOLE

r=Popen("python",creationflags=CREATE_NEW_CONSOLE)
r.communicate(input=b"print(2+2)")

CREATE_NEW_CONSOLE is used, because otherwise terminal window doesn't appear (I run the code from IDE).使用 CREATE_NEW_CONSOLE,因为否则不会出现终端窗口(我从 IDE 运行代码)。 The code above opens a python terminal window, but input doesn't get there.上面的代码打开了一个 python 终端窗口,但输入没有到达那里。 Trying some variations stops window from appearing, like:尝试一些变体会阻止窗口出现,例如:

r=Popen(["python","print(2+2)"],creationflags=CREATE_NEW_CONSOLE)

Or或者

r=Popen("python",creationflags=CREATE_NEW_CONSOLE, stdin=PIPE)
r.communicate(input=b"print(2+2)")

So what can be done to solve the problem?那么可以做些什么来解决这个问题呢?

this is what the environmental variable PYTHONSTARTUP is for...这就是环境变量PYTHONSTARTUP的作用......

see: https://docs.python.org/2/using/cmdline.html#envvar-PYTHONSTARTUP请参阅: https : //docs.python.org/2/using/cmdline.html#envvar-PYTHONSTARTUP

在此处输入图片说明

another option would be to use the -c -i switches另一种选择是使用-c -i开关

C:\>python -i -c "x = 2+2;y=3+3"
>>> x
4
>>> y
6
>>>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM