Skip to main content
 首页 » 编程设计

python之打开 .exe 并通过 Python 子进程向其传递命令

2024年11月01日7Leo_wl

所以我打开了我的 .exe 程序,但我想从我的 python 脚本向它传递字符串。 我这样打开exe

import subprocess 
p = subprocess.Popen("E:\Work\my.exe", shell=True) 
#let user fill in some tables 
p.communicate("userInfo") 

我想向这个程序传递一个字符串,同时让它在后台运行而不接管任何想法?

请您参考如下方法:

来自Python documentation for Using the subprocess module :

You don’t need shell=True to run a batch file, nor to run a console-based executable.

来自Python documentation for Popen Objects :

Note that if you want to send data to the process’s stdin, you need to create the Popen object with stdin=PIPE. Similarly, to get anything other than None in the result tuple, you need to give stdout=PIPE and/or stderr=PIPE too.

代码示例:

from subprocess import Popen, PIPE 
 
p = Popen(r"E:\Work\my.exe", stdin=PIPE) 
p.communicate("userInfo")