【问题标题】:How to redirect python print to a file while running it inside a screen session如何在屏幕会话中运行时将python打印重定向到文件
【发布时间】:2017-08-03 13:40:51
【问题描述】:

我有一个简单的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

但它也没有工作。

【问题讨论】:

    标签: python gnu-screen


    【解决方案1】:

    但是我真正需要的东西不起作用(out.txt 仍然为空):

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

    该命令的工作原理如下:

    • shell 启动screen 程序,标准输出重定向到out.txt
    • screen 会话中,python 在没有任何输出重定向的情况下运行。人们可能会期望 python 的输出最终应该发送到out.txt,因为输出重定向应用于其父进程。但是,这不会发生,因为 screen 自己管理输出流。

    您可以通过在screen 会话中进行输出重定向来解决问题,如下所示:

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

    这在screen 下运行以下命令:

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

    代表 启动 bash 并在其中执行命令 "python test.py > out.txt"

    【讨论】:

      【解决方案2】:

      我不确定您如何将输出重定向到外部或该屏幕命令如何工作,但如果修改该 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】:

        您是否考虑过使用文件 read/write ? 示例:

        file = open("path/to/file", "w")
        file.write("Hello")
        file.close
        

        【讨论】:

        • 我想将它应用到一个已经编写好的大型 python 程序中。因此,如果可能,我想避免重写每个打印语句。
        【解决方案4】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-12-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-15
          • 2020-09-16
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多