Lock Python code in Jupyter Notebook and make it executable as command

与世无争的帅哥 提交于 2019-12-24 10:37:14

问题


I have the below code running in 4 different cells:

cell1:

import pandas as pd
import numpy as np
import os
reference = pd.read_excel(argument1,sheet_name=argument2,na_values='0',converters={'SID': '{:0>12}'.format}) #reference file path
reference.replace('',np.nan,inplace=True)
reference.dropna(how='all',inplace = True)
reference.drop([0],inplace=True)

Cell2:

reference=reference[reference['SType']==argument']

Cell4:

path = argument4
file_list = os.listdir(path)

for i in file_list:
    filename = os.path.join(path, i)
    #ori_df = pd.read_excel(filename)
    df = pd.read_excel(filename)
    cond = pd.Index(df.iloc[0]).intersection(reference.columns)
    df1 = reference[cond].copy()
    #df1.loc[-1] = df1.columns
    d = dict(zip(df.iloc[0], df.columns))
    df1 = df1.sort_index().rename(columns=d)
    x = df1.iloc[:,1:].columns
    df1.dropna(axis=0,how='all',subset=x,inplace=True)
    if len(cond) > 1:
        df1.to_excel(filename,index = False)
    else:
        os.remove(filename)

I want to know is there any way that I can save this code as a .py file and make it executable just by passing the arguments like a command line inside jupyter cells. Is it allowed in Jupyter notebook? if yes, Please let me know how.

** Sorry if I am being ignorant here, I tried doing some research on this but couldnot get any information.


回答1:


Just use nbconvert --to script option.

jupyter-nbconvert --to script path/to/your/notebook.ipynb  

You will not be able to pass custom argument using command line, that will need some further customization of generated script.

Relevant documentation

Convert a notebook to an executable script. This is the simplest way to get a Python (or other language, depending on the kernel) script out of a notebook. If there were any magics in an Jupyter notebook, this may only be executable from a Jupyter session.




回答2:


I had the same question not a long time ago ^^

I'm not sure my answer is what you are expecting for, but here is how I did it :

Let's say your files are like this :

+
|  my_notebook.ipynb
| + folder1
| | my_script.py

And let's say you have a function run_script() in the file my_script.py

Then you can just do :

import folder1.my_script as ms

ms.run_script()

In order to be able to call your script as a package/module, you need to create empty __init__.py file at the right place. So your tree should be like :

+
|  __init__.py
|  my_notebook.ipynb
| + folder1
| |  __init__.py
| | my_script.py


来源:https://stackoverflow.com/questions/52831119/lock-python-code-in-jupyter-notebook-and-make-it-executable-as-command

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!