Why can't environmental variables set in python persist?

前端 未结 7 773
南旧
南旧 2020-11-27 03:55

I was hoping to write a python script to create some appropriate environmental variables by running the script in whatever directory I\'ll be executing some simulation code,

7条回答
  •  独厮守ぢ
    2020-11-27 04:23

    One workaround is to output export commands, and have the parent shell evaluate this..

    thescript.py:

    import pipes
    import random
    r = random.randint(1,100)
    print("export BLAHBLAH=%s" % (pipes.quote(str(r))))
    

    ..and the bash alias (the same can be done in most shells.. even tcsh!):

    alias setblahblahenv="eval $(python thescript.py)"
    

    Usage:

    $ echo $BLAHBLAH
    
    $ setblahblahenv
    $ echo $BLAHBLAH
    72
    

    You can output any arbitrary shell code, including multiple commands like:

    export BLAHBLAH=23 SECONDENVVAR='something else' && echo 'everything worked'
    

    Just remember to be careful about escaping any dynamically created output (the pipes.quote module is good for this)

提交回复
热议问题