How to use export with Python on Linux

后端 未结 12 1521
梦如初夏
梦如初夏 2020-11-29 23:09

I need to make an export like this in Python :

# export MY_DATA=\"my_export\"

I\'ve tried to do :

# -*- python-mode -*-
# -         


        
相关标签:
12条回答
  • 2020-11-29 23:16

    Not that simple:

    python -c "import os; os.putenv('MY_DATA','1233')"
    $ echo $MY_DATA # <- empty
    

    But:

    python -c "import os; os.putenv('MY_DATA','123'); os.system('bash')"
    $ echo $MY_DATA #<- 123
    
    0 讨论(0)
  • 2020-11-29 23:17

    You actually want to do

    import os
    os.environ["MY_DATA"] = "my_export"
    
    0 讨论(0)
  • 2020-11-29 23:18

    Another way to do this, if you're in a hurry and don't mind the hacky-aftertaste, is to execute the output of the python script in your bash environment and print out the commands to execute setting the environment in python. Not ideal but it can get the job done in a pinch. It's not very portable across shells, so YMMV.

    $(python -c 'print "export MY_DATA=my_export"')
    

    (you can also enclose the statement in backticks in some shells ``)

    0 讨论(0)
  • 2020-11-29 23:19

    export is a command that you give directly to the shell (e.g. bash), to tell it to add or modify one of its environment variables. You can't change your shell's environment from a child process (such as Python), it's just not possible.

    Here's what's happening when you try os.system('export MY_DATA="my_export"')...

    /bin/bash process, command `python yourscript.py` forks python subprocess
     |_
       /usr/bin/python process, command `os.system()` forks /bin/sh subprocess
        |_
          /bin/sh process, command `export ...` changes its local environment
    

    When the bottom-most /bin/sh subprocess finishes running your export ... command, then it's discarded, along with the environment that you have just changed.

    0 讨论(0)
  • 2020-11-29 23:26

    Kind of a hack because it's not really python doing anything special here, but if you run the export command in the same sub-shell, you will probably get the result you want.

    import os
    
    cmd = "export MY_DATA='1234'; echo $MY_DATA" # or whatever command
    os.system(cmd)
    
    0 讨论(0)
  • 2020-11-29 23:26
    import os
    import shlex
    from subprocess import Popen, PIPE
    
    
    os.environ.update(key=value)
    
    res = Popen(shlex.split("cmd xxx -xxx"), stdin=PIPE, stdout=PIPE, stderr=PIPE,
                env=os.environ, shell=True).communicate('y\ny\ny\n'.encode('utf8'))
    stdout = res[0]
    stderr = res[1]
    
    
    0 讨论(0)
提交回复
热议问题