In Python script, how do I set PYTHONPATH?

前端 未结 6 1880
一个人的身影
一个人的身影 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:46

    You can get and set environment variables via os.environ:

    import os
    user_home = os.environ["HOME"]
    
    os.environ["PYTHONPATH"] = "..."
    

    But since your interpreter is already running, this will have no effect. You're better off using

    import sys
    sys.path.append("...")
    

    which is the array that your PYTHONPATH will be transformed into on interpreter startup.

提交回复
热议问题