Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 5067

Python • Re: How to get Python to use a custom library path

$
0
0
1. A virtual environment isn't going to happen in this context because it would totally break the entire robot ecosystem.

Then the program has a design flaw.

Usually, a program uses the Python standard libraries, 3rd party libraries (Packages and Modules) and own library code.
The own code does not have to be a PyPI package.

But you can still add additional search paths to sys.path.
This is not required, if the project has already the right directory structure.

e.G. if you run a main.py or something else, this path is added automatically to sys.path, which is used to find modules. Modules are just python-files.

Output:
C:\Users\XXX\TestProg>py main.py
Hello from main.py
Trying to import foo
foo module not found
Adding directory to sys.path
Hello from foo
Structure:

Code:

│   main.py│└───my_lib    └   foo.py 
main.py

Code:

print("Hello from main.py")print("Trying to import foo")try:    import fooexcept ImportError:    print("foo module not found")print("Adding directory to sys.path")import syssys.path.append("my_lib")import foo

Code:

print("Hello from foo")

You can also use the full qualified path of the module:

Code:

print("Hello from main.py")print("Importing foo")import my_lib.foo# my_lib is a NameSpaceprint(my_lib)
If the directory my_lib is not beside your Python Code you run, then you still have to add the path to your program directory.
But without knowing the structure, it's hard to say which takes lesser effort.

Statistics: Posted by DeaD_EyE — Wed Jul 03, 2024 9:54 am



Viewing all articles
Browse latest Browse all 5067

Trending Articles