【Python】調用外部程序 及執行.bat文件


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 模塊

  參考鏈接:https://www.cnblogs.com/-qing-/p/10934322.html

  首先推薦使用的是它的 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()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM