sveti petar
sveti petar

Reputation: 3797

How do I install Python module given as .py file?

I do realize this is a noobish question, but I've been trying for an hour and I can't get it right.

So, I have a Python script which I'd like to modify a bit and play around with as a Python beginner. However, at the very beginning of the script, there's this:

from priodict import priority_dict

Now, I have a file named priodict.py that came with the script. But how do I make it available to the script so it can be included like that?

The Python manual has pages and pages on installing modules, but they all seem to refer to "packages" which are to be placed in certain directories etc. What do I do when I have just the .py file?

I know there is probably a banale one-sentence response to this, but I'm getting frustrated and I'm short on time so I decided to take the easy way out and ask Stack overflow about it.

It seems that, if I don't have the priodict.py file, I get this error:

Traceback (most recent call last):
  File "C:\Python27\scripts\dijksta.py", line 192, in <module>
    main()
  File "C:\Python27\scripts\dijksta.py", line 185, in main
    D, _ = dijkstra(G, 1, v)
  File "C:\Python27\scripts\dijksta.py", line 139, in dijkstra
    Q = priority_dict() # est.dist. of non-final vert.
NameError: global name 'priority_dict' is not defined

If I place the file in the same directory as my script, I get this error:

Traceback (most recent call last):
  File "C:\Python27\scripts\dijksta.py", line 2, in <module>
    from priodict import priority_dict
ImportError: cannot import name priority_dict

These are the files in question:

https://github.com/kqdtran/ADA1/tree/master/dijkstra

Upvotes: 4

Views: 1885

Answers (1)

Kelketek
Kelketek

Reputation: 2446

Place the file in the same directory, and that will get you started. Seems you've figured out that much. If all you have is a .py file, that's what you're usually expected to do.

If you're unable to import a name from a module, it usually means that name doesn't exist in that module. Try:

import priodict
print dir(priodict)

Is priority_dict listed? If not, is there a similarly named attribute that might be what you're looking for? It may just be that the instructions given you were misspelled, like the _ wasn't needed.

If it fails on the import line, it may be that there's an error in the module code itself that must be corrected first. you'll get an error telling you roughly where it is.

Upvotes: 3

Related Questions