0
点赞
收藏
分享

微信扫一扫

根据绝对路径 python 后台打开程序

import subprocess

# 不适用于关闭程序/进程

# subprocess.run
# 等候运行结束
# returncode=0, stdout='', stderr=''

# 后台运行, 避免阻塞
# 避免shell注入gongji
# os.system 需要双引号(以避免空格), subprocess 不需要
# cmd直接输入路径 如果存在空格 需要双引号
# returncode: None
# 运行成功 <Popen: returncode: None args: '...> <_io.TextIOWrapper name=3 encoding='cp936'> <_io.TextIOWrapper name=4 encoding='cp936'>
def fun_open(command):
    try:
        result = subprocess.Popen(
            args=command,
            shell=False,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True)
        print(
            '运行成功' if (result.returncode==None) or (result.returncode==0) else '运行失败',
            str(result),
            result.stdout,
            result.stderr
        )
    except FileNotFoundError:
        print(command, "not correct")
        raise

fun_open(path)

举报

相关推荐

0 条评论