skywind3000 / PyStand

:rocket: Python Standalone Deploy Environment !!
MIT License
641 stars 75 forks source link

请教:将python的stdout重定向到文件 #65

Open hiroi-sora opened 7 months ago

hiroi-sora commented 7 months ago

当前,python的stdout、stderr会被重定向到pystand进程的控制台(如果存在)。

假如希望将pystand的输出重定向到文件,如:

pystand.exe > test.txt

是无法实现的, test.txt 依然为空。

或者用另一个程序调用 pystand.exe ,也无法在管道获取输出内容。

请问,如何实现让pystand输出到正确的地方?

即:如果pystand进程的stdout存在,那么将python的stdout也重定向到相同的地方。

skywind3000 commented 7 months ago

这种需求,直接用 runtime 里的 python.exe 吧,修改下 python38._pth 文件,添加:

import site
../site-packages
hiroi-sora commented 7 months ago

嗯,直接调用解释器是可以。不过我的项目,希望用户使用起来简单一点,无论启动gui还是命令行调用,都能通过 PyStand.exe 这一个入口搞定。

hiroi-sora commented 7 months ago

我初步实现了第二个需求:另一个程序调用 pystand.exe 时,在管道获取输出内容。

C++部分,只有stdout不存在时才重定向:

        if(_fileno(stdout) < 0)
            freopen("CONOUT$", "w", stdout);
        if (_fileno(stderr) < 0)
            freopen("CONOUT$", "w", stderr);

Python部分同理:

    try:
        fd = os.open("CONOUT$", os.O_RDWR | os.O_BINARY)
        fp = os.fdopen(fd, "w")
    except Exception as e:
        fp = open(os.devnull, "w")
    if not sys.stdout:
        sys.stdout = fp
    if not sys.stderr:
        sys.stderr = fp

这样可以让别的程序获取进程输出了。但是仍未解决重定向到文件的问题(pystand.exe > test.txt