簡體   English   中英

在 Jupyter Notebook 中獲取 shell 命令的 output

[英]Getting the output of a shell command in Jupyter Notebook

如果我有一個帶有以下腳本的 python 文件:

import pandas as pd

def csv():

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

csv()

How can I use a shell command in Jupyter Notebook to get the output of this script which is a pandas DataFrame. Or How do I modify the python script to do so but sill use a shell command in Jupyter (For some reason I need a shell command rather than just importing the function from the python file and executing it)

到目前為止我嘗試的是以下但沒有工作(希望 Pandas DataFrame 作為輸出)

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

或者

result = ! python MyPythonFile.py

訪問結果的“stdout”參數:

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

編輯:您不能通過 unix 標准輸出傳遞 DataFrame。 DataFrame 是 Python object,對操作系統沒有意義。 使用導入在另一個 python 腳本中執行您的代碼,或通過 pickle 或類似工具導出生成的對象。 如果你不完全改變你的策略,你試圖完成的事情是不可能的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM