How to capture environment state after running a shell script.
attn.steven.kuo at gmail.com
attn.steven.kuo at gmail.com
Tue Mar 13 14:54:39 EDT 2007
On Mar 13, 5:57 am, "Gerard Flanagan" <grflana... at yahoo.co.uk> wrote:
> 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?
>
(snipped)
> ########## 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
First close the input so that the (sub) process
knows to terminate and flush the output. Then,
you can read from the output:
import subprocess
import popen2
p = subprocess.Popen(["/bin/sh"], stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
p.stdin.write("env -i FOO=BAR\n")
p.stdin.close()
status = p.wait()
ret = p.stdout.readlines()
p.stdout.close()
print ret
# Or
cmdout, cmdin = popen2.popen2("/bin/sh")
cmdin.write("env -i FOO=BAR\n")
cmdin.close()
ret = cmdout.readlines()
cmdout.close
print ret
--
Hope this helps,
Steven
More information about the Python-list
mailing list