伙计们。 我需要:
我试过代码 os.spawnv(os.P_NOWAITO, "C:\Program Files\Microsoft Office oot\Office16\EXCEL.EXE", ["File.xlsx", "File.xlsx"]), 但不好的是:
您可以使用 Python 中的
subprocess
模块实现您的要求。这是一个代码片段,可以满足您的需要:
import subprocess
import os
import sys
def launch_excel(file_path):
# Find the path to Excel.exe
excel_path = find_excel_path()
if not excel_path:
print("Excel not found.")
sys.exit(1)
# Launch Excel without waiting for it to complete
command = f'"{excel_path}" "{file_path}"'
if os.name == 'posix': # Unix-based systems
detached_process = os.setsid
else: # Windows
detached_process = None
subprocess.Popen(command, shell=True, preexec_fn=detached_process)
def find_excel_path():
for p in os.environ["PATH"].split(os.pathsep):
p = os.path.join(p, "EXCEL.EXE")
if os.path.exists(p) and os.path.isfile(p):
return p
return None
if __name__ == "__main__":
launch_excel("File.xlsx")
这个脚本将:
EXCEL.EXE
。您不需要指定两次.xlsx 文件名;你只需要将它传递给
launch_excel
函数一次。该脚本应该与不同的计算机兼容,因为它在系统路径中搜索 Excel。