allow scripts to use .pth files?

samwyse samwyse at gmail.com
Sun Jul 8 08:53:13 EDT 2007


On Jul 3, 9:35 am, Alan Isaac <ais... at american.edu> wrote:
> Suppose I have a directory `scripts`.
> I'd like the scripts to have access to a package
> that is not "installed", i.e., it is not on sys.path.
> On this list, various people have described a variety
> of tricks they use, but nobody has proposed a
> pretty way to allow this.
> I am therefore assuming there is not one. (?)
>
> How about allowing a `scripts.pth` file in such a `scripts`
> directory, to work like a path configuration file?
> (But to be used only when __name__=="__main__".)
> Drawbacks?
>
> Alan Isaac

before i can adequately shoot down your proposal, i need more
information.

first, how does the interpreter know to look in 'scripts' for your
'scripts.pyh' file and not in '.' or '~' or sys.argv[0] or someplace
else?  and you do know, don't you, that if you run 'scripts/
myscript.py' then 'scripts' is automagically prepended to the search
path for modules?

second, what's for format of this proposed file?  does it contain the
name of a single directory?  is it one directory name per line?  is it
intended to be os-specific or will the same file work on windows,
unix, vms and macos?

third, is there anything special about the name?  should i put a
myscripts.pyh file in the myscripts directory?  what if i have
multiple .pyh files?

if i may make some assumptions about the answers to the above, then
this incantation might do somewhat more than what you've asked for
(but what you actually want may be different):

if __name__ == '__main__':
    import sys
    from os.path import split, join, expanduser
    for d in '.', split(sys.argv[0])[0], expanduser('~'):
        scripts_pyh = join(d, 'scripts.pyh')
        try:
            for each_line in open(scripts_pyh).readlines():
                sys.path.append(each_line)
        except:
            pass


personally, though, i would be more likely to use this and skip all of
that 'scripts.pyh' nonsense:

if __name__ == '__main__':
    import sys, os.path
    for d in '.', os.path.expanduser('~'):
        if os.path.isdir(d): sys.path.append(d)




More information about the Python-list mailing list