Aleksey Bilogur
Aleksey Bilogur

Reputation: 3846

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?

Upvotes: 3

Views: 15796

Answers (2)

Back2Basics
Back2Basics

Reputation: 7806

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

Upvotes: 3

randomname12387955
randomname12387955

Reputation: 819

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)

Upvotes: 1

Related Questions