Search code examples
pythonsubprocesswindows-shell

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?


Solution

  • 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