Home Backend Development Python Tutorial Detailed explanation of method examples of Python running other programs

Detailed explanation of method examples of Python running other programs

Aug 18, 2017 pm 01:32 PM
python method program

这篇文章主要介绍了Python实现运行其他程序的四种方式,结合实例形式分析了Python执行其他程序相关模块与函数使用技巧,需要的朋友可以参考下

本文实例讲述了Python实现运行其他程序的四种方式。分享给大家供大家参考,具体如下:

在Python中,可以方便地使用os模块来运行其他脚本或者程序,这样就可以在脚本中直接使用其他脚本或程序提供的功能,而不必再次编写实现该功能的代码。为了更好地控制运行的进程,可以使用win32process模块中的函数,如果想进一步控制进程,则可以使用ctype模块,直接调用kernel32.dll中的函数.

【方式一】使用os.system()函数运行其他程序

os模块中的system()函数可以方便地运行其他程序或者脚本,模式如下:


os.system(command)
Copy after login

command: 要执行的命令,如果要向脚本传递参数,可以使用空格分割程序及多个参数。

示例如下:


>>> import os
>>> os.system('notepad')    # 打开记事本程序.
0
>>> os.system('notepad 1.txt') # 打开1.txt文件,如果不存在,则创建.
0
Copy after login

【方式二】使用ShellExecute函数运行其他程序

除了使用os.system()函数外,还可以使用win32api模块中的ShellExecute()函数来运行其他程序,格式如下:


ShellExecute(hwnd, op, file, args, dir, show)
Copy after login

hwnd: 父窗口的句柄,如果没有父窗口,则为0
op : 要运行的操作,为open,print或者为空
file: 要运行的程序,或者打开的脚本
args: 要向程序传递的参数,如果打开的是文件则为空
dir : 程序初始化的目录
show: 是否显示窗口

示例如下:


>>> import win32api
>>> win32api.ShellExecute(0, 'open', 'notepad.exe', '', '', 0)      # 后台执行
>>> win32api.ShellExecute(0, 'open', 'notepad.exe', '', '', 1)      # 前台打开
>>> win32api.ShellExecute(0, 'open', 'notepad.exe', '1.txt', '', 1)   # 打开文件
>>> win32api.ShellExecute(0, 'open', 'http://www.sohu.com', '', '', 1)  # 打开网页
>>> win32api.ShellExecute(0, 'open', 'D:\\Opera.mp3', '', '', 1)     # 播放视频
>>> win32api.ShellExecute(0, 'open', 'D:\\hello.py', '', '', 1)     # 运行程序
Copy after login

使用ShellExecute函数,就相当于在资源管理器中双击文件图标,系统会打开相应程序运行。

NOTE:

win32api安装 http://sourceforge.net/projects/pywin32/files/pywin32/ 因我的是64的操作系统,所以下载了这个:pywin32-216.win-amd64-py2.7

【方式三】使用ShellExecute函数运行其他程序

创建进程:

为了便于控制通过脚本运行的程序,可以使用win32process模块中的CreateProcess()函数创建

一个运行相应程序的进程。其函数格式为:


CreateProcess(appName, cmdLine, proAttr, threadAttr, InheritHandle, CreationFlags, newEnv, currentDir, Attr)
Copy after login

appName 可执行文件名
cmdLine 命令行参数
procAttr 进程安全属性
threadAttr 线程安全属性
InheritHandle 继承标志
CreationFlags 创建标志
currentDir 进程的当前目录
Attr 创建程序的属性

示例如下:


>>> win32process.CreateProcess('C:\\Windows\\notepad.exe', '', None, None, 0, win32process.CREATE_NO_WINDOW,
None, None, win32process.STARTUPINFO())
(<PyHANDLE:892>, <PyHANDLE:644>, 21592, 18780) # 函数返回进程句柄、线程句柄、进程ID以及线程ID
Copy after login

结束进程:

可以使用win32process.TerminateProcess函数来结束已创建的进程, 函数格式如下:


TerminateProcess(handle, exitCode)
Copy after login

handle 要操作的进程句柄
exitCode 进程退出代码

或者使用win32event.WaitForSingleObject等待创建的线程结束,函数格式如下:


WaitForSingleObject(handle, milisecond)
Copy after login

handle : 要操作的进程句柄
milisecond: 等待的时间,如果为-1,则一直等待.

示例如下:


>>> import win32process
>>> handle = win32process.CreateProcess(&#39;C:\\Windows\\notepad.exe&#39;, &#39;&#39;, None, None, 0, win32process
.CREATE_NO_WINDOW, None, None, win32process.STARTUPINFO())      # 打开记事本,获得其句柄
>>> win32process.TerminateProcess(handle[0], 0)            # 终止进程
Copy after login

或者


>>> import win32event
>>> handle = win32process.CreateProcess(&#39;C:\\Windows\\notepad.exe&#39;, &#39;&#39;, None, None, 0,
win32process.CREATE_NO_WINDOW, None, None, win32process.STARTUPINFO()) # 创建进程获得句柄
>>> win32event.WaitForSingleObject(handle[0], -1)           # 等待进程结束
0                                   # 进程结束返回值
Copy after login

【方式四】使用ctypes调用kernel32.dll中的函数

使用ctypes模块可以让Python调用位于动态链接库的函数。

ctypes模块为Python提供了调用动态链接库中函数的功能。使用ctypes模块可以方便地调用由C语言编写的动态链接库,并向其传递参数。ctypes模块定义了C语言中的基本数据类型,并且可以实现C语言中的结构体和联合体。ctypes模块可以工作在Windows,Linux,Mac OS等多种操作系统,基本上实现了跨平台。

示例:

Windows下调用user32.dll中的MessageBoxA函数。


>>> from ctypes import *
>>> user32 = windll.LoadLibrary(&#39;user32.dll&#39;)
>>> user32.MessageBoxA(0, str.encode(&#39;Ctypes is so smart!&#39;), str.encode(&#39;Ctypes&#39;), 0)
1
Copy after login

ctype模块中含有的基本类型与C语言类似,下面是几个基本的数据类型的对照:

---------------------------------------------
Ctypes data type C data Type
---------------------------------------------
c_char     char
c_short short
c_int int
c_float long
c_doule double
c_void_p void *
---------------- --------------------------

The above is the detailed content of Detailed explanation of method examples of Python running other programs. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Do mysql need to pay Do mysql need to pay Apr 08, 2025 pm 05:36 PM

MySQL has a free community version and a paid enterprise version. The community version can be used and modified for free, but the support is limited and is suitable for applications with low stability requirements and strong technical capabilities. The Enterprise Edition provides comprehensive commercial support for applications that require a stable, reliable, high-performance database and willing to pay for support. Factors considered when choosing a version include application criticality, budgeting, and technical skills. There is no perfect option, only the most suitable option, and you need to choose carefully according to the specific situation.

HadiDB: A lightweight, horizontally scalable database in Python HadiDB: A lightweight, horizontally scalable database in Python Apr 08, 2025 pm 06:12 PM

HadiDB: A lightweight, high-level scalable Python database HadiDB (hadidb) is a lightweight database written in Python, with a high level of scalability. Install HadiDB using pip installation: pipinstallhadidb User Management Create user: createuser() method to create a new user. The authentication() method authenticates the user's identity. fromhadidb.operationimportuseruser_obj=user("admin","admin")user_obj.

Can mysql workbench connect to mariadb Can mysql workbench connect to mariadb Apr 08, 2025 pm 02:33 PM

MySQL Workbench can connect to MariaDB, provided that the configuration is correct. First select "MariaDB" as the connector type. In the connection configuration, set HOST, PORT, USER, PASSWORD, and DATABASE correctly. When testing the connection, check that the MariaDB service is started, whether the username and password are correct, whether the port number is correct, whether the firewall allows connections, and whether the database exists. In advanced usage, use connection pooling technology to optimize performance. Common errors include insufficient permissions, network connection problems, etc. When debugging errors, carefully analyze error information and use debugging tools. Optimizing network configuration can improve performance

Navicat's method to view MongoDB database password Navicat's method to view MongoDB database password Apr 08, 2025 pm 09:39 PM

It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

How to solve mysql cannot connect to local host How to solve mysql cannot connect to local host Apr 08, 2025 pm 02:24 PM

The MySQL connection may be due to the following reasons: MySQL service is not started, the firewall intercepts the connection, the port number is incorrect, the user name or password is incorrect, the listening address in my.cnf is improperly configured, etc. The troubleshooting steps include: 1. Check whether the MySQL service is running; 2. Adjust the firewall settings to allow MySQL to listen to port 3306; 3. Confirm that the port number is consistent with the actual port number; 4. Check whether the user name and password are correct; 5. Make sure the bind-address settings in my.cnf are correct.

Does mysql need the internet Does mysql need the internet Apr 08, 2025 pm 02:18 PM

MySQL can run without network connections for basic data storage and management. However, network connection is required for interaction with other systems, remote access, or using advanced features such as replication and clustering. Additionally, security measures (such as firewalls), performance optimization (choose the right network connection), and data backup are critical to connecting to the Internet.

How to optimize MySQL performance for high-load applications? How to optimize MySQL performance for high-load applications? Apr 08, 2025 pm 06:03 PM

MySQL database performance optimization guide In resource-intensive applications, MySQL database plays a crucial role and is responsible for managing massive transactions. However, as the scale of application expands, database performance bottlenecks often become a constraint. This article will explore a series of effective MySQL performance optimization strategies to ensure that your application remains efficient and responsive under high loads. We will combine actual cases to explain in-depth key technologies such as indexing, query optimization, database design and caching. 1. Database architecture design and optimized database architecture is the cornerstone of MySQL performance optimization. Here are some core principles: Selecting the right data type and selecting the smallest data type that meets the needs can not only save storage space, but also improve data processing speed.

How to use AWS Glue crawler with Amazon Athena How to use AWS Glue crawler with Amazon Athena Apr 09, 2025 pm 03:09 PM

As a data professional, you need to process large amounts of data from various sources. This can pose challenges to data management and analysis. Fortunately, two AWS services can help: AWS Glue and Amazon Athena.

See all articles