hpw to convert a linux python script ?

Steve Holden steve at holdenweb.com
Thu Feb 12 15:22:28 EST 2009


John Machin wrote:
> On Feb 12, 7:48 am, Stef Mientki <stef.mien... at gmail.com> wrote:
>> Alec Schueler wrote:
>>> On Feb 11, 7:58 pm, Stef Mientki <stef.mien... at gmail.com> wrote:
>>>> As there are a whole lot of these lines, in a whole lot of files,
>>>> I wonder if there's a simple trick to point
>>>>   /usr/share/tinybldLin/
>>>> to my directory ?
>>>> thanks,
>>>> Stef
>>> Find and replace?
>> well I was thinking of a more elegant way,
>> so the scripts remains, or better become multi-platform.
> 
> Your current setup is not even single-platform portable ... consider
> the scenario where some Linux admin wants your gear to live in some
> directory other than /usr/share/tinybldLin/
> 
> The standard technique for ensuring that kind of portability involves:
> 1. Find the directory in which your script lives. Inspect sys.argv[0],
> use some os.path.some_functionality() to extract the directory, name
> it (say) home_base.
> 2. When you want to open a data file in the script's directory, do
> this:
>    the_path = os.path.join(home_base, 'stef1.dat')
>    f = open(the_path, .....)
> 
> NOTE: Use os.path.join() instead of some DIY technique; it knows
> better than you what the path separator is on the OS it's being run
> on. In fact, read the whole of the os.path manual carefully before you
> jump in to changing your code.
> 
> If you prefer to have the data files in (say) .../script_locn/data
> instead of .../script_locn, the adjustment should be obvious.
> 
> Unfortunately, you are still going to need use find and replace to fix
> your script. Code in haste, repent at leisure :-)
> 
Of course the real issue here is that the same hard-coded directory name
(or possibly multiple directory names all rooted in the same directory)
are scattered throughout the program. Your (the OP's) first task should
be to store that "root" directory in a variable and then use the
variable in place of all current uses of the root directory.

For example, I have a Django project that I like to run under both
Windows and Cygwin. So in my settings.py file I have:

# Django settings for PyTeach project.
import sys
if sys.platform == 'cygwin':
    fsroot = "/home/sholden"
elif sys.platform  == 'win32':
    fsroot = "C:/Users/sholden/Documents"
else:
    sys.exit("Only configured for Windows and Cygwin")

Than further down I have

# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = fsroot+'/Projects/PytDj/images/'

Note that most Windows APIs allow you to use the forward slash as a
delimiter. It's mostly the command line and Windows Explorer that are
snotty about insisting on the backslash.

regards
 Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC              http://www.holdenweb.com/




More information about the Python-list mailing list