1

Python 3.6.7, Windows 7/10

I have to run two commands one after the other using subprocess.run. The first command opens a new command prompt. The next command needs to be run in the newly created command prompt. With the code below, the second command always runs in the initial command prompt. Can this be done?

import subprocess

subprocess.run('first command', shell=True)  #first command opens a new command prompt
subprocess.run('second command', shell=True)  #second command needs to be run in the newly created command prompt
ontherocks
  • 1,747
  • 5
  • 26
  • 43
  • 1
    You are creating two completely independent subprocesses. You want to feed the commands to the first subprocess as input somehow, though on Windows that probably requires sacrificing a virgin and holding your feet whilst standing on your head. – tripleee Feb 26 '19 at 14:45

2 Answers2

1

It depends on which commands you want to run but I think one solution would be to create a batch script running those two commands one after the other.

Or you could try to write the second command on the stdin of your first subprocess with something like :

pipe = subprocess.Popen('first command', shell=True, stdin=subprocess.PIPE)
pipe.communicate(input='second command')

but I am not sure that would works since the process will finish right after the first command termination ?

EDIT: add indentation

Viper
  • 405
  • 3
  • 11
  • Please, indent your code lines. (add 4 whitespaces) – Adam Bellaïche Feb 26 '19 at 15:01
  • @Viper I tried your suggestion. Unfortunately, the second command doesn't get executed in the new command prompt. One change I had to do was add encoding='utf8' to subprocess.Popen – ontherocks Feb 26 '19 at 16:21
  • Yes that's what I thought. One solution would be use subprocess just to launch cmd and then write your command to it. You can check here for more details : https://stackoverflow.com/questions/39721924/how-to-run-multiple-commands-synchronously-from-one-subprocess-popen-command – Viper Feb 27 '19 at 13:47
0

Why don't you pipe the commands?

subprocess.run('first command | second command', shell=True)
Lucas Azevedo
  • 1,867
  • 22
  • 39