I'm trying to open an .exe file from Python and give it some instructions. This .exe file has its own "language" so, for example, in order to launch a model I should type "call ". Because I have thousands models to run I need to automatize the process.
Here on Stackoverflow I found several options that I tried. Even though I don't get any error, my .exe file doesn't run (actually a window opens and closes immediately). I'm writing one of these solutions. [I'm using Python3]:
from subprocess import Popen, PIPE
p = Popen(["my_file.exe"], stdin=PIPE, stdout=PIPE)
output = p.communicate(input=b"call test.m") # "call test.m" is the way to run a model in my_file.exe
From this simple code I want "just" 'type' in an automatic way in my program "call .m", but it doesn't work.
Can anyone help me? Thanks
Try This:
from subprocess import Popen, check_output, check_call, PIPE, call
get_input = input("What Should I do?")
if get_input.strip().lower() == "run":
your_exe_file_address = r'"C:\Users\you\Desktop\my_file.exe"' # example
your_module_address = r'"C:\Users\you\Desktop\test.m"' # example
your_command = "call"
process = Popen([your_exe_file_address, your_command, your_module_address], stdout=PIPE, stderr=PIPE, shell=True)
stdout, stderr = process.communicate()
# < Other Ways >
# process = check_output([your_exe_file_address, your_command, your_module_address])
# process = check_call([your_exe_file_address, your_command, your_module_address], shell=True)
# process = call([your_exe_file_address, your_command, your_module_address], stdout=PIPE, stderr=PIPE, shell=True)
print(stdout, stderr)
else:
print("Invalid Input")
Another Way :
import os
get_input = input("What Should I do?")
if get_input.strip().lower() == "run":
your_exe_file_address = r'"C:\Users\you\Desktop\my_file.exe"' # example
your_module_address = r'"C:\Users\you\Desktop\test.m"' # example
your_command = "call"
last_shell = your_exe_file_address + " " + your_command + " " + your_module_address
os.system(last_shell)
else:
print("Invalid Input")
Third Way ( On Windows, install pywin32 package ):
import win32com.client
get_input = input("What Should I do?")
if get_input.strip().lower() == "run":
your_exe_file_address = r'"C:\Users\you\Desktop\my_file.exe"' # example
your_module_address = r'"C:\Users\you\Desktop\test.m"' # example
your_command = "call"
last_shell = your_exe_file_address + " " + your_command + " " + your_module_address
shell = win32com.client.Dispatch("WScript.Shell")
shell.Run(last_shell)
else:
print("Invalid Input")
Fourth way :
Save your commands in a .bat file like this:
"C:\Users\you\Desktop\my_file.exe" call "C:\Users\you\Desktop\test.m"
Then try to launch this bat file and get its output:
import os
get_input = input("What Should I do?")
if get_input.strip().lower() == "run":
your_bat_file_address = r'"C:\Users\you\Desktop\my_bat.bat"' # example
os.startfile(your_bat_file_address)
else:
print("Invalid Input")
Good Luck ...