Set an environment variable

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Christian

    Set an environment variable

    Another question from a not even newbie:

    In Unix you can set an environment variable with the command
    export PYTHONPATH
    but I would like to set the variable from at .py script.

    So my question is:
    How do I export an environment variable in a .py script?


    Thanks

    Chris
  • the_crazy88

    #2
    Re: Set an environment variable

    Just use
    os.system("expo rt PYTHONPATH = %s" %("your_pythonp ath"))

    Comment

    • jepler@unpythonic.net

      #3
      Re: Set an environment variable

      In Unix, you generally can't affect the environment of your parent program (in
      a broad sense, which includes environment variables, current working directory,
      opened files, effective user ID, etc).

      You have two basic choices to achieve an effect like this. First, you can
      start a subshell with the desired environment, something like (untested)
      os.environ['VARIABLE'] = 'value'
      os.system(os.en viron['shell'])
      (commands like 'su' work in this way)

      Second, you can produce shell commands that have the effect of changing a
      shell's environment when they are executed. Something like:
      print "VARIABLE=value "
      To use this, the user must write something like
      eval `myscript.py`
      instead of just
      myscript.py
      this can typically be encapsulated in a shell alias or function.
      (commands like 'resize' (which sets the shell's idea of a terminal's size) work
      this way)

      Finally, you might be able to use an OS-specific interface like linux' ptrace
      to change the actual contents of a calling process's memory. I didn't
      immediately find an example of this, but on Linux it would consist of using
      PTRACE_PEEKDATA and PTRACE_POKEDATA to locate the environment in another
      process and modify it. The ptrace interface is not available from any standard
      Python module, and isn't portable anyway. (though my manpage actually says
      'CONFORMING TO SVr4, ..., X/OPEN, BSD 4.3' so maybe ptrace is more portable
      than I believed)

      Jeff

      -----BEGIN PGP SIGNATURE-----
      Version: GnuPG v1.4.1 (GNU/Linux)

      iD8DBQFDV4sxJd0 1MZaTXX0RAj4aAJ 41BlvbrZxLNrhm+ Ea5bgMyZOkVwQCg lsLw
      wFB6iqRqw3FRzno zCpV5qh0=
      =MqJa
      -----END PGP SIGNATURE-----

      Comment

      • Christian

        #4
        Re: Set an environment variable

        Thanks Jeff and the crazy 88.

        Comment

        • Eric Brunel

          #5
          Re: Set an environment variable

          On 20 Oct 2005 01:58:44 -0700, the_crazy88 <python@gentool inux.demon.nl> wrote:
          [color=blue]
          > Just use
          > os.system("expo rt PYTHONPATH = %s" %("your_pythonp ath"))[/color]

          .... except it won't work: os.system will execute the command in a new process, so the environment variable change will only be visible in *this* process. Since you don't do anything else, the environment variable change will never be seen by anyone.

          As for the OP's question, the short answer is "you can't": the Python interpreter will always be executed in a different process than the calling shell, and environment variable changes *never* impact the calling process on Unix.

          The closest thing you can do is that:

          -myScript.py--------------------------------------
          print 'export MY_VARIABLE=val ue'
          --------------------------------------------------

          -myScript.sh--------------------------------------
          python myScript.py > /tmp/chgvars.sh
          .. /tmp/chgvars.sh
          --------------------------------------------------

          This is quite ugly: you write the shell commands changing the environment variables to a file, then "source" this file in the calling shell. But this is probably the best way to do what you want.

          HTH
          --
          python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz 5(17;8(%,5.Z65\ '*9--56l7+-'])"

          Comment

          • Grant Edwards

            #6
            Re: Set an environment variable

            On 2005-10-20, the_crazy88 <python@gentool inux.demon.nl> wrote:
            [color=blue]
            > os.system("expo rt PYTHONPATH = %s" %("your_pythonp ath"))[/color]

            No, that won't work.

            That will set the environment variable in the shell spawned by
            the os.system command. That shell will then immediately exit,
            leaving the caller's environment unchanged.

            --
            Grant Edwards grante Yow! Are you mentally here
            at at Pizza Hut??
            visi.com

            Comment

            • Grant Edwards

              #7
              Re: Set an environment variable

              On 2005-10-20, Christian <christian@spam .not> wrote:
              [color=blue]
              > How do I export an environment variable in a .py script?[/color]



              --
              Grant Edwards grante Yow! My BIOLOGICAL ALARM
              at CLOCK just went off... It
              visi.com has noiseless DOZE FUNCTION
              and full kitchen!!

              Comment

              • Mike Meyer

                #8
                Re: Set an environment variable

                "Eric Brunel" <eric_brunel@de spammed.com> writes:[color=blue]
                > -myScript.py--------------------------------------
                > print 'export MY_VARIABLE=val ue'
                > --------------------------------------------------
                >
                > -myScript.sh--------------------------------------
                > python myScript.py > /tmp/chgvars.sh
                > . /tmp/chgvars.sh[/color]

                It's simpler to use eval and command substitution:

                eval $(python myScript.py)

                <mike

                --
                Mike Meyer <mwm@mired.or g> http://www.mired.org/home/mwm/
                Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.

                Comment

                • Christian

                  #9
                  Re: Set an environment variable

                  >[color=blue]
                  > The closest thing you can do is that:
                  >
                  > -myScript.py--------------------------------------
                  > print 'export MY_VARIABLE=val ue'
                  > --------------------------------------------------
                  >
                  > -myScript.sh--------------------------------------
                  > python myScript.py > /tmp/chgvars.sh
                  > . /tmp/chgvars.sh
                  > --------------------------------------------------[/color]

                  Can I write a .py script that calls a .sh script that executes the
                  export command and then calls another .py script (and how would the
                  first .py script look)?

                  That would be much more what is my basic problem.


                  Thanks

                  Chris

                  Comment

                  • Erik Max Francis

                    #10
                    Re: Set an environment variable

                    Christian wrote:
                    [color=blue]
                    > Can I write a .py script that calls a .sh script that executes the
                    > export command and then calls another .py script (and how would the
                    > first .py script look)?[/color]

                    No, the shell script that the Python program would invoke would be a
                    different process and so commands executed in it would have no effect on
                    the state of another.

                    --
                    Erik Max Francis && max@alcyone.com && http://www.alcyone.com/max/
                    San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
                    Success and failure are equally disastrous.
                    -- Tennessee Williams

                    Comment

                    • Christian

                      #11
                      Re: Set an environment variable

                      Erik Max Francis wrote:[color=blue]
                      > Christian wrote:
                      >[color=green]
                      >> Can I write a .py script that calls a .sh script that executes the
                      >> export command and then calls another .py script (and how would the
                      >> first .py script look)?[/color]
                      >
                      > No, the shell script that the Python program would invoke would be a
                      > different process and so commands executed in it would have no effect on
                      > the state of another.
                      >[/color]

                      So executing an .sh script that calls a .py script works different when
                      executed from a command promt than when executed from a starter .py script?

                      Comment

                      • Sybren Stuvel

                        #12
                        Re: Set an environment variable

                        Mike Meyer enlightened us with:[color=blue]
                        > It's simpler to use eval and command substitution:
                        >
                        > eval $(python myScript.py)[/color]

                        This looks like the best solution to me.

                        Sybren
                        --
                        The problem with the world is stupidity. Not saying there should be a
                        capital punishment for stupidity, but why don't we just take the
                        safety labels off of everything and let the problem solve itself?
                        Frank Zappa

                        Comment

                        • Steve Holden

                          #13
                          Re: Set an environment variable

                          Christian wrote:[color=blue][color=green]
                          >>The closest thing you can do is that:
                          >>
                          >>-myScript.py--------------------------------------
                          >>print 'export MY_VARIABLE=val ue'
                          >>--------------------------------------------------
                          >>
                          >>-myScript.sh--------------------------------------
                          >>python myScript.py > /tmp/chgvars.sh
                          >>. /tmp/chgvars.sh
                          >>--------------------------------------------------[/color]
                          >
                          >
                          > Can I write a .py script that calls a .sh script that executes the
                          > export command and then calls another .py script (and how would the
                          > first .py script look)?
                          >
                          > That would be much more what is my basic problem.
                          >[/color]
                          You can do what you suggest without shell scripting, unless I
                          misunderstand your intention: just set the environment variables you
                          want your Python script to see and then run it using os.system():

                          ::::::::::::::
                          one.py
                          ::::::::::::::
                          import os
                          os.environ['STEVE'] = "You are the man"
                          os.system("pyth on two.py")
                          print "Ran one"
                          ::::::::::::::
                          two.py
                          ::::::::::::::
                          import os
                          print "STEVE is", os.environ['STEVE']
                          print "Ran two"
                          [sholden@headrat tmp]$ python one.py
                          STEVE is You are the man
                          Ran two
                          Ran one
                          [sholden@headrat tmp]$

                          Hope this helps.

                          regards
                          Steve
                          --
                          Steve Holden +44 150 684 7255 +1 800 494 3119
                          Holden Web LLC www.holdenweb.com
                          PyCon TX 2006 www.python.org/pycon/

                          Comment

                          • Chris F.A. Johnson

                            #14
                            Re: Set an environment variable

                            On 2005-10-21, Christian wrote:[color=blue]
                            > Erik Max Francis wrote:[color=green]
                            >> Christian wrote:
                            >>[color=darkred]
                            >>> Can I write a .py script that calls a .sh script that executes the
                            >>> export command and then calls another .py script (and how would the
                            >>> first .py script look)?[/color]
                            >>
                            >> No, the shell script that the Python program would invoke would be a
                            >> different process and so commands executed in it would have no effect on
                            >> the state of another.
                            >>[/color]
                            >
                            > So executing an .sh script that calls a .py script works different when
                            > executed from a command promt than when executed from a starter .py script?[/color]

                            No; it's always the same: an environment variable will only be
                            effective in the process in which it is set, and its children.

                            When you call another program, whether it's a shell script, python
                            script, or binary executable, you are starting a new process.
                            Environment variables set in that process will not affect its
                            parent (i.e., the process that called it).

                            --
                            Chris F.A. Johnson <http://cfaj.freeshell. org>
                            =============== =============== =============== =============== ======
                            Shell Scripting Recipes: A Problem-Solution Approach, 2005, Apress
                            <http://www.torfree.net/~chris/books/cfaj/ssr.html>

                            Comment

                            • Christian

                              #15
                              Re: Set an environment variable

                              Steve Holden wrote:
                              [color=blue]
                              > ::::::::::::::
                              > one.py
                              > ::::::::::::::
                              > import os
                              > os.environ['STEVE'] = "You are the man"
                              > os.system("pyth on two.py")
                              > print "Ran one"
                              > ::::::::::::::
                              > two.py
                              > ::::::::::::::
                              > import os
                              > print "STEVE is", os.environ['STEVE']
                              > print "Ran two"
                              > [sholden@headrat tmp]$ python one.py
                              > STEVE is You are the man
                              > Ran two
                              > Ran one
                              > [sholden@headrat tmp]$
                              >
                              > Hope this helps.
                              >
                              > regards
                              > Steve[/color]

                              Thanks Steve, you're quite right, you are the man. And thanks to all the
                              rest of you for your kind help and patient understanding. I have learned
                              quite a lot and is about to consider my self advanced to the status of
                              Python newbie.

                              So here is my final question:
                              Do I call the .sh script with a .py script like this:

                              os.system("/path/to/the/script/startupscript.s h")

                              Comment

                              Working...