我正在尝试从Python打开一个.exe文件并给它一些指示。此.exe文件有自己的“语言”,因此,例如,为了启动模型,我应该键入“call”。因为我有数千个模型要运行,所以我需要自动化这个过程。
在Stackoverflow上,我找到了几个我尝试过的选项。即使我没有收到任何错误,我的.exe文件也不会运行(实际上是一个窗口打开并立即关闭)。我正在写一个这样的解决方案。 [我正在使用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
从这个简单的代码中我想在我的程序“call .m”中以“自动方式”“输入”,但它不起作用。
任何人都可以帮助我吗? 感谢
答案 0 :(得分:1)
试试这个:
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")
另一种方式:
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")
第三种方式(在Windows上,安装pywin32包):
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")
第四种方式:
将命令保存在.bat文件中,如下所示:
"C:\Users\you\Desktop\my_file.exe" call "C:\Users\you\Desktop\test.m"
然后尝试启动此bat文件并获取其输出:
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")
祝你好运......