Python run exe file with arguments

How to run exe file from python?

It is used to launch .py, .pyw, .pyc, .pyo files and supports multiple Python installations: You can run your Python script without specifying .py extension if you have .py, .pyw in PATHEXT environment variable: It adds support for shebang ( header line) to select desired Python version on Windows if you have multiple versions installed. Question: I have a simple script blah.py (using Python 2): If I execute my script by: It prints argument but if I execute script by: error occurs:

How to run exe file from python?

I try to run a exe (In the background) from a specific path in my local python project, with the os.system libary. I have managed to change folders like ‘cd’ Command, but i can’t run the file.

This is for a python project running on Windows 64BIT, Python 3.5.3

the file.exe is at the «programs» dir.

import os os.system("cd C:\Users\User\AppData\Windows\Start Menu\Programs") subprocess.Popen("file.exe") 

I saw other posts about this issue but i couldn’t resolve it. Any ideas?

Problem is that the system command doesn’t work. It «works», but in a separate subprocess that exits right away. Current directory doesn’t propagate up to the calling process (also, as you’re not checking the return code, the command wouldn’t fail, even with a non-existing directory. Note that it happens here, as the directory name has spaces in it and isn’t quoted. ).

Читайте также:  Css transition position top

You would have to use os.chdir for that, but you don’t even need it.

If you want to run a command in a specific location, just pass the absolute path of the command (and since it’s using string literals, always use r prefix to avoid that some \t or \n chars are interpreted as special characters. ). For instance with python 3, with the command line provided there’s an error (but okay in python 2. ):

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 5-6: truncated \UXXXXXXXX escape 

So always use raw prefix. Here’s how I would rewrite that:

current_dir = r"C:\Users\User\AppData\Windows\Start Menu\Programs" subprocess.Popen(os.path.join(current_dir,"file.exe")) 

And if you really need that the current directory is the same as the exe, use cwd parameter. Also get the return value of Popen to be able to wait/poll/****/whatever and get command exit code:

p = subprocess.Popen(os.path.join(current_dir,"file.exe"),cwd=current_dir) # . return_code = p.wait() 

As a side note, be aware that:

p = subprocess.Popen("file.exe",cwd=current_dir) 

doesn’t work, even if file.exe is in current_dir (unless you set shell=True , but it’s better to avoid that too for security/portability reasons)

Note that os.system is deprecated for a lot of (good) reasons. Use subprocess module, always , and if there are argument, always with an argument list (not string), and avoid shell=True as much as possible.

Can you see if this works

 import os # change the current directory # to specified directory os.chdir(r"C:\Users\User\AppData\Windows\Start Menu\Programs") subprocess.Popen("file.exe") 

Problem solved. Thanks everyone, the issue was administrative privileges.. Started pycharm as administrator. And like i said — i was able to see the file with os.listdir(), but when i try to run it, errors start to pop up. I think the main issue is os.system() inherit current privileges from python proccess.

Using Python for scripting and automation, To install Python using the Microsoft Store: Go to your Start menu (lower left Windows icon), type «Microsoft Store», select the link to open the store. Once the store is open, select Search from the upper-right menu and enter «Python». Select which version of Python you would like to use from the results under Apps.

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 
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]) 

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.

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.

os.system("/path/to/exe/RegressionSystem.exe -config "+str(config)+" filename") 

Here i wanna offer a good example. In the following, I got the argument count of current program then append them in an array as argProgram = [] . Finally i called subprocess.call(argProgram) to pass them wholly and directly :

import subprocess import sys argProgram = [] if __name__ == "__main__": # Get arguments from input argCount = ****(sys.argv) # Parse arguments for i in range(1, argCount): argProgram.append(sys.argv[i]) # Finally run the prepared command subprocess.call(argProgram) 

In this code i supposed to run an executable application named `Bit7z.exe» :

python Bit7zt.py Bit7zt.exe -e 1.zip -o extract_folder 

Notice : I used of for i in range(1, argCount): statement because i dont need the first argument.

How can I to run Windows PowerShell commands from, In order to run powershell commands, all you’d need to do is execute C:\Windows\System32\powershell.exe and pass through the arguments. Here’s some example code to try: import subprocess subprocess.call (‘C:\Windows\System32\powershell.exe Get-Process’, shell=True) You can …

How to execute Python scripts in Windows?

I have a simple script blah.py (using Python 2):

import sys print sys.argv[1] 

If I execute my script by:

It prints argument but if I execute script by:

So arguments do not pass to script.

python.exe in PATH. Folder with blah.py also in PATH.
python.exe is default program to execute *.py files.

When you execute a script without typing «python» in front, you need to know two things about how Windows invokes the program. First is to find out what kind of file Windows thinks it is:

Next, you need to know how Windows is executing things with that extension. It’s associated with the file type «Python.File», so this command shows what it will be doing:

C:\>ftype Python.File Python.File="c:\python26\python.exe" "%1" %*

So on my machine, when I type «blah.py foo», it will execute this exact command, with no difference in results than if I had typed the full thing myself:

"c:\python26\python.exe" "blah.py" foo

If you type the same thing, including the quotation marks, then you’ll get results identical to when you just type «blah.py foo». Now you’re in a position to figure out the rest of your problem for yourself.

(Or post more helpful information in your question, like actual cut-and-paste copies of what you see in the console. Note that people who do that type of thing get their questions voted up, and they get reputation points, and more people are likely to help them with good answers.)

Brought In From Comments:

Even if assoc and ftype display the correct information, it may happen that the arguments are stripped off. What may help in that case is directly fixing the relevant registry keys for Python. Set the

HKEY_CLASSES_ROOT\Applications\python26.exe\shell\open\command 

Likely, previously, %* was missing. Similarly, set

 HKEY_CLASSES_ROOT\py_auto_file\shell\open\command 

to the same value. See http://eli.thegreenplace.net/2010/12/14/problem- passing-arguments -to- python-scripts -on-windows/

example registry setting for python.exe

HKEY_CLASSES_ROOT\Applications\python.exe\shell\open\command The registry path may vary, use python26.exe or python.exe or whichever is already in the registry.

HKEY_CLASSES_ROOT\py_auto_file\shell\open\command

you should make the default application to handle python files be python.exe.

right click a *.py file, select «Open With» dialog. In there select «python.exe» and check «always use this program for this file type» (something like that).

then your python files will always be run using python.exe

Additionally, if you want to be able to run your Python scripts without typing the .py (or .pyw ) on the end of the file name, you need to add .PY (or .PY;.PYW ) to the list of extensions in the pathext environment variable.

right-click on Computer
left-click Properties
left-click Advanced system settings
left-click the Advanced tab
left-click Environment Variables.
under «system variables» scroll down until you see PATHEXT
left-click on PATHEXT to highlight it
left-click Edit.
Edit «Variable value» so that it contains ;.PY (the End key will skip to the end)
left-click OK
left-click OK
left-click OK

Note #1: command- prompt windows won’t see the change w/o being closed and reopened.

Note #2: the difference between the .py and .pyw extensions is that the former opens a command prompt when run, and the latter doesn’t.

On my computer, I added ;.PY;.PYW as the last (lowest-priority) extensions, so the «before» and «after» values of PATHEXT were:

Here are some instructive commands:

C:\>echo %pathext% .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY;.PYW C:\>assoc .py .py=Python.File C:\>ftype Python.File Python.File="C:\Python32\python.exe" "%1" %* C:\>assoc .pyw .pyw=Python.NoConFile C:\>ftype Python.NoConFile Python.NoConFile="C:\Python32\pythonw.exe" "%1" %* C:\>type c:\windows\helloworld.py print("Hello, world!") # always use a comma for direct address C:\>helloworld Hello, world! C:\> 

You could install pylauncher. It is used to launch .py, .pyw, .pyc, . pyo files and supports multiple Python installations:

You can run your Python script without specifying .py extension if you have .py, .pyw in PATHEXT environment variable:

It adds support for shebang ( #! header line) to select desired Python version on Windows if you have multiple versions installed. You could use *nix-compatible syntax #! /usr/bin/env python .

You can specify version explicitly e.g., to run using the latest installed Python 3 version:

It should also fix your sys.argv issue as a side-effect.

Interact with a Windows console application via Python, In case of a program like cmd.exe, even readline() won’t suffice as the line that indicates a new command can be sent is not terminated by a newline, so will have to analyze the output byte-by-byte. Here’s a sample script that runs cmd.exe, looks for the prompt, then issues a dir and then an exit:

Источник

Оцените статью