Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using subprocess.run to run a process on Windows

I wish to run the following very lengthy shell command via Python:

C:/Users/Alex/Desktop/tableexporter/WGTableExporter.exe "E:/Steam (Games Installed Directly to Hard Drive)/steamapps/common/Wargame Red Dragon/Data/WARGAME/PC/430000626/NDF_Win.dat" pc\ndf\patchable\gfx\everything.ndfbin TAmmunition

When I run this as-is from the Windows shell, it works as expected.

However, when I attempt to do the same via Python's subprocess.run, it doesn't like it. Here is my input:

import subprocess
comm = [r'C:/Users/Alex/Desktop/tableexporter/WGTableExporter.exe "E:/Steam (Games Installed Directly to Hard Drive)/steamapps/common/Wargame Red Dragon/Data/WARGAME/PC/430000626/NDF_Win.dat" pc\ndf\patchable\gfx\everything.ndfbin TAmmunition']
subprocess.run(comm, shell=True)

Here is my output:

The directory name is invalid.
Out[5]: CompletedProcess(args=['C:/Users/Alex/Desktop/tableexporter/WGTableExporter.exe "E:/Steam (Games Installed Directly to Hard Drive)/steamapps/common/Wargame Red Dragon/Data/WARGAME/PC/430000626/NDF_Win.dat" pc\\ndf\\patchable\\gfx\\everything.ndfbin TAmmunition'], returncode=1)

Why does this occur?

like image 299
Aleksey Bilogur Avatar asked Jun 20 '26 10:06

Aleksey Bilogur


2 Answers

The spacing is wrong. subprocess is expecting a list of arguments which it will space out correctly for you.

comm = ['C:/Users/Alex/Desktop/tableexporter/WGTableExporter.exe','E:/Steam (Games Installed Directly to Hard Drive)/steamapps/common/Wargame Red Dragon/Data/WARGAME/PC/430000626/NDF_Win.dat','pc\ndf\patchable\gfx\everything.ndfbin','TAmmunition']

The reason you are getting the error is because of the doublequotes around e:/steam... It's writing something like this to a shell:

c:/users/alex/desktop/tableexporter/wgtableexporter.exe \"E:/Steam (Games Installed Directly to Hard Drive)/steamapps/common/Wargame Red Dragon/Data/WARGAME/PC/430000626/NDF_Win.dat\" pc\ndf\patchable\gfx\everything.ndfbin TAmmunition
like image 175
Back2Basics Avatar answered Jun 23 '26 00:06

Back2Basics


The spacing is incorrect, however using os.system() will not require you to change spacing.

This should work:

import os
os.system("""C:/Users/Alex/Desktop/tableexporter/WGTableExporter.exe      "E:/Steam (Games Installed Directly to Hard Drive)/steamapps/common/Wargame Red Dragon/Data/WARGAME/PC/430000626/NDF_Win.dat" pc\ndf\patchable\gfx\everything.ndfbin TAmmunition""")

However if you want to use subprocess (which is better)

import subprocess
comm = ['C:/Users/Alex/Desktop/tableexporter/WGTableExporter.exe','E:/Steam (Games Installed Directly to Hard Drive)/steamapps/common/Wargame Red Dragon/Data/WARGAME/PC/430000626/NDF_Win.dat','pc\ndf\patchable\gfx\everything.ndfbin TAmmunition']
subprocess.run(comm, shell=True)
like image 32
Byron Filer Avatar answered Jun 23 '26 01:06

Byron Filer