In Python script, how do I set PYTHONPATH?

前端 未结 6 1905
一个人的身影
一个人的身影 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条回答
  •  感动是毒
    2020-11-28 06:35

    If you put sys.path.append('dir/to/path') without check it is already added, you could generate a long list in sys.path. For that, I recommend this:

    import sys
    import os # if you want this directory
    
    try:
        sys.path.index('/dir/path') # Or os.getcwd() for this directory
    except ValueError:
        sys.path.append('/dir/path') # Or os.getcwd() for this directory
    

提交回复
热议问题