0

I found this tutorial in A Byte of Python, but do not understand it:

import os
import time

source = [r'C:\Users\Desktop\Stuff']

target_dir = 'C:\Users\Backup'

target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip'

zip_command = 'zip -qr "%s" %s' % (target, ' '.join(source))

if os.system(zip_command) == 0:
    print 'Successful backup to', target
else:
    print 'Backup failed!'

After checking help(os) I do not understand why os.system(zip_command) would ever be zero. .system() does not return a Boolean, does it?

thanks.

3 Answers 3

3

help(os.system) says:

system(...)
    system(command) -> exit_status

    Execute the command (a string) in a subshell.

So, it executes the command you pass as a parameter and returns the exit_status of that command.

When a program returns 0 as result, it means it was executed succesfully and if it returns anything else, it probably means there was an error somewhere.

So in this line:

if os.system(zip_command) == 0:

you are actually asking: if the command line was executed succesfully then ... else ...

Sign up to request clarification or add additional context in comments.

1 Comment

Also worth reading is the online Python docs which explains os.system in more detail.
0

On Windows, the return value is that returned by the system shell after running command, given by the Windows environment variable COMSPEC: on command.com systems (Windows 95, 98 and ME) this is always 0; on cmd.exe systems (Windows NT, 2000 and XP) this is the exit status of the command run; on systems using a non-native shell, consult your shell documentation. see this.

Comments

0

The os.system(command) runs a command in a subshell, and returns an int.

Taken from python docs:

"On Windows, the return value is that returned by the system shell after running command, given by the Windows environment variable COMSPEC: on command.com systems (Windows 95, 98 and ME) this is always 0; on cmd.exe systems (Windows NT, 2000 and XP) this is the exit status of the command run; on systems using a non-native shell, consult your shell documentation."

So it returns 0 if the command was successful, and something else if it wasn't.

Source: http://docs.python.org/library/os.html#os.system

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.