2

The goal is to open python terminal with pre-execution of some commands. 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). The code above opens a python terminal window, but input doesn't get there. 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?

Nik
  • 371
  • 1
  • 4
  • 10
  • Well, the second and third examples open and close very quickly. Are you trying to pipe something to stdin but also attached have stdin attached to the terminal? – Josh Lee Jan 31 '17 at 20:43
  • If I understand your question right, the main idea is to remotely launch multiple commands to terminal without closing the window. All of above tried to achieve that. – Nik Jan 31 '17 at 20:49
  • https://stackoverflow.com/questions/30494945/createprocess-with-new-console-window-but-override-some-std-i-o-handles – Josh Lee Jan 31 '17 at 21:04
  • I can't even get `C:/msys64/usr/bin/cat.exe` to copy its stdin to the console by using Popen in this way. I strongly suspect that the question I linked is related. – Josh Lee Jan 31 '17 at 21:10
  • Does that mean the STARTUPINFO could be changed somehow to accept input from communicate method? Anyway, fortunately the accepted answer does what I want in a simpler way. – Nik Jan 31 '17 at 21:19
  • Probably the problem stemmed from trying to have both console and original program as input channels. I'm not sure whether you can do that at the same time. – Nik Jan 31 '17 at 21:34

1 Answers1

2

this is what the environmental variable PYTHONSTARTUP is for...

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

enter image description here

another option would be to use the -c -i switches

C:\>python -i -c "x = 2+2;y=3+3"
>>> x
4
>>> y
6
>>>
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179