how do I modify the system path variable in python script?

前端 未结 3 823
逝去的感伤
逝去的感伤 2020-12-09 11:39

I\'m trying to run a python script from cron, but its not running properly so I\'m assuming its the different path env variable. Is there anyway to change the variable withi

相关标签:
3条回答
  • 2020-12-09 12:19

    @ubuntu has the right approach, but for what it's worth, @Joe Schmoe, if you ever need the info:

    import sys
    print sys.path
    ['.', '/usr/local/bin', '/usr/local/lib/python2.6/dist-packages',...]
    sys.path.append('/home/JoeBlow/python_scripts')
    print sys.path
    ['.', '/usr/local/bin', '/usr/local/lib/python2.6/dist-packages', '/home/JoeBlow/python_scripts',...]
       

    sys.path is an array containing everything that was in your initiating script's PYTHONPATH variable (or whatever your shell's default PYTHONPATH is).

    0 讨论(0)
  • 2020-12-09 12:20

    While the accepted answer works for the OP's purposes, and while the second answer is correct for updating the python sys.path variable, I think, if the OP weren't able to use the accepted answer (because, say, there was a policy against modifying the OS PATH variable on build/test machines), something like this SO answer would be what they are looking for. Summarizing the simple case here, to change the OS PATH environment variable:

    app_path = os.path.join(root_path, 'other', 'dir', 'to', 'app')
    os.environ["PATH"] += os.pathsep + app_path
    

    At least, this is what I was hoping to find when I read the question.

    0 讨论(0)
  • 2020-12-09 12:40

    You shouldn't need to set the PATH from within the python script. Instead, put something like

    USER=joe
    HOME=/home/joe
    SHELL=/bin/bash
    PATH=/sbin:/bin:/usr/sbin:/usr/bin:/some/other/path
    PYTHONPATH=/home/joe/pybin
    MAILTO=joe
    LANG=en_US.UTF-8
    
    #min hr    day   mon dow
    */5  12    *     *   *     reminder.py 'Eat lunch'
    

    at the top of your crontab. These environment variables will then be available to all cron jobs run through your crontab.

    0 讨论(0)
提交回复
热议问题