I have a custom PyPi
package. It is installed under Pyhon\Python38\Lib\site-packages\myCustomPackage
.
In the __init__
code for myCustomPackage
, I perform a few different directory operations, which failed to find the correct files and directories which reside in the Pyhon\Python38\Lib\site-packages\myCustomPackage
folder.
I looked at the output of os.getcwd()
and it showed the cwd
to be C:\Users\TestUser
, which is the root Windows user folder.
I would like the root folder to be the myCustomPackage
folder.
For example, the file \myCustomPackage\__init__.py
would contain
import os
class myCustomPackage():
def __init__(self):
print(os.getcwd())
If I run:
from myCustomPackage import myCustomPackage
theInstance = myCustomPackage()
The output is:
C:\Users\TestUser
How can I change that to be C:\Users\TestUser\AppData\Local\Programs\Python\Python38\Lib\site-packages\myCustomPackage
?
Note : I would want it to be dynamic. No hard coding, in case the python version changes or the Windows user changes.
CodePudding user response:
My solution was the following function:
import site
import os
import traceback
def changeCWD(self):
try:
sitePackages = site.getsitepackages()
site_packages_dir = sitePackages[1]
top_module_dir = site_packages_dir os.path.sep "myCustomPackage"
os.chdir(top_module_dir)
return True
except:
self.myLogger.error("An error occurred in changeCWD")
tb = traceback.format_exc()
self.myLogger.exception(tb)
return False
CodePudding user response:
To get the directory path of the current module, you can use the built-in __file__
.
To set the cwd
to the module directory, use:
import os
import sys
from pathlib import Path
class myCustomPackage():
def __init__(self):
module_directory = Path(__file__).parent
os.chdir(module_directory)
print(os.getcwd())