This question already has answers here:
Python import modules from a higher level package
(2 answers)
Closed 7 years ago.
I've got a system built in Python in which I now want to run some functions periodically with a regular cron. So I made a file which starts off like this:
#!/usr/bin/env python
from app.models import User
When I import the file from the interactive Python command line I there are no problems:
>>> from app.crons import scrapeChannels
>>>
But when I run the file directly from the terminal I get the ImportError:
$ /home/kramer65/app/crons/scrapeChannels.py
Traceback (most recent call last):
File "/home/kramer65/app/crons/scrapeChannels.py", line 2, in <module>
from app.models import User
ImportError: No module named app.models
Now I assume this has something to do with the fact that app.models not in the sys.path is, but from this point I'm kinda lost. Am I right in my assumption? And how can I solve this issue?
All tips are welcome!
I think if you want to run the script from cron as well, the best would be to manually append the parent directory of app (which seems to be /home/kramer65/ to your sys.path , before the line from app.models import User .
Example -
import sys
sys.path.append('/home/kramer65/')
Add the directory containing the app package to your python path, using PYTHONPATH:
$ set PYTHONPATH=/home/kramer65
$ /home/kramer65/app/crons/scrapeChannels.py
Related
This question already has answers here:
Importing installed package from script with the same name raises "AttributeError: module has no attribute" or an ImportError or NameError
(2 answers)
Closed 8 days ago.
Using Flask (0.8) and Werkzeug (0.8.1) when attempting to run code with app.run(debug=True) I get the below described error. There are no errors when using app.run()
The error
Traceback (most recent call last):
File "code2.py", line 9, in <module>
app.run(debug=True)
File "/<snip>/env/lib/python2.7/site-packages/Flask-0.8-py2.7.egg/flask/app.py", line 703, in run
run_simple(host, port, self, **options)
File "/<snip>/env/lib/python2.7/site-packages/Werkzeug-0.8.1-py2.7.egg/werkzeug/serving.py", line 587, in run_simple
from werkzeug.debug import DebuggedApplication
File "/<snip>/env/lib/python2.7/site-packages/Werkzeug-0.8.1-py2.7.egg/werkzeug/debug/__init__.py", line 14, in <module>
from werkzeug.debug.tbtools import get_current_traceback, render_console_html
File "/<snip>/env/lib/python2.7/site-packages/Werkzeug-0.8.1-py2.7.egg/werkzeug/debug/tbtools.py", line 19, in <module>
from werkzeug.debug.console import Console
File "/<snip>/env/lib/python2.7/site-packages/Werkzeug-0.8.1-py2.7.egg/werkzeug/debug/console.py", line 144, in <module>
class _InteractiveConsole(code.InteractiveInterpreter):
AttributeError: 'module' object has no attribute 'InteractiveInterpreter'
The code (code.py)
from flask import Flask
app = Flask(__name__)
#app.route('/news/')
def news():
pass
if __name__ == '__main__':
app.run(debug=True)
Steps taken to recreate the error
$ cd <project directory>
$ . env/bin/activate # Activates virtuanlenv environment (see below for packages)
$ python code.py
Contents of my env/lib/python2.7/site-packages (versions of various library used) via virtualenv
Flask-0.8-py2.7.egg
Jinja2-2.6-py2.7.egg
pip-1.0.2-py2.7.egg
setuptools-0.6c11-py2.7.egg
Werkzeug-0.8.1-py2.7.egg
Things I have tried to solve this problem so far, that have not helped (unfortunately)
Extensive googling/SO searching
Heavy simplification of my code
Deleting created virtualenv and all libraries and reinstallation via easy_install
The strange thing here is that last night, this code worked fine. This morning, without changing anything (that I'm aware of) the code failed to properly run.
Thanks very much for your help!
The problem is that you have named your module code.py. code is a built in Python module that werkzeug uses.
To fix the problem, rename your code.py to something else, and make sure you delete the code.pyc file.
Solution to your problem is is your filename; don't name your python file name as code.py, main.py, Flask.py, os.py, system.py.
Instead, you can use code1.py or something.
I am working on some projects these days. I have created 3 executable python files in my project called,
crawler.py
process_data.py
process_csv.py
Then I have created run.py to execute the above three, one after one.
Problem -: when I tried to execute the process_csv.py file using run.py, it showed me
Traceback (most recent call last):
File "processors/process_csv.py", line 1, in <module>
import pandas as pd
ModuleNotFoundError: No module named 'pandas'
Interesting point -: But, if I tried to execute process_csv.py separately without using run.py, it was run without any pandas error.
process_csv.py
import pandas as pd
# my code
run.py
import subprocess
subprocess.run(['python', 'processors/process_data.py']) # this line is working fine
subprocess.run(['python ', 'processors/process_csv.py']) # error occur in this line
When I hardly navigate through Stackoverflow, I found a question that has some kind of relation to my question. I realized accepted answer of that question; can be applied to my question also. Then I have applied some changes to my script.
run.py
import subprocess
import sys
subprocess.run(['python', 'processors/process_data.py'])
subprocess.Popen([sys.executable, "processors/process_csv.py"]).communicate()
This solution 100% worked for my script.
Guys I'm new in Python and I'm trying to understand modules.I have a folder in desktop and there are 2 module in that folder. One of them is pr.py ,it's takes a array and displays it.And other one is fillArray.py.Now I want to add these 2 friend into interpreter but when I used in interpreter import pr.py or import fillArray it's giving to me this error
>>> import pr
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
import pr
ImportError: No module named pr
Then if I clicked f5(run) in pr.py module ,write again in interpreter import pr it works.That's ok.But trying to run fillArray.py module same steps, it's restart interpreter and it works butpr.py module is removing.How can I handle this?By the way this can be unnecessary but I'm using python2.7.
Edit:I wrote print.py sorry it should be pr.py
If you have both the modules in the same folder, you can use . which specifies current directory as follows:
from .pr import *
This statement will import all functions of print.py which is in the current directory
If you want specific things to be imported, just specify using their names
from .pr import myfunc1, myfunc2, myclass1, myclass2
If you wish to import the whole module, use:
from . import pr
Hope this helps :)
I have a package my_scripting_library I want to use anywhere on machine. It has an init.py:
from silo_functions import *
and looks like
my_scripting_library
-__init__.py
-silo_functions.py
-test_stuff.py
test_stuff.py looks like:
#!/usr/bin/env python
from silo_functions import *
lines = read_lines('filepath.py')
print lines
in bashrc:
export PYTHONPATH="${PYTHONPATH}:$LIBRARY"
where LIBRARY is a correct filepath to my_scripting_library
In [1]: import sys
In [2]: sys.path
Out[2]:
['',
'/usr/bin',
'/usr/lib/python2.7/site-packages/lxml-3.3.3-py2.7-linux-x86_64.egg',
'/home/cchilders/scripts/python/my_scripting_library',
...
'/home/cchilders/.ipython']
running test_stuff with from .silo_functions import * causes:
Traceback (most recent call last):
File "./test_stuff.py", line 3, in <module>
from .silo_functions import *
ValueError: Attempted relative import in non-package
running test_stuff with from my_scripting_library.silo_functions import * causes:
Traceback (most recent call last):
File "./test_stuff.py", line 3, in <module>
from my_scripting_library.silo_functions import *
ImportError: No module named my_scripting_library.silo_functions
but running test_stuff with from silo_functions import * works:
it prints the lines
Of course I can't use this package from other folders, which is the real issue- I don't want to be forced into throwing all scripts in this one place. This is causing huge problems as I am constantly reusing dozens of functions each script, and over 5 tutorials on making a folder a python package never have worked yet. Why is something on the python path with an init not a package? Thank you
May be it is because you've added '.../python/my_scripting_library' to your path. But there are no 'my_scripting_library.py' at this folder.
If you want to use 'my_scripting_library.silo_functions', try to add '/home/cchilders/scripts/python' (not '/home/cchilders/scripts/python/my_scripting_library') to path.
Because 'my_scripting_library' is module. Python will find this folder, find __init__.py in this folder and mark it as module.
I am trying to setup a simple celery project. As per the official documentation, the layout is as follow:
clemux#melody ~/dev/debian/debsources/debsources
% find new_updater -name "*.py"
new_updater/tasks.py
new_updater/updater.py
new_updater/__init__.py
new_updater/celery.py
In celery.py, I import celery.Celery this way:
from __future__ import absolute_import
from celery import Celery
In IPython, I can import new_updater.celery without problems:
In [2]: from debsources.new_updater import celery
In [3]: celery?
Type: module
String form: <module 'debsources.new_updater.celery' from '/home/clemux/dev/debian/debsources/debsources/new_updater/celery.pyc'>
However, when trying to run new_updater.updater, I run into the following error:
clemux#melody ~/dev/debian/debsources
% python debsources/new_updater/updater.py
Traceback (most recent call last):
File "debsources/new_updater/updater.py", line 6, in <module>
from debsources.new_updater.tasks import print_package
File "/home/clemux/dev/debian/debsources/debsources/new_updater/tasks.py", line 3, in <module>
from debsources.new_updater.celery import app
File "/home/clemux/dev/debian/debsources/debsources/new_updater/celery.py", line 3, in <module>
from celery import Celery
File "/home/clemux/dev/debian/debsources/debsources/new_updater/celery.py", line 3, in <module>
from celery import Celery
ImportError: cannot import name Celery
What could be going on here?
I know I could simply rename celery.py to, e.g. celery_config.py (this is the standard answer to this kind of question on SO), but I'd prefer actually fixing this and not stray away from celery's official documentation.
EDIT: I printed out sys.path in new_updater/updater.py, here's the result:
['/home/clemux/dev/debian/debsources/debsources/new_updater',
'/home/clemux/dev/debian/debsources',
'/home/clemux/.virtualenvs/debsources/lib/python2.7',
<snip>
Deleting sys.path[0] before the other import 'solves' the issue, but I don't understand why that is in the path. How I got that:
mkvirtualenv test
python setup.py develop at the root of my project
EDIT2: it's the same outside a virtualenv, with celery installed from debian, and my PYTHONPATH set this way:
export PYTHONPATH=/usr/lib/python2.7/dist-packages:~/dev/debian/debsources
About how that first line got into 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.
from docs
Anyway, you shouldn't name your files as libraries you use, even if off. docs do so. Will help avoid many possible errors.