Viewed   5.8k times

My python somehow can't find any modules in the same directory. What am I doing wrong? (python2.7)

So I have one directory '2014_07_13_test', with two files in it:

  1. test.py
  2. hello.py

where hello.py:

# !/usr/local/bin/python
# -*- coding: utf-8 -*-

def hello1():
    print 'HelloWorld!'

and test.py:

# !/usr/local/bin/python
# -*- coding: utf-8 -*-

from hello import hello1

hello1()

Still python gives me

>>> Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 4, in <module>
ImportError: No module named hello

What's wrong?

 Answers

1

Your code is fine, I suspect your problem is how you are launching it.

You need to launch python from your '2014_07_13_test' directory.

Open up a command prompt and 'cd' into your '2014_07_13_test' directory.

For instance:

$ cd /path/to/2014_07_13_test
$ python test.py

If you cannot 'cd' into the directory like this you can add it to sys.path

In test.py:

import sys, os
sys.path.append('/path/to/2014_07_13_test')

Or set/edit the PYTHONPATH

And all should be well...

...well there is a slight mistake with your 'shebang' lines (the first line in both your files), there shouldn't be a space between the '#' and the '!'

There is a better shebang you should use.

Also you don't need the shebang line on every file... only the ones you intend to run from your shell as executable files.

Wednesday, October 26, 2022
 
vytis
 
3

A few ways.

The easy way:

Don't extend the module, extend the classes.

exttwitter.py

import twitter

class Api(twitter.Api):
    pass 
    # override/add any functions here.

Downside : Every class in twitter must be in exttwitter.py, even if it's just a stub (as above)

A harder (possibly un-pythonic) way:

Import * from python-twitter into a module that you then extend.

For instance :

basemodule.py

 class Ball():
    def __init__(self,a):
        self.a=a
    def __repr__(self):
        return "Ball(%s)" % self.a

def makeBall(a):
    return Ball(a)

def override():
    print "OVERRIDE ONE"

def dontoverride():
    print "THIS WILL BE PRESERVED"

extmodule.py

from basemodule import *
import basemodule

def makeBalls(a,b):
    foo = makeBall(a)
    bar = makeBall(b)
    print foo,bar

def override():
    print "OVERRIDE TWO"

def dontoverride():
    basemodule.dontoverride()
    print "THIS WAS PRESERVED"

runscript.py

import extmodule

#code is in extended module
print extmodule.makeBalls(1,2)
#returns Ball(1) Ball(2)

#code is in base module
print extmodule.makeBall(1)
#returns Ball(1)

#function from extended module overwrites base module
extmodule.override()
#returns OVERRIDE TWO

#function from extended module calls base module first
extmodule.dontoverride()
#returns THIS WILL BE PRESERVEDnTHIS WAS PRESERVED

I'm not sure if the double import in extmodule.py is pythonic - you could remove it, but then you don't handle the usecase of wanting to extend a function that was in the namespace of basemodule.

As far as extended classes, just create a new API(basemodule.API) class to extend the Twitter API module.

Friday, October 21, 2022
 
2

You need to add __init__.py in your core folder. You getting this error because python does not recognise your folder as python package

After that do

from .posts_run import get_all_posts
#    ^ here do relative import
# or
from core.posts_run import get_all_posts
# because your package named 'core' and importing looks in root folder
Friday, September 9, 2022
 
mzulch
 
2

In python modules are objects. In order to create a module object the code that it contains is executed and the bindings that are found are added to the object as attributes.

Specifying what you want to import doesn't change the fact that the whole module is executed and afterwards only that single binding is put in the scope by the import.

It's standard practice to put any code that you do not want to execute when importing after a guard:

if __name__ == '__main__':
    # your code here

__name__ is a special global that is __main__ only when executing the module. During an import it is set to the name of the module (and thus that code wont be executed).


To learn more about modules read the documentation. There is also a section that explains the above mentioned guard: Executing modules as scripts

Wednesday, October 5, 2022
 
mcb
 
mcb
2

It is not an answer to your question, but It might be helpful:

#!/usr/bin/env python
import Image

def makefilmstrip(images, mode='RGB', color='white'):
    """Return a combined (filmstripped, each on top of the other) image of the images.

    """
    width  = max(img.size[0] for img in images)
    height = sum(img.size[1] for img in images)

    image = Image.new(mode, (width, height), color) 

    left, upper = 0, 0
    for img in images:
        image.paste(img, (left, upper))
        upper += img.size[1]

    return image

if __name__=='__main__':
    # Here's how it could be used:
    from glob import glob
    from optparse import OptionParser

    # process command-line args
    parser = OptionParser()
    parser.add_option("-o", "--output", dest="file",
                      help="write combined image to OUTPUT")

    options, filepatterns = parser.parse_args()
    outfilename = options.file

    filenames = []
    for files in map(glob, filepatterns):
        if files:
            filenames += files

    # construct image
    images = map(Image.open, filenames)    
    img = makefilmstrip(images)
    img.save(outfilename) 

Example:

$ python filmstrip.py -o output.jpg *.jpg
Tuesday, September 6, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :