using python subprocess.popen..can't prevent e

2020-07-21 00:32发布

问题:

I am a python newbie and need some help. I am writing a python script to call an application exe(say abc.exe). I am using subprocess.popen for this purpose. e.g. :

r_stdout = subprocess.Popen(CommandLine,
                                  stdout = subprocess.PIPE,
                                  stderr = subprocess.PIPE).communicate()[1]

the CommandLine here is : abc.exe -options "<optionstr>". abc.exe is a black box to me and it is producing an error prompt for some of the options I am passing. The error prompt is a standard windows' prompt saying abc.exe has stopped working, giving me 3 options to check online for solution, close program, debug program. Now my question is : Is there any way to avoid this command prompt ? i.e. is there a way for a python script to suppress this prompt ?

回答1:

This site seems to have the solution. Basically, it says to include this at the start of your script:

if sys.platform.startswith("win"):
    # Don't display the Windows GPF dialog if the invoked program dies.
    # See comp.os.ms-windows.programmer.win32
    #  How to suppress crash notification dialog?, Jan 14,2004 -
    #     Raymond Chen's response [1]

    import ctypes
    SEM_NOGPFAULTERRORBOX = 0x0002 # From MSDN
    ctypes.windll.kernel32.SetErrorMode(SEM_NOGPFAULTERRORBOX);
    CREATE_NO_WINDOW = 0x08000000    # From Windows API
    subprocess_flags = CREATE_NO_WINDOW
else:
    subprocess_flags = 0

After this, you'd execute your subprocess like this:

r_stdout = subprocess.Popen(CommandLine,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE,
                            creationflags=subprocess_flags).communicate()[1]

The MSDN site has a page which defines many types of creation flags. Hope this helps.