faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

6 of 8 people (75%) answered Yes
Recently 3 of 5 people (60%) answered Yes

Entry

Exit code of executed program (was: Newbie question...)

Jul 5th, 2000 10:00
Nathan Wallace, Hans Nowak, Snippet 148, Carey Evans


"""
Packages: operating_systems.windows
"""
"""
> Good question.  Yes, there is.  Do it just how you had it.  os.system
> returns with exit code of the command you exited, in both *nix and
> Windows - that's how the C system call works, and this is just a thin
> wrapper.
Not quite.  Unix returns what /bin/sh returned, which is usually what
the called program returned.  Windows 95 returns what COMMAND.COM
returned, which is *always* zero.
I've come up with the following code, which is more likely to do what
you want.  You have to run things like "DIR" as "COMMAND.COM /C DIR"
though.
"""
from win32process import CreateProcess, GetExitCodeProcess, STARTUPINFO,\
    CREATE_NEW_PROCESS_GROUP, NORMAL_PRIORITY_CLASS
from win32event import WaitForSingleObject, INFINITE
def system(cmd):
    pinfo = CreateProcess(
        None, cmd, None, None, 0, 0,
        None, None, STARTUPINFO())
    WaitForSingleObject(pinfo[0], INFINITE)
    return GetExitCodeProcess(pinfo[0])