温馨提示×

如何在python中调用外部程序

养鱼的猫咪
568
2021-04-21 14:01:52
栏目: 编程语言

在python中调用外部程序的方法:1.使用os.system()函数调用;2.使用ShellExecute函数调用;3.使用ctypes模块调用;

如何在python中调用外部程序

具体方法如下:

1.使用os.system()函数调用

python中可以使用os.system()函数方便地运行其他程序或者脚本。

#打开记事本

os.system('notepad')

#用记事本打开aa.txt

os.system('notepad aa.txt')

#直接打开aa.txt

os.system('aa.txt')

#直接打开Excel文件

os.system('aa.xlsx')

#直接打开Word文件

os.system('bb.docx')

2.使用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浏览器

3.使用ctypes模块调用

python中可以使用ctypes模块来调用位于动态链接库的函数。

//调用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

0