【问题标题】:Python module can't be imported when triggered by launchctl script in macosmacos中的launchctl脚本触发时无法导入Python模块
【发布时间】:2017-08-19 04:34:51
【问题描述】:

The python program(apple.py) which wanted to be triggered by launchctl script,written under python2.7 in anaconda

The launchctl plist script(com.tushare.refreshall.plist) which was used to trigger the python program

我尝试使用 plist 脚本来启动我的 python 程序但徒劳无功,在程序中,我导入了一个包 tushare,但是在日志文件“stderr”中返回了“ImportError: No module named tushare”,这个包可以成功导入用anaconda编写的python程序。

结果:

Traceback (most recent call last):

  File "/Users/jacksonshawn/PythonCodes/apple.py", line 8, in <module>
import tushare as ts

ImportError: No module named tushare

猜想可能是由于 plist 脚本中缺少“EnvironmentVariables”参数,但我不知道如何修改 plist 脚本来解决问题。每次,我都会执行以下操作来执行脚本。语法检查plist脚本,可以执行。

"launchctl unload -w com.tushare.refreshall.plist"

"launchctl load -w com.tushare.refreshall.plist"

"launchctl start com.tushare.refreshall.plist"

【问题讨论】:

  • 任何人都可以帮忙吗?真的很感激。这个模块tushare在anaconda中的python 2.7中运行良好,我只是不知道为什么它不能导入需要由launchctl脚本触发的程序中.也许我的 plist 脚本中缺少像“EnvironmentVariables”这样的参数。
  • 向您的代码添加一些调试以打印 sys.path 的值。确保您要导入的模块在 sys.path 上。
  • 尝试在python2上创建一个虚拟环境,做项目。并尝试在该环境中安装 tushare。

标签: python macos info.plist launchctl root.plist


【解决方案1】:

当您登录终端(包括 anaconda 配置)时,您使用 launchctl 启动的服务可能不会共享您所在的环境。

您可以通过调整 plist 的 ProgramArguments 键来解决此问题,并首先通过 bash 运行您想要的任何内容,并在预期程序之前包含 conda 激活。下面是一个 emacs 守护进程在名为 py36 的 conda 环境中运行的示例:

  <key>ProgramArguments</key>
  <array>
    <string>bash</string>
    <string>-c</string>
    <string>source /Users/username/anaconda3/etc/profile.d/conda.sh; conda activate py36; /usr/local/opt/emacs/bin/emacs --fg-daemon</string>
  </array>

这假设您是username,并在/Users/username/anaconda3 中安装了anaconda。根据您的具体情况进行调整,包括 conda 环境名称。

【讨论】:

  • 非常感谢,我会照你说的去做。
猜你喜欢
  • 1970-01-01
  • 2023-03-14
  • 1970-01-01
  • 2011-12-19
  • 1970-01-01
  • 2019-06-08
  • 1970-01-01
  • 2021-12-29
  • 2021-08-16
相关资源
最近更新 更多