os.system()函数



import os
# 打开记事本
os.system('notepad')

# 用记事本打开当前程序目录文件 config.json
os.system('notepad config.json')

# 直接打开当前程序目录文件 config.xlsx
os.system('config.xlsx')

#直接打开当前程序目录文件 Word文件
os.system('1.docx')

#打开/xxx目录下的xxx.txt
os.system('notepad /xxx/xxx.txt')

#打开当前目录下包含中文的文件
filepath='测试.xlsx'
os.system(filepath.decode('utf8').encode('GBK'))

# 打开绝对路径下的文件
path = os.path.dirname(os.getcwd())
name = test.log
os.system("notepad "+ path + "%s" %name)


ShellExecute函数



# 语法
ShellExecute(hwnd, op, file, args, dir, show)

    hwnd: 父窗口的句柄,如果没有父窗口,则为0

    op : 要运行的操作,为open,print或者为空

    file: 要运行的程序,或者打开的脚本

    args: 要向程序传递的参数,如果打开的是文件则为空

    dir : 程序初始化的目录

    show: 是否显示窗口


相当于在资源管理器中双击程序,系统会打开相应程序



import win32api

# 后台执行 (程序可加文件扩展名exe)
win32api.ShellExecute(0, 'open', 'notepad.exe', '', '', 0)

# 前台打开(扩展名exe可省略)
win32api.ShellExecute(0, 'open', 'notepad', '', '', 1)

# 打开当前目录文件
win32api.ShellExecute(0, 'open', 'notepad.exe', 'config.json', '', 1)

# 打开/xxx/xxx目录文件
win32api.ShellExecute(0, 'open', 'notepad', './xxx/xxx/123.txt', '', 1)

# 打开IE浏览器
win32api.ShellExecute(0, 'open', 'iexplore.exe', '', '', 1)

# 用IE浏览器打开百度网址
win32api.ShellExecute(0, 'open', 'iexplore', 'https://www.baidu.com/', '', 1)

#打开系统附件自带的画图
win32api.ShellExecute(0, 'open', 'mspaint.exe', '', '', 1)


ctypes调用kernel32.dll(动态链接库)中的函数



# Windows下调用user32.dll中的MessageBoxA函数
from ctypes import *
user32 = windll.LoadLibrary('user32.dll')
a = user32.MessageBoxA(0, str.encode('Hello Ctypes!'),str.encode('title'), 0)


利用python执行.bat文件

subprocess 模块​

首先推荐使用的是它的 run 方法,更高级的用法可以直接使用 Popen 接口



# D:\start.bat
start cmd



# 第一种方法
import subprocess

a=subprocess.getoutput('D:\start.bat')
print(a)



# 第二种方法
def cmds():
# cmd = 'cmd.exe d:/start.bat'
c = subprocess.Popen("cmd.exe /c" + "d:/start.bat", stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
curline = c.stdout.readline()
while (curline != b''):
print(curline)
curline = c.stdout.readline()
c.wait()
print(c.returncode)

if __name__ == '__main__':
cmds()