我写了一个 python 脚本,如果我正常运行它就可以工作(python path/to/file.py)。我需要它每隔几个小时自动运行一次。因此,我在 /Users/User/Library/LaunchAgents 中创建了一个 plist 文件,该文件触发了一个 .sh 文件,该文件最终触发了 python 脚本。
python 脚本无法在没有错误的情况下运行。我设法将问题缩小到模块“PyPDF2”和“reportlab”(如果我排除这些模块,脚本运行良好)。我收到的错误消息显示“没有名为 reportlab.pdfgen 的模块”和“没有名为 PyPDF2 的模块”。
代码的相关部分是:
.sh 脚本:
#!/bin/sh
python /Users/User/path/to/file.py
Python脚本:
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
import mechanize #pip install mechanize
import time
import os
from reportlab.pdfgen import canvas
from PyPDF2 import PdfFileWriter, PdfFileReader
同样,如果我自己运行脚本,它就可以工作。我的猜测是,launchctl 以 root 身份运行,而 root 不知何故无法找到/访问模块。我已经进行了广泛的搜索,但找不到任何东西。
我对此比较陌生,可能会遗漏一些明显的东西?
我在 Mac 上运行 2.7 版的 python 脚本。
这里似乎有什么问题?
感谢您的帮助
更新:如果我将 print(sys.path) 放入代码中并自己运行它以及使用触发器,我两次都会得到一长串路径。其中一些是相同的,但大多数是不同的。我也跑了
print(help("modules"))
print(help("modules reportlab"))
print(help("modules PyPDF2"))
我自己和使用触发器。虽然如果我自己运行模块会显示,但如果我使用触发器则不会。
print(reportlab.__file__)
print(PyPDF2.__file__)
给我“/usr/local/lib/python2.7/site-packages/reportlab/init .pyc ”和“/usr/local/lib/python2.7/site-packages/PyPDF2/init .pyc ”。我尝试运行 sys.path.append("/usr/local/lib/python2.7/site-packages/PyPDF2/ init .pyc") sys.path.append("/usr/local/lib/python2.7/ site-packages/reportlab/ init .pyc") 在我被触发时在脚本中,但它似乎没有帮助。