在Python中,能够方便地运用os模块来运转其他剧本或许顺序,如许就能够在剧本中直接运用其他剧本或顺序供应的功用,而没必要再次编写完成该功用的代码。为了更好地掌握运转的历程,能够运用win32process模块中的函数,假如想进一步掌握历程,则能够运用ctype模块,直接挪用kernel32.dll中的函数。下面引见4种体式格局:
1、os.system()函数
os模块中的system()函数能够方便地运转其他顺序或许剧本,形式以下:
os.system(command):command: 要实行的敕令,假如要向剧本通报参数,能够运用空格支解顺序及多个参数
实例:
#翻开记事本 os.system('notepad') #用记事本翻开aa.txt os.system('notepad aa.txt') #aa.txt文件必需在当前顺序目次 #直接翻开aa.txt os.system('aa.txt') #直接翻开Excel文件 os.system('aa.xlsx') #直接翻开Word文件 os.system('bb.docx') filepath='测试.xlsx' #翻开包括中文的文件 os.system(filepath.decode('utf8').encode('GBK'))
2、ShellExecute函数
运用win32api模块中的ShellExecute()函数来运转其他顺序,花样以下
ShellExecute(hwnd, op, file, args, dir, show)
hwnd:父窗口的句柄,假如没有父窗口,则为0
op: 要运转的操纵,为open,print或许为空
file: 要运转的顺序,或许翻开的剧本
args: 要向顺序通报的参数,假如翻开的是文件则为空
dir : 顺序初始化的目次
show: 是不是显现窗口
运用ShellExecute函数,就相当于在资源管理器中双击文件图标,体系会翻开响应顺序运转。
import win32api win32api.ShellExecute(0, 'open', 'notepad.exe', '', '', 0) # 背景实行 win32api.ShellExecute(0, 'open', 'notepad.exe', '', '', 1) # 前台翻开 win32api.ShellExecute(0, 'open', 'notepad.exe', 'wmi.txt', '', 1) # 翻开文件 win32api.ShellExecute(0, 'open', 'iexplore.exe', '', '', 1) # 翻开IE浏览器 win32api.ShellExecute(0, 'open', 'iexplore.exe', 'https://www.baidu.com/', '', 1) # 用IE浏览器翻开百度网址 win32api.ShellExecute(0, 'open', 'mspaint.exe', 'wxqr.png', '', 1) #用体系附件自带的绘图翻开图片wxqr.png
3、CreateProcess
建立历程:
为了便于掌握经由过程剧本运转的顺序,能够运用win32process模块中的CreateProcess()函数建立一个运转响应顺序的历程。其函数花样为: CreateProcess(appName, cmdLine, proAttr, threadAttr, InheritHandle, CreationFlags, newEnv, currentDir, Attr)
appName:可实行文件名
cmdLine:敕令行参数
procAttr:历程平安属性
threadAttr:线程平安属性
InheritHandle:继续标志
CreationFlags:建立标志
currentDir:历程的当前目次
Attr:建立顺序的属性
完毕历程:
能够运用win32process.TerminateProcess函数来完毕已建立的历程, 函数花样以下:
TerminateProcess(handle, exitCode)
handle:要操纵的历程句柄
exitCode:历程退出代码
或许运用win32event.WaitForSingleObject守候建立的线程完毕,函数花样以下:
WaitForSingleObject(handle, milisecond)
handle : 要操纵的历程句柄
milisecond: 守候的时候,假如为-1,则一向守候.
import win32process # 翻开记事本,取得其句柄 handle = win32process.CreateProcess(r'C:\Windows\notepad.exe', '', None, None, 0, win32process.CREATE_NO_WINDOW, None, None, win32process.STARTUPINFO()) time.sleep(4) # 停止历程 win32process.TerminateProcess(handle[0], 0) import win32event #守候历程完毕 print win32event.WaitForSingleObject(handle[0], -1)
4、运用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('user32.dll') a = user32.MessageBoxA(0, str.encode('Hello Ctypes!'), str.encode('Ctypes'), 0) print a
更多Python相干技术文章,请接见Python教程栏目举行进修!
以上就是python怎样挪用其他顺序的细致内容,更多请关注ki4网别的相干文章!