我使用 os.system 正确吗?我的应用程序将不再打开
Am I using os.system correctly? My application won't open anymore
几天前,我的程序中有行 os.system(r"C:\Users\red\Desktop\Test UI")
。我测试了它,它运行良好,它打开了应用程序,就像我想要的那样。
现在,大约五天后我回来使用它,突然间它无法正常工作。我检查了进程,上面写着 'C:\Users\red\Desktop\Test' is not recognized as an internal or external command, operable program, or batch file.
我已经看过关于 os.system 的其他问题,例如 How do I execute a program from Python? os.system fails due to spaces in path,但我已经在使用原始字符串,就像建议的答案之一一样。我不明白它怎么一天能工作,第二天又不做任何改变就不能工作了。
实际上,您正在使用正确的命令执行文件,但是您要执行的文件不在该目录中。当文件不在目录路径中时出现错误'C:\users...' is not not recognized as an internal or external command, operable program, or batch file
。
不需要在文件名后面写.exe
,但是你必须写那个目录中存在的正确文件名。
在 Windows 上的路径出现一些问题后,我们最近将 os.system 替换为 subprocess.run。
对于此示例,您可以替换
os.system(r"C:\Users\red\Desktop\Test UI")
和
subprocess.run(r'"C:\Users\red\Desktop\Test UI"',shell=True)
对于 Windows 快捷方式,我必须在调用中添加 .lnk 扩展名:
subprocess.run(r'"C:\Users\red\Desktop\Test UI.lnk"',shell=True)
我明白了。出于某种原因,os.system 停止工作并且 subprocess.run 或 subprocess.call 不工作。我将我的命令改为使用 os.startfile,它开始正常工作。
这是最终结果:
os.startfile(r"C:\Users\red\Desktop\Test UI")
几天前,我的程序中有行 os.system(r"C:\Users\red\Desktop\Test UI")
。我测试了它,它运行良好,它打开了应用程序,就像我想要的那样。
现在,大约五天后我回来使用它,突然间它无法正常工作。我检查了进程,上面写着 'C:\Users\red\Desktop\Test' is not recognized as an internal or external command, operable program, or batch file.
我已经看过关于 os.system 的其他问题,例如 How do I execute a program from Python? os.system fails due to spaces in path,但我已经在使用原始字符串,就像建议的答案之一一样。我不明白它怎么一天能工作,第二天又不做任何改变就不能工作了。
实际上,您正在使用正确的命令执行文件,但是您要执行的文件不在该目录中。当文件不在目录路径中时出现错误'C:\users...' is not not recognized as an internal or external command, operable program, or batch file
。
不需要在文件名后面写.exe
,但是你必须写那个目录中存在的正确文件名。
在 Windows 上的路径出现一些问题后,我们最近将 os.system 替换为 subprocess.run。
对于此示例,您可以替换
os.system(r"C:\Users\red\Desktop\Test UI")
和
subprocess.run(r'"C:\Users\red\Desktop\Test UI"',shell=True)
对于 Windows 快捷方式,我必须在调用中添加 .lnk 扩展名:
subprocess.run(r'"C:\Users\red\Desktop\Test UI.lnk"',shell=True)
我明白了。出于某种原因,os.system 停止工作并且 subprocess.run 或 subprocess.call 不工作。我将我的命令改为使用 os.startfile,它开始正常工作。
这是最终结果:
os.startfile(r"C:\Users\red\Desktop\Test UI")