【发布时间】:2020-08-20 08:51:19
【问题描述】:
我在 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)
我应该使用什么来打开代码中的文件?提前致谢
【问题讨论】:
标签: python-3.x subprocess filepath