Question about imports and packages

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed May 25 04:27:14 EDT 2016


On Wednesday 25 May 2016 14:39, Ben Finney wrote:

> What the Python import system expects you to do is::
> 
> cd ../
> python3 -m fnord.foo

I don't think you even need to do the cd provided the fnord directory is inside 
a directory on the path. It only gets complicated if fnord cannot be found by 
the import system.


> To me, that makes Python at a severe handicap as a simple-to-use
> scripting language.

There's something to what you say, but I don't think it's quite that bad. To 
me, "simple to use" means a stand-alone, single file .py file that only imports 
modules in the standard library or site-packages (including the per-user 
directories). So long as your script is a single file, you can always run it 
the old fashioned way:

python /path/to/my/script.py

and it will Just Work.

It's only packages or collections of modules that get tricky, and for them, the 
supported One Obvious Way is to make sure that they are on the PYTHONPATH. To 
make that happen, you are absolutely spoiled for choice:

- if you have root access, you can put them in the global site-packages 
directory;

- otherwise, you can put them in your per-user site directory;

- or you can put them anywhere you like, and point a .pth file to them;

- or add the enclosing directory to your PYTHONPATH;

- or even have your script's main module modify sys.path.


I don't think this is that much different from the way other scripting 
languages handle it. E.g. bash. If I have a set of (say) shell scripts:

fnord/
+-- foo.sh
+-- bar.sh


where foo.sh runs bar.sh, but fnord is *not* on the PATH, the way you make it 
work is:

- have foo.sh temporarily modify the PATH;
- have foo.sh call bar.sh using an absolute pathname.

That second option isn't available to Python, but then, .pth files aren't 
available to the shell :-)


-- 
Steve




More information about the Python-list mailing list