What is sys.path[0] in python

In python, sys.path is a list of the folders that contains python modules.

The first element of sys.path list, or we can say sys.path[0], is a bit changeable.

For python REPL

python REPL means the interactive shell you get when you run python without any arguments.

In this way, sys.path[0] is simply a blank string "", it means current working directory.

For python file

If you run your python code in the way of running a file:

python /path/to/example.py

Then sys.path[0] is /path/to, which is the path of the folder containing example.py.

For python module

If you run your python code in the way of runnin a module:

python -m foo.bar.example

Then sys.path[0] is a blank string "", it means current working directory. It behaves the same as REPL.

Posted on 2022-03-25