0

There is some python code at my company that uses sys.path[0] in some file paths. Generally, everybody's sys.path[0] points to c:\\<user.name>\\workspace and I believe mine used to as well. However, now my sys.path[0] is c:\\users\\<user.name>\\repos\\venv\\lib\\site-packages\\git\\ext\\gitdb so obviously these paths are now incorrect on my local and causing errors.

My questions are what would cause this change in my local sys.path and if it is bad practice to use sys.path because of situations like this. What should we use in this case instead?

This is all for python code running on a flask server.

Kevin
  • 59
  • 1
  • 5
  • 1
    Relying on the order of `sys.path` seems like a terrible idea. It can change because you're using a virtual environment, because something has explicitly set `sys.path`, etc. – larsks Jan 28 '21 at 21:26
  • If it assumes `~/workspace`, then just use that – OneCricketeer Jan 28 '21 at 21:27
  • It's a bad practice. `sys.path` should only be used to affect where module lookups occur, not accessed directly. – chepner Jan 28 '21 at 21:27
  • More to the point, *why* does the script need to lookup `sys.path[0]` anyway? What's it trying to find? User files? User executables? Python modules? (Anyway, even just within a Windows shop, users can set/prepend any custom PATHs they want. ) – smci Jan 28 '21 at 21:33
  • why not `~/workspace` (with `os.path.expanduser()` ) or `$HOME/workspace` (with `os.path.expandvars()`) but this probably path for Linux and Windows may need something like `%UserProfile%\workspace` – furas Jan 29 '21 at 00:32

1 Answers1

0

It is not safe, because, as it says in comments, lots of things can modify the order of sys.path.

As a workaround, you can import some file in workspace and then get the directory:

import something_in_workspace
workspace = os.path.dirname(something_in_workspace.__file__)

Usually it is needed to retrieve data files. Better is to package your project and use importlib.resources. See How to read a (static) file from inside a Python package?

Balaïtous
  • 826
  • 6
  • 9