Win XP: Problem with shell scripting in Python

Fredrik Lundh fredrik at
Fri Jun 9 09:19:22 CEST 2006

A.M wrote:

> It works very fine with DIR command, but for commands like "MD :" it doesn't 
> return the error message into the string:
> print os.popen('MD :').read()
> # No error message

in python, "MD" is spelled os.mkdir.

> Am I missing anything?

the difference between STDOUT and STDERR, and the difference between 
buffered output and non-buffered output, and perhaps a few other things 
related to how STDIO behaves on modern computers...  however, if you 
want to pretend that STDOUT and STDERR are the same thing, you can use 

 >>> o, i = os.popen4("md :")
'The filename, directory name, or volume label syntax is incorrect.\n'

or the subprocess module.

> Considering the fact that Ruby doesn't have any problem with redirecting
 > STDOUT into files or string variables, is Python the right tool for
 > this kinds of shell scripting?

rewriting BAT files as a series of os.system or os.popen calls isn't 
exactly optimal (neither for the computer nor the programmer nor the 
future user); better take an hour to skim the "generic operating system 
services" section in the library reference, and use built-in functions 
wherever you can:

the following modules are especially useful:

by using the built-in tools, you get better performance in many cases, 
better error handling, and code that's a lot easier to reuse (also on 
non-Windows platforms).


More information about the Python-list mailing list