Importing function from a py file while using the Python shell

enter image description here

I'm using the Python shell since i'm learning this programming language.

I've found a simple script on Github and i would like to save it as a python file and then import it while I'm using the Python shell, in order to use a function declared in this script.

In order to be imported from the Python shell, in which path do i need to save this script ? (I'm on Ubuntu)

1 answer

  • answered 2020-05-22 12:44 Alexander Pushkarev

    There're several points to consider:

    1) Is downloading the script from Github is the only option? Many python libraries would be possible to install using pip, which will make it possible just to import library:

    pip install mylibrary

    2) If it is not possible, please refer to python import system explained here

    When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named in a list of directories given by the variable sys.path. sys.path is initialized from these locations:

    1) The directory containing the input script (or the current directory when no file is specified).
    2) PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
    3) The installation-dependent default.

    It seems that in your case it should be enough to start python shell from the same folder where the downloaded script is.

    Note: it is not always legally possible to just download the script from github and use it, make sure to check the license.