Python module can't be imported when triggered by launchctl script in macos

510 Views Asked by At

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

I try to use a plist script to launch my python program but in vain,in the program,i import a package tushare,but "ImportError: No module named tushare" returned in log file "stderr",this package can be successfully imported in python program written in anaconda.

Results:

Traceback (most recent call last):

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

ImportError: No module named tushare

Guess maybe it's due to "EnvironmentVariables" parameter missing in plist script,but i don't know how to amend the plist script to fix the problem.Every time,i do the following to execute the script.Syntax checked with the Plist script,it can be executed.

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

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

"launchctl start com.tushare.refreshall.plist"
1

There are 1 best solutions below

1
Piotr Mardziel On

The service you are starting with launchctl likely does not share the environment you are in when you login into the terminal including the anaconda configuration.

You can fix this by adjusting the plist's ProgramArguments key and run whatever you intent through bash first and include the conda activation before the intended program. Here is an example where the emacs daemon is run in a conda environment named py36:

  <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>

This assumes that you are username, with anaconda installed in /Users/username/anaconda3. Adjust as per your specifics including the conda environment name.