简体   繁体   中英

Running out of cron.hourly won't import a Python module

I have foo running out of cron.hourly. It's been chmod +x'd, and it runs fine. My problem is it does not recognize Python modules as importable.

I have ~/Foo/src, and within that lies the original Python code that I turned into an executable (main), as well as the other module I'm trying to import (foobar). I have a init .py sitting there, empty, which should let either module be imported. In fact, running my script with

python src/main.py

Everything works just fine and I don't get this error. When running

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

I get an error as follows:

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

The way that I'm importing foobar is

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

Again, this works when running from Python, but not when running my executable. Why is this, and what can I change to avoid this?

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

import foobar

From the doc:

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 (eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM