can I redirect the output of this program to script?

偶尔善良 提交于 2019-12-24 22:53:05

问题


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

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

it doesn't work with subprocess either

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'

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.


回答1:


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

So try this:

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

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

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

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



来源:https://stackoverflow.com/questions/49594237/can-i-redirect-the-output-of-this-program-to-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!