簡體   English   中英

crontab Python 腳本中的“ImportError: No module named requests”

[英]“ImportError: No module named requests” in crontab Python script

我正在嘗試在 crontab 中設置 Python 腳本。 我有以下內容:

0-59 * * * * python ~/PycharmProjects/dailySearch.py trees >> ~/woah.log 2>&1

在我的日志文件中,我收到ImportError: No module named requests 我已經搜索了其他 SO 問題並嘗試了各種建議,但均未成功。

當我在 IDLE 中運行腳本時, sys.version將我的版本顯示為3.7.1 (default, Dec 14 2018, 13:28:58)

我安裝了兩個 Python 版本,雖然我正在運行 python3 (3.7.1),但我不確定我是否有請求,並且 pip 也安裝在它應該安裝的位置

python3 位於: /Users/jaai/anaconda3/bin/python3

pip3: /Users/jaai/anaconda3/bin/pip3

為了確認我正在使用 pip3 安裝請求,我使用以下命令運行sudo pip3 install requests

Requirement already satisfied: requests in /Users/jaai/anaconda3/lib/python3.7/site-packages (2.22.0)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /Users/jaai/anaconda3/lib/python3.7/site-packages (from requests) (1.24.1)
Requirement already satisfied: certifi>=2017.4.17 in /Users/jaai/anaconda3/lib/python3.7/site-packages (from requests) (2018.11.29)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /Users/jaai/anaconda3/lib/python3.7/site-packages (from requests) (3.0.4)
Requirement already satisfied: idna<2.9,>=2.5 in /Users/jaai/anaconda3/lib/python3.7/site-packages (from requests) (2.8)

任何幫助表示贊賞!

有幾件事可能是罪魁禍首,但為了確保您運行的解釋器與使用的 cron 相同,請確保包含 python3 的完整路徑,即

0-59 * * * * /Users/jaai/anaconda3/bin/python3/python ~/PycharmProjects/dailySearch.py trees >> ~/woah.log 2>&1

如果問題仍然存在,那么也許您應該考慮為 cron 設置 PYTHONPATH 環境變量,以便它與您的 shell 的設置相匹配。

我在 Ubuntu 18.04 上遇到了同樣的問題,並且在 crontab 中使用顯式路徑不起作用。 出於某種原因,cron 不起作用,而我帳戶中的 sudo 確實起作用。 我本以為它們會是一樣的,但很可惜,它們不是。 我得出的結論是這是一個環境變量問題。

對我來說,解決方法是讓 crontab 調用 shell 腳本,然后執行 python 腳本。 還必須設置HOMEPYTHONPATH環境變量:

crontab:

# Execute shell script and pipe stdout and stderr to a log file
# Which will enable you to see what's going on
* * * * * <your_path>/yourscript.sh  >> <your_path>yourscript_cron.log 2>&1

你的腳本.sh:

#!/bin/bash
echo yourscript.sh called: `date`
HOME=<your_home_dir>
PYTHONPATH=<path_to_dist_packages>
cd <path_to_your_python_script>
<python_executable> ./<your_python_script> 2>&1 1>/dev/null

有趣的是,這個 shell 包裝方法是我過去在 windows 上確定的計划任務的方式,因為它為您提供了最好的調試和靈活性。

希望這對其他人有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM