How To Run Python Script .py File In Jupyter Notebook .ipynb File And IPython

In this article, i will tell you how to invoke python script file (.py) from jupyter notebook file (.ipynb) and ipython console. But first you should create a python virtual environment in anaconda and start jupyter notebook server, you can read article How To Start Jupyter Notebook In Anaconda Python Virtual Environment to learn more.

1. Invoke Python Script File From Jupyter Notebook.

  1. Create a jupyter notebook file like below, the jupyter notebook file name is InvokePythonScript.ipynb. ( We will introduce list_file.py and list_file_path.py later. )
    create a jupyter notebook file
  2. Click file InvokePythonScript.ipynb to edit it.
  3. Add first line cell and input below source code. Below ipython code will create a python script file with name list_file.py. When you run this python script file in jupyter notebook, it will print out all the files and directories name in the folder which you pass to it as command line input argument. If you do not pass any folder name as the command line input arguments when you invoke list_file.py, it will list the files and directories name in current directory.
    ipython script to create a python script file

    %%writefile list_file.py
    
    # use ipython magic command %%writefile to create a python script file and write below script content to it.
    # import two python standard module. 
    import sys
    import os
    
    # set dir_name value to current directory by default.
    dir_name = './'
    
    # if user input an argument.
    if len(sys.argv) > 1:
        # give the first argument value to a local variable, the argument value should be a directory name.
        dir_name = sys.argv[1]
    
        
    # get all the dir_name directory contained files in a list
    files_list = os.listdir(dir_name)
        
    # loop in the files_list.
    for file in files_list:
        # print out file name in the standard output.
        print(file)
  4. Select above line cell to make it focus, then click Run button at top to run it, then you can see a message is printed, the message is Writing list_file.py ( if list_file.py do not exist ) or Overwriting list_file.py ( if list_file.py exist ).
  5. Now you can find the list_file.py has been created or overwrote in your jupyter notebook web server started folder.
  6. Add another line cell and write below code in it. Focus below line and click Run button, you can see all files and folders name listed under the code line.
    run python script file command in jupyter note book

    %run -i list_file.py
  7. Create another python file with IDLE editor or any text editor, save the python file as list_file_path.py, it is saved in same directory with list_file.py. When you run list_file_path.py, it will first print out each command line argument when you invoke it and then show all the file or folder’s absolute path in the folder that you pass to the python file.
    # import system module.
    import sys
    import os
    
    # set dir_name's value to current folder by default.
    dir_name = './'
    
    # if invoke this scrpit with more than 1 argument.
    if len(sys.argv) > 1:
    
        i = 1
        # loop for all the args passed when this .py file is invoked.
        for arg in sys.argv:
                print('arg',i,'=',arg)
                i = i + 1
    
        # assign the first argument value to local variable dir_name. 
        dir_name = sys.argv[1]
    
    # list all the files in the dir_name directory and return them in a list.
    files_list = os.listdir(dir_name)
        
    # loop in above files_list
    for file in files_list:
        # print out each file absolute path.
        print(os.path.abspath(file))
    
  8. Add a new line cell in jupyter notebook, and run below command in it, then you will get current folder contained all files or folders’s absolute path listed.
    run list_file_path python script file in jupyter notebook line cell

    %run list_file_path.py ./

2. Invoke Python Script File From Ipython Command Line.

  1. Click the green triangle button of python virtual environment in anaconda environments list, then click Open Terminal menu item.
    python virtual environment open terminal menu item
  2. Then goto the python script file saved directory use cd command, and then run command ipython -i list_file.py like below. It will print out all files and folders name in current folder.
    (env_jupyter_example) C:\Users\song zhao>cd C:\WorkSpace\JupyterExampleProject\JupyterSlideBarExample
    
    (env_jupyter_example) C:\WorkSpace\JupyterExampleProject\JupyterSlideBarExample>DIR
     Volume in drive C has no label.
     Volume Serial Number is E6EE-6486
    
     Directory of C:\WorkSpace\JupyterExampleProject\JupyterSlideBarExample
    
    07/25/2020  09:48 PM    <DIR>          .
    07/25/2020  09:48 PM    <DIR>          ..
    07/25/2020  09:06 PM    <DIR>          .ipynb_checkpoints
    07/25/2020  09:48 PM             2,682 InvokePythonScript.ipynb
    07/25/2020  09:47 PM               665 list_file.py
    07/21/2020  09:31 AM               708 list_file_path.py
                   3 File(s)          4,055 bytes
                   3 Dir(s)  69,612,453,888 bytes free
    
    (env_jupyter_example) C:\WorkSpace\JupyterExampleProject\JupyterSlideBarExample>ipython -i list_file.py
    Python 3.7.6 (default, Jan  8 2020, 20:23:39) [MSC v.1916 64 bit (AMD64)]
    Type 'copyright', 'credits' or 'license' for more information
    IPython 7.12.0 -- An enhanced Interactive Python. Type '?' for help.
    .ipynb_checkpoints
    InvokePythonScript.ipynb
    list_file.py
    list_file_path.py
    
    In [1]: exit()
    
    (env_jupyter_example) C:\WorkSpace\JupyterExampleProject\JupyterSlideBarExample>
READ :   How To Add Interactive Widget ( Slide Bar ) In Jupyter Notebook

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.