【问题标题】:Logging/print statements do not work in subprocess in Python Django application记录/打印语句在 Python Django 应用程序的子进程中不起作用
【发布时间】:2021-09-16 13:42:51
【问题描述】:

在我的 Django 项目中,我有一个名为 views.py 的文件。那里有几个日志记录/打印语句,它们工作正常。

但是,views.py 使用子进程的 run 方法调用另一个 python 脚本。令人惊讶的是,该脚本中没有任何日志记录/打印语句。 这就是 run() 的调用方式:

out= run([sys.executable, /path/to/script.py, param1, param2], shell=False, stdout=PIPE)

在settings.py中记录是这样配置的:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
    },
    'loggers': {
        'my_logger': {
            'handlers': ['console'],
            'level': 'INFO',
        },
    },
}

请告知发生了什么问题。

谢谢。

【问题讨论】:

    标签: python python-3.x django web logging


    【解决方案1】:

    当您使用stdout=subprocess.PIPE 调用subprocess.run 时,您必须自己显示来自调用脚本的标准流。以下是您应该如何捕获这些打印语句:

    p = run(
        [sys.executable, /path/to/script.py, param1, param2],
        shell=False, stdout=PIPE, stderr=PIPE
    )
    # Display the contents of the standard output
    print(p.stdout.read())
    # Display the contents of the standard error
    print(p.stderr.read())
    

    请注意这里的pCompletedProcess 的一个实例。这意味着您可以使用它通过调用p.returncode 来检查您运行的命令是否成功,其中应该包含运行脚本的返回码。

    如果您不希望自己捕获标准流并显示其内容,请考虑调用脚本stdoutstderr 设置为PIPE

    p = run(
        [sys.executable, /path/to/script.py, param1, param2], shell=False
    )
    

    这将强制在脚本运行时显示标准流(stdoutstderr)。

    【讨论】:

    • 感谢您的回复。除了 stdout=subprocess.PIPE 之外还有什么选项可以让我在脚本本身中使用打印语句?
    • 不设置 stdoutstderr 应该会强制 subprocess.run 打印标准流的内容。请查看我的编辑。
    • 非常感谢。这个解决方案非常适合我!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-25
    • 1970-01-01
    • 2018-02-02
    • 1970-01-01
    相关资源
    最近更新 更多