问题描述
我正在Mac上使用IDLE,并且正在尝试制作一个小的程序,该程序从文件夹中打开一个随机文件(实际上是对更大项目的测试)。在该文件夹中,我有许多类型的文件,例如“ .blend”,“。m4a”,“。py”和“ .webloc”,但我希望将来还会更多。我希望我的代码可以使用各自的程序(Blender,QuickTime Player,IDLE,Chrome ...)随机打开一个,但是到目前为止,我还没有找到任何方法。可能吗?我最能做的就是从Windows计算机上打开Google Chrome。它在Mac上不起作用(可能是因为它是.app而不是.exe?),而且我只能打开程序,而不能打开文件。这是我用于此的代码:
import subprocess
subprocess.Popen(['C:\Program Files (x86)\Google\Chrome\Application\\chrome.exe','-new-tab'])
当我在Mac上输入密码(但Mac的文件路径正确)时:
import subprocess
subprocess.Popen(['/Applications/Google Chrome.app','-new-tab'])
它给了我这个错误(可能是因为文件路径写不正确?我右键单击Chrome文件并单击“复制为路径”复制了它):
>>>
=============== RESTART: /Users/jaimewalter/Desktop/Test/Test3.py ==============
Traceback (most recent call last):
File "/Users/jaimewalter/Desktop/Test/Test3.py",line 3,in <module>
subprocess.Popen(['/Applications/Google Chrome.app','-new-tab'])
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/subprocess.py",line 854,in __init__
self._execute_child(args,executable,preexec_fn,close_fds,File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/subprocess.py",line 1702,in _execute_child
raise child_exception_type(errno_num,err_msg,err_filename)
PermissionError: [Errno 13] Permission denied: '/Applications/Google Chrome.app'
>>>
这是我的随机文件选择器代码:
import random
files = ["Test1.blend","Test2.m4a","Test3.py","Test4.webloc"]
open_this = random.choice (files)
print(open_this)
if open_this == "Test1.blend":
print("Opening Test1.blend")
#now it should open Test1.blend on a new Blender window (/Users/jaimewalter/Desktop/Test/Test1.blend)
elif open_this == "Test2.m4a":
print("Opening Test2.m4a")
#now it should open Test2.m4a on a new QuickTime Player window (/Users/jaimewalter/Desktop/Test/Test2.m4a)
elif open_this == "Test3.py":
print("Opening Test3.py")
#now it should open Test3.py on a new IDLE window or preferably runs the code inside directly it if that's possible (/Users/jaimewalter/Desktop/Test/Test3.py)
elif open_this == "Test4.webloc":
print("Opening Test4.webloc")
#now it should open Test4.webloc on a new Chrome or Safari window (/Users/jaimewalter/Desktop/Test/Test4.webloc)
我应该使用什么来打开代码中的文件?预先感谢
解决方法
我已经解决了。我用过
import subprocess
subprocess.call(["open","Test1.blend"])
我认为使用Linux是xdg-open