从子脚本到子进程内的控制台的

从子脚本到子进程内的控制台的

本文介绍了从子脚本到子进程内的控制台的 Python 输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的父脚本中,我执行以下操作:

in my parent script, I do the following:

fout=open(outfile,"w")
ferr = open(errfile,"w")

subprocess.call("1.py",stdout=fout,stderr=ferr,shell=True)

1.py 脚本中,我希望大部分日志消息进入日志文件,但有些消息,我想在控制台上打印,基于打印条件:

In the 1.py, script, I want most of the log message to go to log file, but some messages, I want to print on Console, based on the Print Conditions:

print "Hello World"

但它正在打印到outfile,我也想在控制台上打印,我试过了

but it is printing to outfile, which I wanted to print on console as well, I tried doing

sys.__stdout__.write("Hello World");

但这也不起作用.任何帮助将不胜感激!

but that aslso doesn't work. Any help would be appreciated!

推荐答案

如果stdout、stderr被重定向,那么你可以尝试直接打印到控制台:

If stdout, stderr are redirected then you could try to print directly to the console:

try: # Windows
    from msvcrt import putwch

    def print_to_console(message):
        for c in message:
            putwch(c)
        # newline
        putwch('
')
        putwch('
')
except ImportError: # Unix
    import os

    fd = os.open('/dev/tty', os.O_WRONLY | os.O_NOCTTY)
    tty = os.fdopen(fd, 'w', 1)
    del fd
    def print_to_console(message, *, _file=tty):
        print(message, file=_file)
    del tty

例子:

print_to_console("Hello TTY!")
# -> Hello TTY!

这篇关于从子脚本到子进程内的控制台的 Python 输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 09:42