Adding environment variables to bash.

Craig Allen callen314 at gmail.com
Thu Sep 11 17:02:25 EDT 2008


On Sep 11, 10:25 am, nntpman68 <news1... at free.fr> wrote:
> >> doesn't exactly work for Python scripts, though:
>
> >> $ cat env.py
> >> #!/usr/bin/env python
> >> import os
> >> os.environ["TEST"] = "hello"
>
> >> $ . ./env.py && env | grep TEST
> >> import: unable to open X server `'.
> >> bash: os.environ[TEST]: command not found
>
> >> </F>
>
> There's two options for the desperate ones.
>
> 1. Assuming the python script doesn't want to print anything useful
> =========================================================================
>
> the python script just prints the exoprt commands and is
> being called via backticks from a shell code snipped being sourced with .
>
> #-------- mypythonfile.py ------------------------
> #!/usr/bin/env python
> value = myfavourite_python_function()
> print 'export ENV_VAR="%s"' ^ value
> #--------------- end of file --------------
>
> #----------------- my_wrapper_file.sh ------------------
> `./mypythonfile.py`
> # file end
>
> and then you call
> . ./my_wrapper_file.sh
>
> 2._ Pytho script wants to display something and set a variable
> ===================================================================
>
> a file being invoked with . calls the python script (which will create a
> small file with variables to be set).
> then this created file is being sourced
>
> #-------- mypythonfile.py ------------------------
> #!/usr/bin/env python
> value = myfavourite_python_function()
> file('my_export_commands.sh','w').write('export ENV_VAR="%s"\n' % value)
> #--------------- end of file --------------
>
> #----------------- my_wrapper_file.sh ------------------
> ./mypythonfile.py
> . ./my_export_commands.sh
> # file end
>
> bye
>
> N
>
> Fredrik Lundh wrote:
> > John Lawrence wrote:
>
> >> You can make a command use the current shell though if you use the '.'
> >> command e.g.:
>
> >> jl > cat env.sh
> >> export TEST='hello'
>
> >> jl > ./env.sh && env | grep TEST          #Doesn't set TEST in parent
> >> shell
> >> jl > . ./env.sh && env | grep TEST          #Adding '. ' before the
> >> command uses the same shell
> >> TEST=hello
>
> > doesn't exactly work for Python scripts, though:
>
> > $ cat env.py
> > #!/usr/bin/env python
> > import os
> > os.environ["TEST"] = "hello"
>
> > $ . ./env.py && env | grep TEST
> > import: unable to open X server `'.
> > bash: os.environ[TEST]: command not found
>
> > </F>

oooh, clever but also... teh evil!  Ok not evil, but teh not-pretty.
But you did say "for the desperate" so good on you. cheers.



More information about the Python-list mailing list