How to import a function from another module...

marco.nawijn at colosso.nl marco.nawijn at colosso.nl
Tue Aug 4 17:04:40 CEST 2015


On Tuesday, August 4, 2015 at 3:11:41 PM UTC+2, Dwight GoldWinde wrote:
> Thank you, Steven.
> I am a newbie with Python? so I really want to learn how to do it the easy
> way.
> Yes, could you tell me how to put the py.file that contains the function
> in the Python search path???
> 
> 
> 
> BIG SMILE...
> 
> Always, Dwight
> 
> 
> www.3forliving.key.to (video playlist on YouTube)
> www.couragebooks.key.to (all my books on Amazon)
> 
> 
> 
> 
> 
> 
> 
> 
> On 8/4/15, 9:24 AM, "Steven D'Aprano" <st... at pearwood.info> wrote:
> 
> >On Tue, 4 Aug 2015 09:57 am, Dwight GoldWinde wrote:
> >
> >> I am trying to import a function defined in another module.
> >
> >You can't use spaces in the name of importable Python modules: change the
> >name from "Simulate typing.py" to "simulate_python.py". You can use spaces
> >in file names if they are only used as a runnable script and not imported.
> >
> >Then use this:
> >
> >from simulate_python import humprint
> >
> >There's no need to use importlib.
> >
> >You may need to arrange for the simulate_python file to be placed
> >somewhere
> >in the Python search path. Do you need help with that?
> >
> >What you are trying to do with importlib is fight the language. Your life
> >will be much simpler if you work within the parameters of how the language
> >is designed to work.
> >
> >
> >
> >-- 
> >Steven
> >
> >-- 
> >https://mail.python.org/mailman/listinfo/python-list
Hi Dwight,

There are at least two ways to manipulate your search path, one from
within Python, one by setting/updating an environmental variable
in your operating system.

1. Dynamically add a search path in Python
First note that if you want to know which parts are currently
in the Python search path you can do the following (note that >>>
means type it in the Python shell and I am using Python 2 syntax)

>>> import sys
>>> for path in sys.path:
...     print path

So, if you want to add a folder to your search path, in your
script add the following *before* you access attributes etc.
from the module your are trying to use:

sys.path.append("the_path_that_contains_the_py_file")
# Import stuff from the py file here

The downside of this approach is that you have to do this
in every script that accesses information from your ".py"
file. If you want to do this once and for all, use the
second method

2. Setting/updating the environment variable
You can use the environment variable PYTHONPATH to inform
Python on which search paths it should use (besides the
default ones). 



More information about the Python-list mailing list