2

In "Learning python the hard way" the author states we can import a script without having to use python ex25.py. We can do import ex25 and the script will run.

When I do this, I get:

>>> import ex25
Traceback (most recent call last):
  File "<stdin>", line 1, in <modul
ImportError: No module named ex25

The author states it will look like this

Python 2.7.1 (r271:86832, Jun 16 2011, 16:59:05)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import ex25
>>> sentence = "All good things come to those who wait."
>>> words = ex25.break_words(sentence)
>>> words
['All', 'good', 'things', 'come', 'to', 'those', 'who', 'wait.']
>>> sorted_words = ex25.sort_words(words)
>>> sorted_words
['All', 'come', 'good', 'things', 'those', 'to', 'wait.', 'who']
>>> ex25.print_first_word(words)
All
>>> ex25.print_last_word(words)
wait.
>>> wrods
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'wrods' is not defined
>>> words
['good', 'things', 'come', 'to', 'those', 'who']
>>> ex25.print_first_word(sorted_words)
All
>>> ex25.print_last_word(sorted_words)
who
>>> sorted_words

It seems that Python is not able to find ex25. Perhaps I need to place it in the Python 27 directory? However, how then, do I keep a clean directory if I need to place all my .py files there?

When I don't get the first challenge (can't find file), I get:

>>> import ex25
>>> 

Seems like nothing is happening.

Nz1
  • 91
  • 1
  • 9
  • 4
    Is this book really the best to learn? <- No, it is pretty horrible. Consider "Dive Into Python" as your first book. /opinion – timgeb Feb 07 '16 at 12:45
  • @timgeb That's the book I went through, and I enjoyed it. Since then, all I have done is practice, and I have learned quite a lot. – zondo Feb 07 '16 at 12:48
  • 1
    Just my two cents - don't use that book :) https://redd.it/40s6dm – xrisk Feb 07 '16 at 12:50
  • @MartijnPieters: he was asking, in my opinion: http://stackoverflow.com/posts/35253628/revisions -- fell free to rollback if you disagree – Andrea Corbellini Feb 07 '16 at 12:53
  • In case, anyone is actually interested in those books, here are the links, [Dive Into Python](http://www.diveintopython.net/), [Python OOP](http://www.amazon.com/Python-3-Object-Oriented-Programming/dp/1849511268), and [Fluent Python](http://www.amazon.com/Fluent-Python-Luciano-Ramalho/dp/1491946008). – zondo Feb 07 '16 at 13:01
  • Where are all your files? And where is the ex25.py? – Oisin Feb 07 '16 at 13:23
  • Hi, I have put them in the python directory (same path as in ENV) – Nz1 Feb 07 '16 at 13:29

5 Answers5

3

In your System Config you will find a Variable call PythonPath (Default C:\Python27). When running the python command from the command line it will check in your current directory (Default C:\Users\[Your Name]) and the directory specified by the PythonPath. If you want to run your programm you need to either:

  1. Change to the Folder where your Programm is by using ie. cd Desktop
  2. Put in in your Python27 Folder

If you are using IDLE you dont need to use the console, you can just press F5 and the programm will run.

Oisin
  • 770
  • 8
  • 22
  • Or change your Pythonpath :) – xrisk Feb 07 '16 at 12:55
  • Okay, I am bit further. First I put an ex3.py file in the python 27 dir, I could then (import ex3) and the program would run. Then I made init.py (dir inside the dir, to see if I can keep my directories clean) and now I get the same weird thing happening as stated OOP (which is >>> import ex3 >>> (nothing here) – Nz1 Feb 07 '16 at 13:28
2

If you want to import a package in python (ex25 for example), you should structure your source code in a specific way like:

 .
 └── ex25               # <- package name = folder name
     ├── __init__.py    # <- can be empty
     └── lib.py         # <- contains your class or code

The if you want to import this package you do:

>> import ex25

If you want to import the specific class "DummyClass" in lib file you do:

>> from ex25.lib import DummyClass
>> class B(DummyClass):
     pass

and then continue with your code.

As for python learning books I would recommend that you pick whatever you find it easy to start with and continue to the end with it. A website or a book.

Hope this helps.

Edit: (after editing the question)

I have no idea about that book, but it looks like the books comes with some already written source code and packages to practice on. Try to get that source code and there you should find a folder with the name ``ex25'' .. probably.

Ammar
  • 1,305
  • 2
  • 11
  • 16
1

Also, current directory on Unix variants, or per shell session one liner:

export PYTHONPATH=$PYTHONPATH:/some/path

Or add that line to .bash_profile, .bashrc, .profile, or whichever is preferred, to have python check the folder each time a shell/terminal gets created.

Or for windows:

set PYTHONPATH=%PYTHONPATH%;C:\path\to\files

And set with autoexec.bat

Better yet, import programatically with:

sys.path.append

Also see:

Community
  • 1
  • 1
jmunsch
  • 22,771
  • 11
  • 93
  • 114
1

You can create packages in Python by putting an empty file entitled __init__.py in the directory containing other Python files. Once you do that, you can collectively or individually import that directory, or any python scripts in that directory, or any modules or functions in the python scripts in that directory. That is, as long as that directory is either located in your Python/lib, or in the directory where the Python script that is importing it, is saved.

The alternative to that would be to add the path where the your library is located to Python's search path. You can do so as follows:

from sys import path
path.append('The absolute path to your module/library')
Pouria
  • 1,081
  • 9
  • 24
  • Interesting enough, I tried this. First I put an ex3.py file in the python 27 dir, I could then (import ex3) and the program would run. Then I made __init__.py and now I get the same weird thing happening as stated OOP (which is >>> import ex3 >>> (nothing here) – Nz1 Feb 07 '16 at 13:26
  • I'm not sure if you've done this here only, or you've actually done it. It is not `init.py`, but `__init__.py`. The double-underscore (aka. dunderscore) is an element recognised by Python, and very extensively used. Don't put things in Python27 dir, it's not a good idea. If you want to do that, it must be done using a `setup.py` file created for this purpose. If you don't know how to create a `setup.py` file, I can write another answer explaining it in more details. But when you put things in Python27 directory, you (as correctly stated by yourself) risk disturbing the hierarchy. – Pouria Feb 07 '16 at 13:32
  • This all goes way over my head :) I didn't make .py in the python directory (not as a .py.. but as a directory to put .py's in there. That didn't do the trick. So perhaps .. Well, IDK. import just doesn't seem to work :) – Nz1 Feb 07 '16 at 13:35
  • 1
    Nah, don't worry. I'll put a thorough example here for all of these. – Pouria Feb 07 '16 at 13:39
1

Example of library creation and module implementation/import in Python.

Hierarchy

.
├── package_a
│   ├── __init__.py
│   ├── mod_a.py
│   └── mod_b.py
└── package_b
    ├── __init__.py
    ├── mod_a2.py
    └── mod_b2.py

Contents

Individual files contain:

File name package_a/__init__.py:

#!/usr/bin/env python3

File name package_a/mode_a.py:

#!/usr/bin/env python3

MOD_A_CONSTANT = 5

File name package_a/mod_b.py:

#!/usr/bin/env python3

from package_a.mod_a import MOD_A_CONSTANT


class MyModClass(object):
        class_prop = 'This is MOD_A_CONSTANT from mod_b class: {}'.format(MOD_A_CONSTANT)

        def __str__(self):
               return self.class_prop


if __name__ == '__main__':
        test = MyModClass()
        print(test)
        # Displays: This is MOD_A_CONSTANT from mod_b class: 5

File name package_b/__init__.py:

#!/usr/bin/env python3

File name package_b/mod_a.py:

#!/usr/bin/env python3

from package_a import mod_a, mod_b

def string_args():
        resp = (
                'mod_a.MOD_A_CONSTANT: {} | '
                'mod_b.MyModClass.class_prop: {}'.format(
                        mod_a.MOD_A_CONSTANT,
                        mod_b.MyModClass.class_prop
                )
        )

        return resp
        # Displays: mod_a.MOD_A_CONSTANT: 5 | mod_b.MyModClass.class_prop: This is MOD_A_CONSTANT from mod_b class: 5


if __name__ == '__main__':
        print(string_args())

File name package/mod_b2.py:

#!/usr/bin/env python3

from package_b.mod_a2 import string_args


class MyMod2Class(object):
        def __str__(self):
                return string_args()


if __name__ == '__main__':
        test = MyMod2Class()
        print(str(test).replace('|', '\n\n'))
        # Displays: 
        # mod_a.MOD_A_CONSTANT: 5 
        #
        # mod_b.MyModClass.class_prop This is MOD_A_CONSTANT from mod_b class: 5

This should tell you all you need to know about creating, importing, and implementing modules and libraries in Python.

Pouria
  • 1,081
  • 9
  • 24
  • Interesting. See OP what I had to do according to LPTHW. Every exercise you need to typ in code. But you have to figure out everything yourself why things happen or don't happen. I am not sure if I agree with that teaching method. – Nz1 Feb 07 '16 at 15:53
  • 1
    It is a debatable system, I agree. It is important for people to have an idea of what it is they're doing, or at least be told what it is that they're NOT supposed to be doing! Like copying thing directly into the Python's library! ;) – Pouria Feb 07 '16 at 16:26
  • Okay. Now I see a couple of things.There is a path for Python. However, I also see a PATH where JAVA is in the variable, and not Python. There is a Pythonpath. This path is in the System variable. Not in the User variable. When I EDIT path in User variable (where JAVA is) I can't seem to select the Python directory. – Nz1 Feb 07 '16 at 17:05
  • What I just don't get is.. Why can't I run anything from python and do I first need to go to CD [ directory where my .py files are ] – Nz1 Feb 07 '16 at 17:07
  • 1
    What do you mean you can't run anything from Python? Of course you can! You can run everything from Python, as long as that "thing", which I assume is a `.py` file, is either not modulated and therefore requires no input, or has a `if __name__ == '__main__': ... ` inside it that define how the "thing" should be run if it is called on it own. For the latter case, you can do this: `python -m name_of_the_thing.py` or import it to idle using `python -i name_of_the_thing.py` and then use the modules / functions inside it as you would do with typical python syntaxes. – Pouria Feb 07 '16 at 18:11
  • Okay, man, yesterday I let everything sink in and all of a sudden I realised something. You gonna laugh. I decided to type in the python shell import ex25 .. Then I decided to write the code down in the shell.. And it worked. So far, I have been writing code in Notepad++, saving it, opening it in the shell and thought thats the way how it should be run. Now I think notepad++ is more to safe your code? Anyway, I had no idea I could write IN the shell since LPTHW never really explained that cleary (to me). I feel like such a goofball. – Nz1 Feb 09 '16 at 07:37