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

In this article, I will tell you how to invoke a python script file (.py) from the 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 the 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 with the name InvokePythonScript.ipynb. ( There are also 2 python script files list_file.py and list_file_path.py which we will introduce later. )
  2. Click file InvokePythonScript.ipynb to edit it.
  3. Add the 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’ names in the folder which you pass to it as a 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’ names in the current directory.
    %%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 the above line cell to make it focus, then click the Run button at the 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 webserver started folder.
  6. Add another line cell and write the below code in it. Focus on the below line and click the Run button, you can see all files and folders’ names listed under the code line.
    %run -i list_file.py
    
    .ipynb_checkpoints
    InvokePythonScript.ipynb
    list_file.py
    list_file_path.py
  7. Create another python file with the IDLE editor or any text editor, save the python file as list_file_path.py, it is saved in the 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 the below command in it, then you will get the current folder contained all files or folders’ absolute path listed.
    %run list_file_path.py ./
    
    arg 1 = list_file_path.py
    arg 2 = ./
    C:\WorkSpace\.ipynb_checkpoints
    C:\WorkSpace\InvokePythonScript.ipynb
    C:\WorkSpace\list_file.py
    C:\WorkSpace\list_file_path.py

2. Invoke Python Script File From Ipython Command-Line.

  1. Click the green triangle button of the python virtual environment in the Anaconda environments list, then click the Open Terminal menu item.
  2. Then go to 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 the 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>
5 2 votes
Article Rating
Subscribe
Notify of
guest

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

1 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Brian Gygi
Brian Gygi

This site is not helpful. There are many many things they don’t explain, perhaps just assuming users know it

1
0
Would love your thoughts, please comment.x
()
x