在python中运行带有用户参数的.exe文件

2024-07-07 05:32:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我编译了一个windows可执行文件,它连接到一个软件无线电,并读取寄存器中的值。当我在命令提示符中执行这个命令时,它返回以下输出

Running the .exe without arguments

我的硬件是通过USB连接到COM4的,当我把这些作为参数传递时,我会看到下面的屏幕,在这里我可以选择用它们的ID(100是主机无线电)。101、102、103和104是其他无线电),或者可以通过键入“q”退出应用程序。在

With -u and COM4 port

如果我输入要测距的收音机的ID,我就会得到测距信息,这个过程会一直持续到我输入‘q’退出为止 ranging and quitting the application

我现在可以调用python的可执行文件来存储这些值。我在其他主题中读到,这可以通过库的“子进程”来实现。我的代码片段如下

#!/usr/bin/env python

import subprocess
import time

#subprocess.Popen([r"C:\Users\Raja\Documents\SUMO_Final\rcmSampleApp.exe"])

p = subprocess.Popen("C:/Users/Raja/Documents/SUMO_Final/rcmSampleApp.exe -u COM4", shell = True, stdin = subprocess.PIPE)


p.stdin.write('104')
time.sleep(5)
p.stdin.write('q')
p.kill()

当我在.py文件中执行此操作时,.exe会独立循环,如下所示 .exe looping indefinitely inspite of p.kill()

论坛上的一些答案建议更改shell=False并在终止进程之前终止它,但我不清楚。有人能帮忙吗?在

干杯


Tags: importid可执行文件time进程stdinexeusers
2条回答

当你交互使用你的程序时,我假设你输入101Return,然后输入qReturn。在

从Python启动时,必须用\n模拟返回,并且应该等待程序结束而不是终止它:

p.stdin.write('104\n')
time.sleep(5)
p.stdin.write('q\n')
p.wait()

但是,由于您只传递已知的输出,如果您只想读取和处理输出,您最好选择使用communicate

^{pr2}$

flush编写命令时的管道(并包含新行,以模拟按Enter键的用户输入,假设程序期望如此),完成后close管道。一般来说,避免shell=True也是一个好主意,因为它引入了包装命令的附加层(在除此之外的其他情况下,会增加安全性和稳定性问题)。尝试:

#!/usr/bin/env python

import subprocess
import time

# Use list form of command to avoid shell=True, and raw string to allow
# safe use of "normal" looking Windows-style path
# Include universal_newlines=True automatic str decoding in Py3; it might
# fix newlines on Py2 as well, but if not, you'll need to explicitly send
# \r\n instead of just \n to match OS conventions (or use os.linesep to autoselect)
p = subprocess.Popen([r"C:\Users\Raja\Documents\SUMO_Final\rcmSampleApp.exe", "-u", "COM4"],
        stdin=subprocess.PIPE, universal_newlines=True)

p.stdin.write('104\n')  # Include newline that manual entry includes
p.stdin.flush()         # Ensure write not buffered
time.sleep(5)
p.stdin.write('q\n')    # Include newline
p.stdin.close()         # Flush and close stdin, so program knows no more input coming
p.kill()                # Depending on program, p.join() might be enough

假设p.join()起作用,您可以将最后三行(writeclose和{}/join)替换为:

^{pr2}$

它将隐式地执行所有三个任务。在

相关问题 更多 >