Example of how Python runs other programs

Source: Internet
Author: User
This article mainly describes the Python implementation of other programs run four ways, in conjunction with the instance form of Python to perform other program related modules and functions of the use of skills, the need for friends can refer to the following

The examples in this article describe four ways Python implements other programs. Share to everyone for your reference, as follows:

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:


>>> Import os>>> os.system (' Notepad ')    # Open Notepad program .0>>> os.system (' Notepad 1.txt ') # Open the 1.txt file and create it if it does not exist. 0

"Way Two" run other programs using the ShellExecute function

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:


>>> Import win32api>>> Win32API. ShellExecute (0, ' open ', ' notepad.exe ', ', ', ' 0 ')      # Background execution >>> Win32API. ShellExecute (0, ' open ', ' notepad.exe ', ', ', ' 1 ')      # Reception Open >>> Win32API. ShellExecute (0, ' open ', ' notepad.exe ', ' 1.txt ', ', 1)   # Open File >>> Win32API. ShellExecute (0, ' open ', ' http://www.sohu.com ', ', ', ' 1 ')  # open page >>> Win32API. ShellExecute (0, ' open ', ' D:\\opera.mp3 ', ', ', 1)     # Play Video >>> Win32API. ShellExecute (0, ' open ', ' d:\\hello.py ', ', ', 1)     # Run the program

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:


>>> win32process. CreateProcess (' C:\\windows\\notepad.exe ', ', none, none, 0, win32process. Create_no_window,none, None, win32process. Startupinfo ()) (<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:


>>> import win32process>>> handle = win32process. CreateProcess (' C:\\windows\\notepad.exe ', ', none, none, 0, win32process. Create_no_window, none, none, win32process. Startupinfo ())      # Open Notepad to get its handle >>> win32process. TerminateProcess (Handle[0], 0)            # Terminate process

Or


>>> import win32event>>> handle = win32process. CreateProcess (' C:\\windows\\notepad.exe ', ', none, none, 0,win32process. Create_no_window, none, none, win32process. Startupinfo ()) # Create process get handle >>> win32event. WaitForSingleObject (Handle[0],-1)           # Wait for process to end 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.


>>> from ctypes import *>>> user32 = Windll. LoadLibrary (' user32.dll ') >>> user32. MessageBoxA (0, Str.encode (' ctypes is so smart! '), Str.encode (' ctypes '), 0) 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 Char
C_short Short
C_int int
C_long Long
C_float float
C_doule Double
c_void_p void *
---------------------------------------

Related Article

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.