Keeping os context possible? Re: Python a good thing for sysadmins ?

Donn Cave donn at drizzle.com
Thu Sep 13 23:52:19 EDT 2001


Quoth Magnus Lycka <magnus at thinkware.se>:
... [ interacting with a separate application process ]

| Can I achieve this from inside python? To be honest, I haven't
| even quite understood how to use stdin with popen. Could that
| somehow be used to achieve this? (And by the way, isn't the manual
| page on popen2 wrong? "Returns the file object (child_stdout,
| child_stdin)" Or am I confused here?

You're not the first one to be confused by this.  os.popen2 just
calls popen2.popen2, but reverses the return.  So if you're reading
the documentation for os.popen2, it should say "(child_stdin, child_stdout)".
Don't look at me.

| To return to the subject: Is the solution some expect-like
| thingie? And in that case, which, if I want it to work on
| both Windows and Linux?

Yes, the only way that will reliably work with just any application
is through a pseudotty device, which is expect's specialty.  Support
for pty devices is a lot better in 2.0 and later, with the openpty
function in the posix module, but it's far from universal and to my
knowledge is limited to the UNIX world.

A few applications, that don't buffer their output, can be used with
simple pipes, though - here's a simplistic example for your amusement.

import os
from popen2 import Popen3

class Shell(Popen3):
	def __init__(self):
		Popen3.__init__(self, ('sh',))
	def execute(self, line):
		os.write(self.tochild.fileno(), line + '\n')
		return os.read(self.fromchild.fileno(), 8192)

s = Shell()
print repr(s.execute('uname -a'))
print repr(s.execute('date'))

	Donn Cave, donn at drizzle.com



More information about the Python-list mailing list