Four ways to run other programs in Python

Source: Internet
Author: User

Original address: http://blog.csdn.net/jerry_1126/article/details/46584179

In Python, it is easy to use the OS module to run other scripts or programs so that the functionality provided by other scripts or programs can be used directly in the script without having to write code that implements that functionality again. To better control the running process, you can use the functions in the Win32process module, and if you want to further control the process, you can call the functions in Kernel32.dll directly using the CType module.

" Way One " uses the Os.system () function to run other programs

The system () function in the OS module makes it easy to run other programs or scripts with the following pattern:

Os.system (command)

    • Command: To execute the commands, if you want to pass parameters to the script, you can use a space to split the program and multiple parameters.


Examples are as follows:

    1. >>> import OS
    2. >>> Os.system (' Notepad ') # Open Notepad program.
    3. 0
    4. >>> Os.system (' notepad 1.txt ') # Open 1.txt file, if not present, create.
    5. 0

" mode two " uses the ShellExecute function to run other programs
In addition to using the Os.system () function, you can use the ShellExecute () function in the Win32API module to run other programs in the following format:
ShellExecute (hwnd, OP, file, args, dir, show)

    • HWND: The handle of the parent window, or 0 if there is no parent window
    • OP: The operation to be run, either open,print or empty
    • File: The program to run, or the script that opens
    • Args: The parameter to pass to the program, or null if the file is open
    • Dir: Directory of program initialization
    • Show: Whether the window is displayed

Examples are as follows:

  1. >>> Import Win32API
  2. >>> Win32API. ShellExecute (0, ' open ', ' notepad.exe ', ', ', 0) # background execution /c2>
  3. >>> Win32API. ShellExecute (0, ' open ', ' notepad.exe ', ', ', 1) # The front desk opens the /c1>
  4. >>> Win32API. ShellExecute (0, ' open ', ' notepad.exe ', ' 1.txt ', ', 1) # Open File
  5. >>> Win32API. ShellExecute (0, ' open ', ' http://www.sohu.com ', ', ', 1) # Open Web page
  6. >>> Win32API. ShellExecute (0, ' open ', ' D:\\opera.mp3 ', ', ' , 1) # Play Video
  7. >>> Win32API. ShellExecute (0, ' open ', ' d:\\hello.py ', ', ' , 1) # Run the program /c1>

Using the ShellExecute function, it is equivalent to double-clicking the file icon in Explorer and the system will open the corresponding program to run.

Note:

Win32API install http://sourceforge.net/projects/pywin32/files/pywin32/because I am a 64 operating system, so download this: pywin32-216.win-amd64-py2.7



" Way three " run other programs using the ShellExecute function

To create a process:
To facilitate control of programs running through scripts, you can use the CreateProcess () function in the Win32process module to create

A process that runs the corresponding program. The format of the function is:

CreateProcess (AppName, CmdLine, Proattr, Threadattr, Inherithandle, Creationflags, Newenv, Currentdir, Attr)

    • AppName executable file name
    • CmdLine command-line arguments
    • Procattr Process Security Properties
    • Threadattr Thread Safety Properties
    • Inherithandle Inheritance Flag
    • Creationflags Creating a flag
    • Current directory of the Currentdir process
    • Attr Creating a program's properties


Examples are as follows:

    1. >>> win32process. CreateProcess ( ' C:\\windows\\notepad.exe ',   ",  none, none, 0, win32process. create_no_window,   
    2. none,  none, win32process. Startupinfo ())   
    3. (<pyhandle:892>,  <pyhandle:644>, 21592, 18780)  #  function returns the process handle, thread handle, process ID, and thread id  



End Process:

You can use win32process. TerminateProcess function to end a process that has already been created, the function is formatted as follows:

TerminateProcess (handle, ExitCode)

    • Handle the handle of the process to be manipulated
    • ExitCode Process Exit code

or use Win32event. WaitForSingleObject waits for the created thread to end, the function is formatted as follows:

WaitForSingleObject (handle, Milisecond)

    • Handle: Handle of the process to be manipulated
    • Milisecond: Wait time, if 1, then wait.


Examples are as follows:

  1. >>> Import win32process
  2. >>> handle = win32process. CreateProcess (' C:\\windows\\notepad.exe ', ', none, None, 0, win32process
  3. . Create_no_window, None, none, win32process. Startupinfo ()) # Open Notepad to get its handle
  4. >>> win32process. TerminateProcess (handle[0], 0) # Terminate process
  5. Or
  6. >>> Import win32event
  7. >>> handle = win32process. CreateProcess (' C:\\windows\\notepad.exe ', ', none, None, 0,
  8. Win32process. Create_no_window, None, none, win32process. Startupinfo ()) # Create process get handle
  9. >>> win32event. WaitForSingleObject (handle[0],-1) # Wait for the process to end
  10. 0                                                                          #  process end return value   

" mode four " uses cTYPES to invoke functions in Kernel32.dll
Using the cTYPES module allows Python to invoke functions located in the dynamic-link library.

The cTYPES module provides Python with the ability to invoke functions in a dynamic-link library. The cTYPES module makes it easy to invoke and pass parameters to a dynamic-link library written in C. The cTYPES module defines the basic data types in the C language, and can implement structs and unions in C. The cTYPES module can operate on a wide range of operating systems such as the Windows,linux,mac OS, which basically implements cross-platform.

Example:

Windows downgrades the MessageBoxA function in user32.dll.

    1. >>> from ctypes import *
    2. >>> User32 = Windll. LoadLibrary (' user32.dll ')
    3. >>> User32. MessageBoxA (0, Str.encode (' ctypes is so smart! '), Str.encode (' ctypes '), 0)
    4. 1


The basic types contained in the CType module are similar to the C language, and the following are the comparison of several basic data types:

---------------------------------------

ctypes data type           C data type
----------- ---------------------------- 
c_char                   &NBSP;CHAR
c_short               &NBS P   SHORT&NBSP;
c_int                   &NBSP ; INT
c_long                   &NBSP;LONG
c_float                   FLOAT
c_doule                   DOUBLE
span>

c_void_p void *

---------------------------------------

Four ways to run other programs in Python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.