简体   繁体   English

如何使用 sudo 运行 Python 脚本? (苹果电脑)

[英]How do I run a Python script with sudo? (MAC)

I want to test the keyboard.on_press_key() function, but OSX blocks it naturally.我想测试keyboard.on_press_key() function,但OSX自然会阻止它。 When I try to run it through the terminal using sudo python [pathtofile] I get an import error: "ImportError: No module named keyboard".当我尝试使用sudo python [pathtofile]通过终端运行它时,我收到一个导入错误:“ImportError: No module named keyboard”。 I tried installing the module using sudo ( sudo pip install keyboard ) but, even though it installs just fine, I still get the same error.我尝试使用 sudo 安装模块( sudo pip install keyboard )但是,即使它安装得很好,我仍然得到同样的错误。 What am I doing wrong?我究竟做错了什么?

That is a error in your script, you probably didnt import the keyboard module before you used.那是您的脚本中的错误,您可能在使用之前没有导入键盘模块。 Try adding this in the first lines of your python script:尝试在 python 脚本的第一行添加这个:

 import keyboard

Note that python on macOS refers to the system installation.注意macOS上的python是指系统安装。 You should not install packages via pip to the system installation of Python.您不应通过pip将软件包安装到 Python 的系统安装中。 I'd recommend you to install another Python interpreter eg via brew .我建议您安装另一个 Python 解释器,例如通过brew See www.brew.sh for more info.有关更多信息,请参见www.brew.sh。

Then, it is just a matter of installing Python via然后,只需通过安装 Python

$ brew install python3

After that, simply install your keyboard package again:之后,只需再次安装keyboard package:

$ pip3 install keyboard

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM