Execute a BASH command in Python-- in the same process
You are calling a '.' shell command. This command means 'execute this shell file in current process'. You cannot execute shell file in Python process as Python is not a shell script interpreter.
The /home/b2v95/sqllib/db2profile
probably sets some shell environment variables. If you read it using system()
function, then the variables will be only changed in the shell executed and will not be visible in the process calling that shell (your script).
You can only load this file before starting your python script – you could make a shell wrapper script which would do . /home/b2v95/sqllib/db2profile
and execute your python script.
Other way would be to see what the db2profile
contains. If that are only NAME=value
lines, you could parse it in your python script and update os.environ
with the data obtained. If script does something more (like calling something else to obtain the values) you can reimplement whole script in Python.
Update An idea: read the script into python, pipe it (using Popen) to the shell, after the script write env
command to the same shell and read the output. This way you will get all the variables defined in the shell. Now you can read the variables.
Something like this:
shell = subprocess.Popen(["sh"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)script = open("/home/db2v95/sqllib/db2profile", "r").read()shell.stdin.write(script + "\n")shell.stdin.write("env\n")shell.stdin.close()for line in shell.stdout: name, value = line.strip().split("=", 1) os.environ[name] = value
you need to do:
subprocess.Popen(['.', '/home/db2v95/sqllib/db2profile'], shell=True)
Not sure what OS you are working on and what DB2 version you are using. The newer versions (at least 9.5 and above, not sure about 9.0 or 9.1) work by setting db2clp to **$$**
. Since the DB2 usually is a LUW it might work under linux/unix too. However, under AIX I need to run the profile script to connect to the right DB instance. Haven't checked too much into what that script does.