jython - how to call command.com?

Alex Martelli aleax at aleax.it
Sat Jan 26 06:01:05 EST 2002


charles wrote:

> I'm using Jython on Windows. How can I execute from it a DOS command
> line, wait till it finishes and return?

I'm not sure if there are shortcuts, but you can do it via java's underlying
libraries, for example:

>>> import java
>>> p = java.lang.Runtime.getRuntime().exec('ls')
>>> fin = 
java.io.BufferedReader(java.io.InputStreamReader(p.getInputStream())) 
>>> while 1:
...   line = fin.readLine()
...   if not line: break
...   print line
...

I think this should work in DOS, too, using e.g. 'command.com' instead of
'ls', but I don't currently have a Jython installation on DOS to try it out.

If the external program you want to run does not emit its results on 
standard output (command.com might well not), you don't have to
work via java.io's classes -- you might well just call p.waitFor() to
wait for process p to finish, for example.

Note that, when you need to get as coupled to the underlying platform
as this, it's unlikely (though not impossible) that Jython can serve you
better than Classic Python.  Jython's main strength is after all the
ability to run on any JVM, independently of the underlying platform.
However, it can happen that the reason for choosing Jython is not
platform-independence but, for example, access to certain specific
Java-only libraries, in which case this kind of platform coupling may
of course be OK.


Alex




More information about the Python-list mailing list