首页 > 解决方案 > 如何将 os.execlpe() 的 stdout stderr 重定向到文件中

问题描述

我正用头撞墙,jpyter nbconvert通过以下方式从 python 运行,因为它允许我将参数传递给 jupyter notebook:

env['IPYTHONARGV'] = json.dumps({'timeperiod':timeperiod,'infile':infile})
os.execlpe('jupyter', 'jupyter', 'nbconvert', '--execute','notebook.ipynb', 
           '--to', 'html', '--output', output_html, '2>&1', '1>log.out',  env)

省略'2>&1', '1>log.out',部分时,该命令可以正常工作。但是使用 bash 重定向,该命令会抱怨以下内容:

[NbConvertApp] WARNING | pattern '2>&1' matched no files
[NbConvertApp] WARNING | pattern '1>log.out' matched no files

有谁知道如何解决这个问题?

标签: pythonbashstdoutjupyternbconvert

解决方案


重定向2>&1广告1>log.out由 shell 解释,但您将它们作为参数提供给命令。这就是为什么 Jupyter 抱怨无法将它们作为文件找到的原因。

您可以subprocess使用shell=True

import subprocess as sp
env['IPYTHONARGV'] = json.dumps({'timeperiod':timeperiod,'infile':infile})
sp.check_call('jupyter nbconvert --execute notebook.ipynb --to html --output output_html 2>&1 1>log.out', shell=True, env=env)

sp.check_output()如果您需要在 Python 中处理输出,您可以使用和删除重定向。


推荐阅读