Skip to content Skip to sidebar Skip to footer

How Can I Get Python To Start A Command Prompt Session And Run Commands In It?

I am trying to get my python app to start a command prompt session and run commands in it. I have been successful in getting it to start a cmd session, but I cannot make it run com

Solution 1:

I am trying to get my python app to start a command prompt session and run commands in it.

If I understand you correct, you're trying to send commands to a shell like it was typed on the keyboard.

To achieve that, you need

  • start the shell process
  • determine input and output streams of the shell process
  • write and read some data to that streams

I'm not familiar with CMD shell and Windows, but here's the example how it could be done on linux with ZSH:

In [48]: import subprocess, time
    ...:
    ...:
    ...: defmain():
    ...:     with subprocess.Popen(['/usr/bin/zsh'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, bufsize=1) as proc:
    ...:         proc.encoding = 'utf-8'
    ...:         proc.text_mode = True
    ...:         proc.universal_newlines = True
    ...:         COMMAND = 'echo "Hello From Python! Current shell is \"$SHELL\"!"\r\n'
    ...:
    ...:         print('Sending command:', proc.pid, '\n<<<', repr(COMMAND))
    ...:
    ...:         proc.stdin.writelines([COMMAND.encode()])
    ...:         proc.stdin.flush()
    ...:
    ...:         print('Receiving outputs:', proc.pid, '\n>>>', end=' ')
    ...:         raw = proc.stdout.readline()
    ...:         res = raw.decode()
    ...:         print(repr(res))
    ...:
    ...:         proc.terminate()
    ...:
    ...: main()
Sending command: 1250722
<<< 'echo "Hello From Python! Current shell is "$SHELL"!"\r\n'
Receiving outputs: 1250722>>> 'Hello From Python! Current shell is /usr/bin/zsh!\r\n'

If you need to go deeper, please take a look at this answer: Understanding Popen.communicate

Post a Comment for "How Can I Get Python To Start A Command Prompt Session And Run Commands In It?"