0

I am trying to do the following:

setenv PRJ_ROOT /home/to/proj_dir
setenv VAR1 /home/user/john/to/proj_dir/design_files
setenv VAR2 /home/user/john/to/proj_dir/model_files
....
....
....
setenv VARN /home/user/john/to/proj_dir/random_files

So, if I have all the above commands in a file say "setup" I can simply call "source setup" to set all the env variable. But Now i wish to make it generic with respect to the path.

I have tried subprocess.call and os.environ to set up the path but didn't get any success. My code is below. I am quite new to python and trying to build on this skill, please guide.

#!/usr/bin/python
import os
import subprocess
cmd1 = "setenv VAR1 path"
cmd2 = "setenv VAR1 path"
...
...
...
path = os.getcwd()
var1Path = path + '/design_files'
var2Path = path + '/model_files'
...
...
...

#try 1
os.environ['VAR1'] = var1Path
os.environ['VAR2'] = var2Path
....
....

#try 2
subprocess.call(cmd1, shell=True)
#(or)
subprocess.call(cmd1, shell=True, executable='/bin/bash')
#(or)
subprocess.call(['/bin/bash','-i','-c', cmd1])
#(or)
subprocess.Popen(['/bin/sh', cmd])

#NOTE: tried both /bin/sh and also /bin/bash

Expected result: after the running script, if I do "echo $VAR1" output should be the complete path.

Actual result:

/bin/sh: setenv: command not found
(or)
bash: setenv: command not found
arajshree
  • 626
  • 4
  • 13

3 Answers3

1

setenv is not valid keyword in bash shell, try export

here is some help:

Setting environment variables in Linux using Bash

1

I think your intention might be to set variables in the environment of the parent, which is not possible.

Other answers show how you can set them for children.

Therefore, if you want to set environment variables of your current bash you can create a script that spits the sentences and then you eval them.

$ ./setenv.py
export VAR1=path
export VAR2=path

then

$ eval $(./setenv.py)
Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134
0

I think you are mixing your shells. 'setenv' is part of csh and not part of bash.

If I understand your requirement, you want to set some variables in the python process' environment, and make them available to child processes.

Here is an example:

#!/usr/bin/python
import os
import subprocess

path=os.getcwd()

var1Path=path+'/design_files'
var2Path=path+'/model_files'

os.environ['VAR1']=var1Path
os.environ['VAR2']=var2Path

cmd1='echo $VAR1 $VAR2'
print 'cmd1='+cmd1
subprocess.call(cmd1,shell=True)

Result is:

echo $VAR1 $VAR2
/var/tmp/design_files /var/tmp/model_files

The subprocess knows about the bash variables.

DavidG
  • 399
  • 2
  • 10