使用Python调用可执行文件.exe的方法详解

方式一: os.system(cmd_command)

os.system() 相当于打开了windows系统中的一个cmd窗口,cmd_command 相当于在命令行中输入的命令。 cmd_command 可以是一个单独的exe文件的路径,这时表示打开一个exe程序,比如下面例子,表示用python打开一个notepad++软件。

import os 

def cmd_run_exe(exe_path):
    """
    功能:打开一个exe程序
    参数: exe_path:exe程序的全局路径,
    注意:需要输入的是exe的全局路径,路径中不能有空格,也不能仅仅是exe软件名
    """
    os.system(exe_path) 

def cmd_kill_exe(exe_name):
    """
    功能:关闭一个已经打开的exe软件程序
    参数:
        exe_name:已经打开的exe程序的名称,是名称,不能是路径
    """
    os.system("taskkill /f /t /im {}".format(exe_name))
    print("killed process {}".format(exe_name))

if __name__ == "__main__":
    exe_path = "E:/software-setups/notepad++/notepad++.exe"
    
    # 打开nodepad++软件
    cmd_run_exe(exe_path)
    

cmd_command 也可以是一个命令行,示例如下:

        创建一个hello.py文件

## hello.py
print("hello world!")

        创建一个main.py文件

## main.py 
import os 

def run_cmd_command(cmd_command):
    os.system(cmd_command)

if __name__ == "__main__":
    python_exe_path = "python.exe"
    py_file_path = "hello.py"
    
    cmd_command = "{} {}".format(python_exe_pyth, py_file_path)
    run_cmd_command(cmd_command)

        运行上面的main.py脚本,就相当于在cmd的命令行中运行“python.exe hello.py”

方式二:subprocess 方法

subprocess存在的目的就是为了替代上面的os.system(),它集成了很多功能,用起来很方便。

import subprocess

def python_run_exeCommand(cmd_exe_command,waitTime=10000):
    """
    功能:打开一个exe软件,等待waitTime秒,关闭该程序。
    参数:
        cmd_exe_command: 待打开的exe软件路径及命令.
            可以是完整的命令字符串,也可以是字符串列表。
            路径中不能存在空格,最好不要有汉字。不能仅仅是软件名。
        waitTime: 最大等待时长,单位:秒。
            超过该时长后,关闭exe程序。
    """
    Popen_Obj = subprocess.Popen(cmd_exe_command)
    try:
        Popen_Obj.wait(timeout=waitTime)
    except Exception as e:
        print("===== process timeout {} =====".format(cmd_exe_command))
        Popen_Obj.kill()
        return None
    

if __name__ == "__main__":
    python_exe_path = "python.exe"
    py_file_path = "hello.py" ## 上一章中创建的hello.py文件。

    python_run_exeCommand([python_exe_path,py_file_path])

subprocess的一个典型应用是:可以向exe_command提供输入参数,也可以存储exe_command运行过程中产生的print()信息。

import subprocess

def python_run_exeCommand(cmd_exe_command,waitTime=10000):
    """
    功能:打开一个exe软件,等待waitTime秒,关闭该程序。
    参数:
        cmd_exe_command: 待打开的exe软件路径及命令.
            可以是完整的命令字符串,也可以是字符串列表。
            路径中不能存在空格,最好不要有汉字。不能仅仅是软件名。
        waitTime: 最大等待时长,单位:秒。
            超过该时长后,关闭exe程序。
    """
    Popen_Obj = subprocess.Popen(cmd_exe_command,stdout = subprocess.PIPE)

    # cmd_stdout = Popen_Obj.stdout.read() # 返回bytes格式,如 b"hello world."
    # cmd_stdout = Popen_Obj.stdout.read().decode("utf-8") ## 把返回的bytes格式转换为string格式
    cmd_stdout = Popen_Obj.stdout.readlines()# 返回bytes格式,如 b"hello world.",如果有多行,返回一个列表。
    # cmd_stdout = Popen_Obj.stdout.readline()# 返回bytes格式,如 b"hello world.",如果有多行,返回第一行。

    ## 打印subprocess返回的信息
    for output in cmd_stdout:
        print("subprocess-output:",output.decode("utf-8"))

    try:
        Popen_Obj.wait(timeout=waitTime)
    except Exception as e:
        print("===== process timeout {} =====".format(cmd_exe_command))
        Popen_Obj.kill()
        return None
    

if __name__ == "__main__":
    python_exe_path = "python.exe"
    py_file_path = "hello.py"

    python_run_exeCommand([python_exe_path,py_file_path])

备注:上面用到的是subprocess的高级用法Popen,一般来说使用subprocess的普通用法就够用了:subprocess.run([cmd_command_list])

import subprocess

python_exe_path = "python.exe"
py_file_path = "D:/6-Projects/python_run_exe/hello.py"
cmd_command = "{} {}".format(exe_path,py_path)

res = subprocess.run([python_exe_path,py_file_path],stdout=subprocess.PIPE)

stdout =  res.stdout.decode("utf-8")
out_list = stdout.split("\r\n")
print(out_list)

subprocess很强大,更多功能参考:

subprocess — Subprocess management — Python 3.11.5 documentation

【Python】python之subprocess模块详解_python_伐尘-华为云开发者联盟

6个例子快速学会python中subprocess库的使用_Light2077的博客-CSDN博客

python subprocess-更优雅的创建子进程 – 知乎

python中3种调用可执行文件.exe的方法_python 打开本地exe文件_Ethan的博客的博客-CSDN博客

物联沃分享整理
物联沃-IOTWORD物联网 » 使用Python调用可执行文件.exe的方法详解

发表评论