【问题标题】:Display output from another python script in jupyter notebook在 jupyter notebook 中显示另一个 python 脚本的输出
【发布时间】:2018-03-30 23:03:18
【问题描述】:

我在 jupyter 笔记本中运行了一个循环,该循环使用 execfile 命令引用了另一个 python 文件。
我希望能够从我从 execfile 调用的文件中查看所有各种打印和输出。但是,我没有看到任何 pandas 数据框打印输出。例如。如果我只是说'df',我看不到数据框表的输出。但是,我会看到“打印 5”。

谁能帮我设置哪些选项才能查看?

import pandas as pd
list2loop =['a','b','c','d']


for each_item in list2loop:
    execfile("test_file.py")

“test_file.py”在哪里:

df=pd.DataFrame([each_item])   
df
print 3

【问题讨论】:

  • 不幸的是,除非您在 test_file 中定义一个函数,然后在主程序中导入该函数,然后使用参数调用该函数,否则这是行不通的。

标签: pandas jupyter-notebook jupyter


【解决方案1】:

解决方案只是使用%run 魔法而不是execfile(无论execfile 是什么)。

假设你有一个文件test.py

#test.py
print(test_input)

那么你可以简单地做

for test_input in (1, 2, 3):
    %run -i test.py

-i 告诉 Python 在 IPython 的名称空间中运行文件,因此脚本知道您的所有变量,并且脚本中定义的变量随后在您的名称空间中。如果您在脚本中显式调用sys.exit,则必须另外使用-e

【讨论】:

    猜你喜欢
    • 2019-11-29
    • 1970-01-01
    • 2020-08-06
    • 2019-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多