Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to run an exe file with the arguments using python

Suppose I have a file RegressionSystem.exe. I want to execute this executable with a -config argument. The commandline should be like:

RegressionSystem.exe -config filename

I have tried like:

regression_exe_path = os.path.join(get_path_for_regression,'Debug','RegressionSystem.exe')
config = os.path.join(get_path_for_regression,'config.ini')
subprocess.Popen(args=[regression_exe_path,'-config', config])

but it didn't work.

like image 448
bappa147 Avatar asked Apr 10 '13 14:04

bappa147


People also ask

How do you run an argument file in Python?

In order to pass arguments to your Python script, you will need to import the sys module. Once this module is imported in your code, upon execution sys. argv will exist, containing a list of all of the arguments passed to your script.

How do you pass a file path as an argument in Python?

To use it, you just pass a path or filename into a new Path() object using forward slashes and it handles the rest: Notice two things here: You should use forward slashes with pathlib functions. The Path() object will convert forward slashes into the correct kind of slash for the current operating system.


2 Answers

You can also use subprocess.call() if you want. For example,

import subprocess FNULL = open(os.devnull, 'w')    #use this if you want to suppress output to stdout from the subprocess filename = "my_file.dat" args = "RegressionSystem.exe -config " + filename subprocess.call(args, stdout=FNULL, stderr=FNULL, shell=False) 

The difference between call and Popen is basically that call is blocking while Popen is not, with Popen providing more general functionality. Usually call is fine for most purposes, it is essentially a convenient form of Popen. You can read more at this question.

like image 141
hjweide Avatar answered Oct 06 '22 22:10

hjweide


For anyone else finding this you can now use subprocess.run(). Here is an example:

import subprocess
subprocess.run(["RegressionSystem.exe", "-config filename"])

The arguments can also be sent as a string instead, but you'll need to set shell=True. The official documentation can be found here.

like image 45
Daniel Butler Avatar answered Oct 06 '22 21:10

Daniel Butler