From: Kevin B. <kb...@ca...> - 2002-01-24 15:54:56
|
Syver Enstad wrote: > > Syver Enstad <syv...@on...> writes: > > Here's a quick hack os.popen, it only works for reading at the time, > > but would be easy to fix I believe. > > > > def popen(path, mode='r'): > > r = java.lang.Runtime.getRuntime() > > p = r.exec(path) > > if mode == 'w': > > return org.python.core.PyFile(p.getInputStream()) > > elif mode == 'r': > > return org.python.core.PyFile(p.getOutputStream()) > > else: > > raise OSError(0, "Invalid mode", mode) > > the only trouble I have so far is that the right ctor for PyFile > doesn't seem to be because, the PyFile returned is always a PyFile in > read mode, even though PyFile has one ctor for java.io.InputStream and > one for java.io.OutputStream. This is because of the wonderful naming convention of the getInputStream/getOutputStream methods :-) : Process.getOutputStream() returns an OutputStream representing stdin (so you can write to the process's stdin) Process.getInputStream() returns an InputStream representing stdout (so you read the process's stdout) Process.getErrorStream() returns an InputStream representing stderr This suggests you need to reverse the 'r' and 'w', and probably end up w/ something like this: import java import org def popen(path, mode='r'): r = java.lang.Runtime.getRuntime() p = r.exec(path) return org.python.core.PyFile( p.getInputStream(), p.getOutputStream(), mode ) f = popen( "echo hello" ) print f.read() f.close() f = popen( "cat" ) f.write( "This is\na test\nof write\n" ) f.flush() for i in range( 3 ): print f.readline(), f.close() try: popen( "set" ) assert "Should throw IOException: CreateProcess "\ "because set is a built-in" except java.io.IOException: print "shell built-ins not supported, " \ "because we're not invoking a shell" Note the following caveats: 1- PyFile is an internal class. It may change! Don't rely on it in code you expect to keep working later. 2- To get stderr, we'd need to do some wrapping of the stdout & stderr streams into one. 3- I don't think the mode handling is quite right. :-) 4- Shell built-ins don't work, because we're not invoking a shell kb > > > -- > > Vennlig hilsen > > Syver Enstad > > _______________________________________________ > Jython-users mailing list > Jyt...@li... > https://lists.sourceforge.net/lists/listinfo/jython-users |