How to capture environment state after running a shell script.

Gerard Flanagan grflanagan at yahoo.co.uk
Tue Mar 13 08:57:37 EDT 2007


Hello,

I have a third party shell script which updates multiple environment
values, and I want to investigate (and ultimately capture to python)
the environment state after the script has run. But running the script
as a child process only sets values for that process, which are lost
after execution.  So I thought I could simply tack on an 'env' command
line to the script input lines as shown below. However, using
subprocess.Popen gives the error shown (even though the docs say that
any file object may be used for stdin), and using popen2 hangs
indefinitely. I think I'm missing something basic, any advice? Or is
there a better approach?

(This is Python 2.4 and a Korn shell script on AIX Unix)

Thanks in advance.

from StringIO import StringIO
from subprocess import Popen
from popen2 import popen2

fname = '/opt/WebSphere/AppServer/bin/setupCmdLine.sh'

buf = StringIO()

f = open(fname, 'r')

try:
    f.readline() #ignore shebang
    for line in f:
        buf.write(line)
finally:
    f.close()

buf.write('\nenv\n')

buf.seek(0)

########## first method ##########
p = Popen('/bin/sh', stdin=buf)
print p.stdout.readlines()

Traceback (most recent call last):
  File "scratch.py", line 36, in ?
    p = Popen('/bin/sh', stdin=buf)
  File "/usr/local/lib/python2.4/subprocess.py", line 534, in __init__
    (p2cread, p2cwrite,
  File "/usr/local/lib/python2.4/subprocess.py", line 830, in
_get_handles
    p2cread = stdin.fileno()
AttributeError: StringIO instance has no attribute 'fileno'

########## second method ##########
cmdout, cmdin = popen2('/bin/sh')
for line in buf:
    cmdin.write(line)

ret = cmdout.readlines()
cmdout.close()
cmdin.close()

print ret




More information about the Python-list mailing list