代码之家  ›  专栏  ›  技术社区  ›  BlueSun

如何在屏幕会话中运行python打印时将其重定向到文件

  •  0
  • BlueSun  · 技术社区  · 7 年前

    我有一个简单的python脚本test.py:

    from __future__ import print_function
    print("Hello")
    

    我尝试将打印重定向到屏幕会话内的文件。以下事项有效:

    无屏幕:

    python test.py > out.txt
    

    screen -S tmp
    python test.py > out.txt
    exit
    

    然而,我真正需要的是无法工作(out.txt仍为空):

    screen -Sdm tmp python test.py > out.txt
    

    读了一篇看似相关的文章后 question 我还尝试了:

    screen -Sdm tmp stdbuf -i0 -o0 -e0 python test.py > out.txt
    

    4 回复  |  直到 6 年前
        1
  •  1
  •   Leon    7 年前

    然而,我真正需要的是无法工作(out.txt仍为空):

    screen -Sdm tmp python test.py > out.txt
    

    该命令的工作原理如下:

    • shell启动 screen 标准输出重定向到的程序 out.txt
    • 屏幕 一场 python 无论如何,因为输出重定向应用于其父进程。然而,从那以后,这种情况就没有发生过 自己管理输出流。

    您可以通过使输出重定向发生在 屏幕 会议内容如下:

    screen -Sdm tmp bash -c "python test.py > out.txt"
    

    屏幕 以下命令:

    bash -c "python test.py > out.txt"
    

    它代表 "python test.py > out.txt" .

        2
  •  1
  •   FernAndr    7 年前

    我不确定如何从外部重定向输出,或者screen命令如何工作,但是如果修改Python程序在您的控制之下,那么 this solution

    import sys
    
    class Logger(object):
        def __init__(self, logfile):
            self.terminal = sys.stdout
            self.log = open(logfile, "a")
    
        def write(self, message):
            self.terminal.write(message)  # This might be optional for you
            self.log.write(message)  
    
        def flush(self):
            #this flush method is needed for python 3 compatibility.
            #this handles the flush command by doing nothing.
            #you might want to specify some extra behavior here.
            pass    
    
    if len(sys.argv) > 1:  # Just in case no argument was passed to the program
        sys.stdout = Logger(sys.argv[1])
    

    这样,您就不需要重写每个打印语句。然后你会使用你的 screen 不带 >

    screen -Sdm tmp python test.py out.txt
    

    或者您可能需要引号才能使其生效:

    screen -Sdm tmp python "test.py out.txt"
    
        3
  •  0
  •   TuffK    7 年前

    例子:

    file = open("path/to/file", "w")
    file.write("Hello")
    file.close
    
        4
  •  -2
  •   mohhinder    7 年前

    只是实现一些日志记录怎么样?使用 daiquiri 简化它。