Skip to main content
 首页 » 编程设计

python之用完 cron.hourly 不会导入 Python 模块

2025年05月04日8me-sa

我有 foo 用完 cron.hourly。它已经 chmod +x'd,并且运行良好。我的问题是它无法将 Python 模块识别为可导入的。

我有 ~/Foo/src,其中包含我转换为可执行文件 (main) 的原始 Python 代码,以及我尝试导入的其他模块 (foobar)。我有一个 init.py 坐在那里,它是空的,应该可以导入任何一个模块。事实上,用

运行我的脚本
python src/main.py 

一切正常,我没有收到此错误。运行时

run-parts -v /etc/cron.hourly/main 

我得到如下错误:

ImportError: No module named foobar 
run-parts: /etc/cron.hourly//main exited with return code 1 

我导入 foobar 的方式是

os.chdir("/home/ubuntu/Foo/src/") 
import foobar 

同样,这在从 Python 运行时有效,但在运行我的可执行文件时无效。为什么会这样,我可以做些什么来避免这种情况?

请您参考如下方法:

import sys 
sys.path.append("/home/ubuntu/Foo/src") 
 
import foobar 

来自文档:

sys.path

A list of strings that specifies the search path for modules. Initialized from the environment variable PYTHONPATH, plus an installation-dependent default.

As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH.

A program is free to modify this list for its own purposes.