Pass arguments to executable in Python

Question:

I am using os.startfile('C:\test\sample.exe') to launch the application. I don’t want to know the application’s exit status and I just want to launch the exe.

I need to pass the argument to that exe like 'C:\test\sample.exe' -color

Please suggest a method to run this in Python.

Asked By: Bala

||

Answers:

You should use the subprocess module instead of os.startfile or os.system in every case that I’m aware of.

import subprocess
subprocess.Popen([r'C:testsample.exe', '-color'])

You could, as @Hackaholic suggests in the comments, do

import os
os.system(r'C:testsample.exe -color')

But this is no simpler, and the docs for os recommend the use of subprocess instead.

Answered By: senshin

Create a batch file sam_ple.bat with the following commands and arguments

cd C:test
start sample.exe -color

Then put sam_ple.bat in the same directory as your script.py file

Enter the following line of code in python to launch the exe:

os.startfile('.sam_ple.bat')
Answered By: Bevin
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.