打开一个 .exe 文件并在 Python 中为其输入参数

Open an .exe file and give it input parameters in Python

我正在尝试从 Python 打开一个 .exe 文件并给它一些指令。这个 .exe 文件有自己的 "language",因此,例如,为了启动一个模型,我应该键入 "call "。因为我有数千个模型 运行 我需要自动化这个过程。

在 Whosebug 上,我发现了几个我尝试过的选项。即使我没有收到任何错误,我的 .exe 文件也没有 运行(实际上 window 会立即打开和关闭)。我正在编写这些解决方案之一。 [我正在使用 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" 中以自动方式 "just" 'type',但它不起作用。

谁能帮帮我? 谢谢

试试这个:

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

祝你好运...