'Can't run EXE file in Python

In a folder, I have two files— a Python Script and an Executable application. What I want is to run the Executable app using the Python script. I used below pieces of code:

os.chdir("D:\\ToneFinder GIthub\\ToneFinder\\Record.exe") # NotADirectoryError: [WinError 267] The directory name is invalid: 'D:\\ToneFinder GIthub\\ToneFinder\\Record.exe'
os.system("D:\\ToneFinder GIthub\\ToneFinder\\Record.exe") # 'D:\ToneFinder' is not recognized as an #internal or external command,
operable program or batch file.

os.startfile("D:\\ToneFinder GIthub\\ToneFinder\\Record.exe") # Nothing happens

subprocess.call("D:\\ToneFinder GIthub\\ToneFinder\\Record.exe") #Error loading Python DLL 'D:\ToneFinder GIthub\ToneFinder\python310.dll'

Note: Always, the path is 100% correct

Any ideas on that? Thank you.



Solution 1:[1]

chdir

os.chdir is for changing the working directory, not running a program. ...\Record.exe is not a directory.

system, startfile

The path contains a space, so Windows tries to run D:\ToneFinder (which implicitly becomes D:\ToneFinder.exe) with the argument GIthub\ToneFinder\Record.exe. Since there is no such file, an error occurs. Surrounding it with double quotes (os.system(r'"D:\ToneFinder GIthub\ToneFinder\Record.exe"')) will cause it to be interpreted as one long path.

call

subprocess.call takes a list of space-separated arguments, so it should be called like so: subprocess.call(r'"D:\ToneFinder GIthub\ToneFinder\Record.exe"'.split())

Which one should I use?

See Difference between subprocess.Popen and os.system.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Makonede