Add directory to sys.path based on variable

Tim Golden mail at timgolden.me.uk
Thu Jan 30 09:14:18 EST 2014


On 30/01/2014 14:03, loial wrote:
> Ok, that works fine with the apth hard coded, but I want to do something like the code below. i.e I am trying to dynamically add a path that is relative to the path of the current executing python script.
> 
> In this case the import fails.
> 
> import sys
> import os
> from os.path import *
> 
> scriptpath=os.path.dirname(sys.argv[0])
> otherscriptspath=printerpath.replace("scripts","otherscripts")
> sys.path.append(otherscriptspath)
> 
> from AuditUpdate import *

Well, adding a path to sys.path and then importing is generally
considered a safe bet. So it's more likely that somewhere inside your
path manipulation something's going wrong.

You've presumably not cut-and-pasted that code from the console (since
you've got an undefined "printerparth" on the 6th line). But why not
scatter some print()s and os.listdir()s around, eg:


import os, sys

print(sys.path)
print(sys.argv[0])

scriptpath=os.path.dirname(sys.argv[0])
print(scriptpath)

otherscriptpath = scriptpath.replace("xxx", "yyy")
print(otherscriptpath)
print(os.listdir(otherscriptpath))

... and so on. Somewhere in there, I imagine something won't be as you
expect. Feel free to come back here if you need more help.

TJG



More information about the Python-list mailing list