Thursday, 27 February 2020

How to set/export a directory in python sys path?

SET YOUR DIRECTORY PATH INTO PYTHON SYS PATH


Suppose you are creating module in python in a directory and you want this module to be accessed from any directory you open python IDLE or any editor.
e.g.
I have one test.py file created having below code snippet only.
def printname():
    print('hello world!')

That code is contained on this location. E:\Study\python\higher_order_functions\test.py
Now I have opened my IDLE or Terminal from other directory let’s say from E:\Study\python.
if you import test
It gives error: No module named 'test'
To overcome from this issue and you want this file to be accessed from every directory and make directory(E:\Study\python\higher_order_functions) global:
1   Open terminal from directory(E:\Study\python\higher_order_functions)
2   type py and hit enter button
3    if you are using window OS write set PYTHONPATH= higher_order_functions
4   if you are using Linux OS write export PYTHONPATH= higher_order_functions
5   That’s it. Now your higher_order_functions directory is set in python sys path.

To check if it is set in python sys path
1.     Import sys
2.     sys.path
3.     it gives you array of paths in that your directory would also be listed.
sys.path

No comments:

Post a Comment