xtlc
xtlc

Reputation: 1368

Python add windowsPath to sys.path

I need to dynamically add packages which are created on the fly to my sys.path. I have a some.py file holding a method that in the directory media\TEMP:

This code works:

sys.path.append("""C:\\Users\\admin\\Desktop\\tools\\testtool\\media\\TEMP""")

this results in:

[
...
'C:\\Users\\admin\\Desktop\\tools\\\testTool\\venv', 
'C:\\Users\\admin\\Desktop\\tools\\\testTool\\venv\\lib\\site-packages', 
'C:\\Users\\admin\\Desktop\\tools\\\testTool\\media\\TEMP'
]

and importlib.import_module(f"{some}.{that}") works. But this does not work:

sys.path.append(Path.cwd().parent.joinpath("media", "TEMP"))

this results in:

[
... 
'C:\\Users\\admin\\Desktop\\tools\\\testTool\\venv', 
'C:\\Users\\admin\\Desktop\\tools\\\testTool\\venv\\lib\\site-packages', 
WindowsPath('C:/Users/admin/Desktop/tools/testTool/media/TEMP'
]

and this fails with a ModuleNotFoundError. Can't a windows path be in the sys.path? I also tried Path.resolve() with no success.

Upvotes: 1

Views: 1255

Answers (1)

AKX
AKX

Reputation: 168913

You can't put pathlib.Path objects (including WindowsPath) in sys.path, only plain strings.

In other words, you'll need to call str(...) on them:

sys.path.append(str(Path.cwd().parent.joinpath("media", "TEMP")))

Upvotes: 3

Related Questions