os.popen command working differently on Windows

MRAB python at mrabarnett.plus.com
Thu May 12 10:45:51 EDT 2011


On 12/05/2011 15:11, Ayaskanta Swain wrote:
> Hi All,
>
> 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. I am
> executing the ‘mv’ command on linux & the ‘move’ DOS command on windows
> machine from my python script. Everything works fine on linux & windows
> , but the script fails to detect a particular error situation on
> Windows, which is very important for my application.
>
> Normally the move operation fails if we try to move a directory to a
> location where the same directory already exists. That means overwriting
> of directories is not allowed by the OS for move operation.
>
> For example on Windows command prompt – *“move /Y C:\temp\my_dir
> C:\stage\profiles\”* will fail with *Access is Denied* message if
> C:\stage\profiles\ already contains my_dir inside it. It is an expected
> OS behavior. But the problem is that, this error message is not thrown
> if the command is executed from a python script.
>
> ---
>
> filemove.py script has the following code –
>
> …………………………………………..
>
> import os
>
> src = sys.argv[1]
> dst = sys.argv[2]
>
> # Using the DOS command 'move'. Adding quotes("") to avoid issues with spaces in the path.
>
> command = 'move' + ' ' + '/Y' + ' ' + '"' + src + '"' + ' ' + '"' + dst + '"'
>
> try:
>     os.popen(command)
> except IOError:
>     print 'fatal: failed to execute move command'
> except OSError, err:
>     print >> sys.stderr, "System Error while making a copy from " + src + " to " + dst
>
> ………………………………………………………………………………..
>
> The script executes without giving any error msg and returns 0 exit
> code, but in the back ground the directory is not moved to the
> destination. I am providing the source & destination values as command
> line arguments to the script.
>
> On Linux this type of use case gives me the OS error message “cannot
> overwrite directory” which makes it easy for me to catch the error
> message & return it the end user. But I wonder why is this not the case
> on Windows. Any help to solve this will be great.
>
os.popen(command) will just call the command. If the command fails, its
exit code will be non-zero, but that won't make Python raise an
exception.

os.popen(...) will return an object and you can get the exit code of
the command on closing it:

     p = os.popen(command)
     exit_code = p.close()

On my PC (Windows XP) I get None (not 0) if the command succeeded and 1
if it failed.



More information about the Python-list mailing list