【问题标题】:Getting the output of a shell command in Jupyter Notebook在 Jupyter Notebook 中获取 shell 命令的输出
【发布时间】:2020-01-24 19:04:51
【问题描述】:

如果我有一个带有以下脚本的 python 文件:

import pandas as pd

def csv():

    r = pd.DataFrame([[1,2,3,6],[1,3,4,5]])
    return r

csv()

如何在 Jupyter Notebook 中使用 shell 命令来获取此脚本的输出,即 pandas DataFrame。或者我如何修改python脚本来这样做,但仍然在Jupyter中使用shell命令(出于某种原因,我需要一个shell命令,而不是仅仅从python文件中导入函数并执行它)

到目前为止我尝试的是以下但没有工作(希望 Pandas DataFrame 作为输出)

import subprocess
result = subprocess.run(['python','MyPythonFile.py'], stdout=subprocess.PIPE)

result = ! python MyPythonFile.py

【问题讨论】:

  • 你想要=!
  • 第一个 Python 脚本不产生任何输出。它需要在某个地方调用print(),例如print(csv())
  • @inspectorG4dget =! 应该是什么意思?
  • @inspectorG4dget 没有任何区别。
  • @Barmar Print 不返回 pandas DataFrame 对象。这 ”!”是一种特定于 jupyter 的魔法,可以在其中运行 shell 命令。

标签: python shell command-line terminal jupyter-notebook


【解决方案1】:

访问结果的“stdout”参数:

import subprocess
result = subprocess.run(['python','MyPythonFile.py'], stdout=subprocess.PIPE)
print(result.stdout)

编辑:您不能通过 unix 标准输出传递 DataFrame。 DataFrame 是一个 Python 对象,对操作系统没有任何意义。使用导入在另一个 python 脚本中执行您的代码,或通过 pickle 或类似方法导出生成的对象。如果你不完全改变你的策略,你想要完成的事情是不可能的。

【讨论】:

  • 没有返回 DataFrame 对象。
  • @AlirezaRanjbar 这是因为第一个脚本没有产生任何输出,正如我在 cmets 中指出的那样。
  • @Barmar 使用 print() 并没有给出实际的 pandas DataFrame 对象,我的问题主要是关于这个。
  • @AlirezaRanjbar 您不能通过管道传递对象本身,只能通过字符串。
  • (上面给出答案的人)这太棒了!谢谢!
猜你喜欢
  • 2012-02-07
  • 1970-01-01
  • 2016-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多