【问题标题】:How to call python command line program with Jupyter cell如何使用 Jupyter 单元调用 python 命令行程序
【发布时间】:2018-12-20 00:36:55
【问题描述】:

我正在使用旨在作为命令行程序运行的第三方程序,该程序会输出我以后需要在我的代码中使用的文件。我在 Jupyter Lab 工作,想将函数调用集成到我的代码中。典型的运行方式是:

python create_files.py -a input_a -b input_b -c -d

然后我想在我的 Jupyter 笔记本中调用它。我已经能够通过使用! 使其工作,即:

! python create_files.py -a input_a -b input_b -c -d

问题在于,当我想使用变量指定input_ainput_b 时,这不起作用,因为! 似乎需要一个文字字符串,可以这么说。

有没有一种更简洁的方法可以做到这一点而不必更改该程序的源代码(我已经尝试过研究,并且代码的编写方式是没有简单的方法来调用它的 main 函数。)

【问题讨论】:

  • 您可以尝试通过 bash 之类的方式回显文件吗?
  • subprocess.Popen('python create_files.py -a %s -b %s -c -d' % (input_a, input_b)) 怎么样?

标签: python python-3.x command-line jupyter-notebook


【解决方案1】:

在 Jupyter notebook 上,使用subprocess 运行命令行脚本是这样的:

简单的命令行版本:

 dir *.txt /s /b

在 Jupyter 笔记本上:

import subprocess
sp = subprocess.Popen(['dir', '*.txt', '/s', '/b'], \
    stderr=subprocess.PIPE, \
    stdout=subprocess.PIPE, \
    shell=True)

(std_out, std_err) = sp.communicate()   # returns (stdout, stderr)

打印出错误信息,以防万一:

print('std_err: ', std_err)

打印回显消息:

print('std_out: ', std_out)

我认为这个例子很清楚,你可以根据自己的需要调整它。希望能帮助到你。

【讨论】:

  • 这是一个很好的解决方案;谢谢你。我还想为输出添加一项功能:我运行的程序输出进度文本,我希望在进程运行时实时显示在 Jupyter 笔记本中。您的代码只会在进程完成后将文本作为一个块打印出来。谢谢!
【解决方案2】:

你的问题和那个类似:

How to execute a * .PY file from a * .IPYNB file on the Jupyter notebook?

您可以使用以下命令,这有点hacky:

%run -i 'create_files.py'

“正确”的方法是使用 autoreload 方法。一个例子如下:

%load_ext autoreload
%autoreload 2
from create_files import some_function
output=some_function(input)

autoreload的参考如下: https://ipython.org/ipython-doc/3/config/extensions/autoreload.html

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2019-12-20
    • 1970-01-01
    • 2021-02-09
    • 2020-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-25
    相关资源
    最近更新 更多