0

using python 3.7

I have the following issue: I wrote a python script in which I open a cmd prompt, do some actions then I want to send some commands to that opened cmd prompt

To simplify, it looks something like:

import subprocess
process = subprocess.Popen(['start','cmd','/k','dir'], shell = True, stdin= subprocess.PIPE, 
stdout = subprocess.PIPE, text = True)

"DO some actions"

input = 'date'
process.stdin.write(input)
process.communicate(input, timeout = 10)

All the time the script exits with exception TimeoutExpired , and in the cmd prompt i do not see command written (the input)

I looked in the documentation, but i am new with python and did not understood very well how to use the subprocess module

Thank you for the support!

6
  • Why do you start the process? What do you run there? Commented Sep 30, 2021 at 13:59
  • Two problems here: 1) by indirectly launching cmd via start, you create a command window that you have no control over; 2) since you didn't end the "date" string with a newline, you haven't actually executed a command. Commented Sep 30, 2021 at 14:07
  • Hi Balderman, The idea is that i have to open a .exe file and on different timmings i have to write on the opened window some commands. I simplified the question with the example with the cmd prompt i which i first send a dir command and afte that i want to send a new command(date) to the same cmd window. I do not know how to do this. Commented Sep 30, 2021 at 14:21
  • Hi @jasonharper, is there a way to have control on that cmd window ? Commented Sep 30, 2021 at 14:25
  • Yes, by launching cmd directly, rather than asking start to launch it for you. Commented Sep 30, 2021 at 14:29

1 Answer 1

1

If you want to write something like date in another cmd tab, do like this:

import subprocess
input = 'date'
subprocess.Popen(['start','cmd','/k','echo',input], shell = True, stdin = subprocess.PIPE, stdout = subprocess.PIPE, text = True)

Result:
enter image description here

Sign up to request clarification or add additional context in comments.

3 Comments

Hi Behdad, the second command input ('date') is not send to the opned command prompt. in The command prompt you see only the result of the dir command. Also i run the code from IDE not in the cmd prompt.
I've updated my answer, please check it @Costi
Hi @Behdad, it is not what i want. My script will open the cmd prompt, i will do some operation and then i want to send some commands to that open cmd prompt.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.