我可以将此程序的输出重定向到脚本吗? [英] can I redirect the output of this program to script?

查看:38
本文介绍了我可以将此程序的输出重定向到脚本吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行一个管理 USB 设备的二进制文件.二进制文件,执行时将结果输出到我指定的文件中.

I'm running a binary that manages a usb device. The binary file, when executed outputs results to a file I specify.

在python中有什么方法可以将二进制文件的输出重定向到我的脚本而不是文件?我只需要打开文件并在这行代码运行后立即获取它.

Is there any way in python the redirect the output of a binary to my script instead of to a file? I'm just going to have to open the file and get it as soon as this line of code runs.

def rn_to_file(comport=3, filename='test.bin', amount=128):
    os.system('capture.exe {0} {1} {2}'.format(comport, filename, amount))

它也不适用于子进程

from subprocess import check_output as qx
>>> cmd = r'C:\repos\capture.exe 3 text.txt 128'
>>> output = qx(cmd)
Opening serial port \\.\COM3...OK
Closing serial port...OK
>>> output
b'TrueRNG Serial Port Capture Tool v1.2\r\n\r\nCapturing 128 bytes of data...Done'

文件的实际内容是一系列 0 和 1.这不会将输出重定向到文件给我,而是只是打印出无论如何都会打印出来的内容.

The actual content of the file is a series of 0 and 1. This isn't redirecting the output to the file to me, instead it just prints out what would be printed out anyway as output.

推荐答案

看起来你在使用 Windows,它有一个特殊的保留文件名 CON 表示使用控制台(模拟*nix 将是 /dev/stdout).

It looks like you're using Windows, which has a special reserved filename CON which means to use the console (the analog on *nix would be /dev/stdout).

试试这个:

subprocess.check_output(r'C:\repos\capture.exe 3 CON 128')

可能需要在其中使用 shell=True,但我怀疑您不需要.

You might need to use shell=True in there, but I suspect you don't.

这个想法是让程序写入虚拟文件 CON,它实际上是 stdout,然后让 Python 捕获它.

The idea is to make the program write to the virtual file CON which is actually stdout, then have Python capture that.

另一种方法是 CreateNamedPipe(),它可以让您创建自己的文件名并从中读取,而无需磁盘上的实际文件.有关更多信息,请参阅:python 中的 createNamedPipe

An alternative would be CreateNamedPipe(), which will let you create your own filename and read from it, without having an actual file on disk. For more on that, see: createNamedPipe in python

这篇关于我可以将此程序的输出重定向到脚本吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆