Permission Denied when using os.system on Mac

huangapple go评论134阅读模式
英文:

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 &quot;sh: {path} permission denied&quot;.


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&#39;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&#39;{tree_name}.pdf&#39;)
os.system(f&#39;open {shlex.quote(path)}&#39;)

I'm also using shlex.quote here to avoid shell injection vulnerabilities, and os.path.join() for proper cross-platform path handling.

huangapple
  • 本文由 发表于 2023年6月5日 21:36:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76406979.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定