I had a function all by itself in the file [filename].py, and the file was properly executable. This is how people advised me to call it externally:

import func
func.[filename]()

But I was getting errors all over the place. So I contacted Python help and they told me something different, which worked when I tested it.

Let's say the function inside [filename].py is called funcname. This is what I did:

>>> import [filename]
>>> [filename].[funcname]()
[function returned output successfully]

Now, I navigated to the directory in which [funcname].py was located, so there were no path issues. If not in that directory, I'd have to add it to the $PATH variable, although Linux people probably know of a better way to do it.

Recommended Answers

All 6 Replies

If not in that directory, you must add it to the $PYTHONPATH variable, not $PATH. ($PATH is for executable programs, not python modules). Another way is to put filename.py in your site-packages directory (or your per-user site-packages directory). The third way is to dynamically add the folder to sys.path at run time.

Do you happen to know what the command in bash 4.2.45(1) is for permanently altering the $PYTHONPATH variable? I imagine it's set, but I don't know the syntax.

I did check the paths and there is indeed a site-packages subdirectory where I could place my module script files, so that's an option.

In terms of the third option, what I've tried, and what appears to work, is this:

>>>import sys
>>>sys.path.append("[path]")

Which really ain't that much of a hassle, so, if all else fails, I can do that.

Thanks for your help. :)

In your ~/.bashrc , add the line

export PYTHONPATH="$PYTHONPATH:$HOME/foo/bar"

to add ~/foo/bar to the list of directories. You may also create a personal site-packages directory

~/.local/lib/python2.7/site-packages

(or python3.2, ...)

Hmm. I'm going to write personal library calls that chmod +x a fresh python script and copy it to the personal site-packages directory, unless that functionality is already in an existing python library.

You can use symbolic links instead of file copy. Don't duplicate code !

Symlinks are actually a pretty good idea. :) Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.