os.popen command working differently on Windows

Hans Mulder hansmu at xs4all.nl
Fri May 13 13:10:44 EDT 2011


On 12/05/2011 16:21, Tim Golden wrote:
> On 12/05/2011 15:11, Ayaskanta Swain wrote:
>> Please help me in solving the following issue I am facing while
>> executing my python script. Basically I am executing the OS specific
>> move command to move a file/dir from one location to another.
>
> Why? Why not use os.rename or shutil.move which already do
> whatever is needed under the covers for different Operating Systems?
>
> os.popen returns a file-like object from which you can read any
> error messages generated. You're not doing that, and os.popen
> won't raise an error itself unless you, say, pass it a number
> rather than a string.
>
> <code>
> import os
>
> output = os.popen ("dir")
> print output.read ()
>
> #
> # But note:
> #
> os.popen ("Nonsen*se")
>
> # raises no exception
>
> </code>

If you want exceptions, try the subprocess module:

 >>> import subprocess
 >>> subprocess.Popen("Nonsen*se")
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File 
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", 
line 672, in __init__
     errread, errwrite)
   File 
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", 
line 1201, in _execute_child
     raise child_exception
OSError: [Errno 2] No such file or directory
 >>>

In fact, os.popen is deprecated in favour of subprocess.Popen().

HTH,

-- HansM




More information about the Python-list mailing list