In Python script, how do I set PYTHONPATH?

前端 未结 6 1868
一个人的身影
一个人的身影 2020-11-28 05:45

I know how to set it in my /etc/profile and in my environment variables.

But what if I want to set it during a script? Is it import os, sys? How do I do it?

6条回答
  •  -上瘾入骨i
    2020-11-28 06:38

    You don't set PYTHONPATH, you add entries to sys.path. It's a list of directories that should be searched for Python packages, so you can just append your directories to that list.

    sys.path.append('/path/to/whatever')
    

    In fact, sys.path is initialized by splitting the value of PYTHONPATH on the path separator character (: on Linux-like systems, ; on Windows).

    You can also add directories using site.addsitedir, and that method will also take into account .pth files existing within the directories you pass. (That would not be the case with directories you specify in PYTHONPATH.)

提交回复
热议问题