python : windows : Subporcess open a .bat file in a new command window and run

Viewed 132

I have a bat file in which it runs a python file

test.bat

python test.py
pause

the python code file is

test.py

print("Hello World")

Now i want to use suprocess and open a windows command prompt and run the .bat file

i tried creating a python script with subprocess

test2.py

import subprocess
filepath=r"D:\test.bat"
subprocess.Popen([filepath], shell=True) 

Now I try to run this python file in command Promp and expecting another windows command prompt to open and run the test.py and pause, what i get is it does not open, but runs the bat file there itself

Microsoft Windows [Version 10.0.18363.1198]                                                                                                                     
(c) 2019 Microsoft Corporation. All rights reserved.                                                                                                            
                                                                                                                                                                
D:>python test2.py

D:>                                                                                                                                     
D:>python test.py                                                                                                                       
Hello World                                                                                                                                                     
                                                                                                                                                                
D:>pause                                                                                                                                
Press any key to continue . . . 
2 Answers

Try to launch a command in a new command interpreter:

filepath=r"cmd /K D:\test.bat"

You could make use of Windows's start command, which starts a separate Command Prompt window to run a specified program or command:

import subprocess
filepath=r"D:\test.bat"
subprocess.Popen("start {}".format(filepath), shell=True)
Related