路径中包含空格 需用双引号括起来
import os
# 需要双引号(以避免空格)
# 返回退出状态码 正确返回0 错误返回1
# 等候运行完成
# 如果程序本身已经在运行 则输出完成
path_5 = ...
os.system('"' + path_5 + '"')
不完整案例
import subprocess
# 不适用于关闭某程序/进程
# subprocess.run
# 等候运行结束
# returncode=0, stdout='', stderr=''
# 后台运行, 避免阻塞
# 避免shell注入gongji
# os.system 需要双引号(以避免空格), subprocess 不需要
# returncode: None
# 运行成功 <Popen: returncode: None args: '...> <_io.TextIOWrapper name=3 encoding='cp936'> <_io.TextIOWrapper name=4 encoding='cp936'>
def fun_Popen(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 '运行失败',
result,
result.stdout,
result.stderr
)
except FileNotFoundError:
print(command, "not correct")
raise
在Python中,你可以使用os
模块的system
函数来打开一个exe文件。以下是一个例子:
import os
# 替换为你的exe文件的完整路径
exe_path = "C:\\path\\to\\your\\file.exe"
# 使用os.system打开exe文件
os.system(exe_path)
请确保你的exe文件路径是正确的,并且使用双反斜杠(\\
)来避免转义字符的问题。如果你的exe文件在Python脚本的同一目录下,你可以直接使用exe文件的名字,而不需要完整路径。例如,如果你的exe文件名为example.exe
,你可以直接使用os.system("example.exe")
来打开它。
注意:os.system
函数会阻塞你的Python程序,直到打开的exe程序关闭。如果你想要在后台打开exe文件,你可以使用subprocess
模块的Popen
函数。以下是一个例子:
import subprocess
# 替换为你的exe文件的完整路径
exe_path = "C:\\path\\to\\your\\file.exe"
# 使用subprocess.Popen打开exe文件
subprocess.Popen(exe_path)
subprocess.Popen
函数会在后台打开exe文件,这样你的Python程序可以继续运行,而不需要等待exe程序关闭。同样,请确保你的exe文件路径是正确的。如果你的exe文件在Python脚本的同一目录下,你可以直接使用exe文件的名字,而不需要完整路径。例如,如果你的exe文件名为example.exe
,你可以直接使用subprocess.Popen("example.exe")
来打开它。