英文:
Permission Denied when using os.system on Mac
问题
我正在尝试使用新生成的PDF打开PDF阅读器。在我的Windows桌面上,以下代码可以完美运行,但在我的Mac上却报错“sh: {path} permission denied”。
```python
path = os.getcwd() + "{}.pdf".format(tree_name)
os.system(path)
我尝试只使用PDF文件的名称,因为我希望程序在本地查找,但这也不起作用。我绝对需要它在我的Mac笔记本上运行,因为这段代码是为演示而编写的,所以任何帮助都会很感激。
<details>
<summary>英文:</summary>
I am trying to open a pdf reader with a newly generated pdf. On my Windows desktop it works perfectly with the following code, but not on my Mac where is raises "sh: {path} permission denied".
path = os.getcwd() + "{}.pdf".format(tree_name)
os.system(path)
I tried using just the name of the pdf file since I want the program to look locally anyways, but that doesn't work either. I need it to work on my Mac laptop absolutely because the code is a for a demo so any help is appreciated.
</details>
# 答案1
**得分**: 0
在macOS上使用`open`工具。 (Windows的等效命令是[`start`](https://ss64.com/nt/start.html))。
```python
import os
import shlex
path = os.path.join(os.getcwd(), f'{tree_name}.pdf')
os.system(f'open {shlex.quote(path)}')
我在这里还使用了shlex.quote
来避免Shell注入漏洞,并使用os.path.join()
来正确处理跨平台的路径。
英文:
Use the open
tool on macOS. (The Windows equivalent is start
.)
import os
import shlex
path = os.path.join(os.getcwd(), f'{tree_name}.pdf')
os.system(f'open {shlex.quote(path)}')
I'm also using shlex.quote
here to avoid shell injection vulnerabilities, and os.path.join()
for proper cross-platform path handling.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论