I use python3 with emacs (editor and shell) under Linux OS. Why the cwd is not in the sys.path ?? How can we put it, for all sessions !! I Thank you.
sys. path is a built-in variable within the sys module. It contains a list of directories that the interpreter will search in for the required module. When a module(a module is a python file) is imported within a Python file, the interpreter first searches for the specified module among its built-in modules.
path is just a list, you can add new paths. In this example, the append() method is used, but you can also use the insert() method and so on. If you import after adding a path to sys. path , you can import the modules in the added path.
PYTHONPATH is related to sys. path very closely. PYTHONPATH is an environment variable that you set before running the Python interpreter. PYTHONPATH , if it exists, should contain directories that should be searched for modules when using import .
You do not want to add cwd()
to the sys.path
. Always adding cwd()
would be a terrible idea as you can no longer control what files are available for import.
Python adds the directory of the script being executed instead.
E.g. when you run:
python.exe path/to/script.py
then path/to
is automatically added to the sys.path
.
Only if you run a script from the current directory is ''
added to the start of the path, meaning the current working directory is searched for imports. E.g. when you run python.exe localfile.py
then Python does add the current working directory, in the assumption you wont't change the current working directory while importing.
See Interface options in the Command line and environment documentation:
If the script name refers directly to a Python file, the directory containing that file is added to the start of
sys.path
, and the file is executed as the__main__
module.
and the sys.path
documentation:
As initialized upon program startup, the first item of this list,
path[0]
, is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input),path[0]
is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result ofPYTHONPATH
.
You can always add the current working directory to sys.path
explicitly:
import sys
if sys.path[0] != '':
sys.path.insert(0, '')
Be careful, any python file or package in that working directory with a name matching a module you are already using in your code will mask that module, easily leading to breakage.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With