Mark Mark - 11 days ago 5
Python Question

ImportError in python

In clean.py I have:

import datetime
import os

from flask_script import Manager
from sqlalchemy_utils import dependent_objects

from components import db, app
from modules.general.models import File
from modules.workflow import Workflow

manager = Manager(usage='Cleanup manager')

@manager.command
def run(dryrun=False):

for abandoned_workflow in Workflow.query.filter(Workflow.current_endpoint == "upload.upload_init"):
if abandoned_workflow.started + datetime.timedelta(hours=12) < datetime.datetime.utcnow():
print("Removing abandoned workflow {0} in project {1}".format(
abandoned_workflow.id, abandoned_workflow.project.name
))

if not dryrun:
db.session.delete(abandoned_workflow)

db.session.commit()


for file in File.query.all():
dependencies_number = dependent_objects(file).count()

print("File {0} at {1} has {2} dependencies".format(file.name, file.path, dependencies_number))

if not dependencies_number:
file_delete(file, dryrun)

if not dryrun:
db.session.delete(file)

db.session.commit()

# List all files in FILE_STORAGE directory and delete ones tat don't have records in DB
all_files_hash = list(zip(*db.session.query(File.hash).all()))

for file in os.listdir(app.config['FILE_STORAGE']):
if file.endswith('.dat'):
continue

if file not in all_files_hash:
file_delete(os.path.join(app.config['FILE_STORAGE'], file), dryrun)enter code here


I need start def run()
in console I write:
python clean.py

And I have outputs :

`Traceback (most recent call last):
File "cleanup_command.py", line 7, in <module>
from components import db, app
ImportError: No module named 'components'


clean.py is located in- C:\App\model\clean.py

components.py is located in - C:\components.py

Workflow.py is located in - C:\modules\workflow\Workflow.py

Please, tell me what could be the problem?

Answer

The problem is that modules for import are searched in certain locations: https://docs.python.org/2/tutorial/modules.html#the-module-search-path.

In your case you can put all source directory paths in PYTHONPATH var like:

PYTHONPATH=... python clean.py

But I guess it would be better to relocate your code files (i.e. put all the libs in one location)