[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

Example 11-2 serves its purpose, but later in this book update project, I grew tired of
using Notepad to view text files from command lines run in arbitrary places and wrote
the script in Example 11-3 to launch PyEdit in a more general and automated fashion.
This script disables the DOS pop up, like Example 11-2, when clicked or run via a
desktop shortcut on Windows, but also takes care to configure the module search path
on machines where I haven’t used Control Panel to do so, and allows for other launch-
ing scenarios where the current working directory may not be the same as the script’s
directory.


Example 11-3. PP4E\Gui\TextEditor\pyedit.pyw


#!/usr/bin/python
"""
convenience script to launch pyedit from arbitrary places with the import path set
as required; sys.path for imports and open() must be relative to the known top-level
script's dir, not cwd -- cwd is script's dir if run by shortcut or icon click, but may
be anything if run from command-line typed into a shell console window: use argv path;
this is a .pyw to suppress console pop-up on Windows; add this script's dir to your
system PATH to run from command-lines; works on Unix too: / and \ handled portably;
"""


import sys, os
mydir = os.path.dirname(sys.argv[0]) # use my dir for open, path
sys.path.insert(1, os.sep.join([mydir] + ['..']*3)) # imports: PP4E root, 3 up
exec(open(os.path.join(mydir, 'textEditor.py')).read())


To run this from a command line in a console window, it simply has to be on your
system path—the action taken by the first line in the following could be performed just
once in Control Panel on Windows:


C:\...\PP4E\Internet\Web> set PATH=%PATH%;C:\...\PP4E\Gui\TextEditor
C:\...\PP4E\Internet\Web> pyedit.pyw test-cookies.py

This script works on Unix, too, and is unnecessary if you set your PYTHONPATH and
PATH system variables (you could then just run textEditor.py directly), but I don’t do
so on all the machines I use. For more fun, try registering this script to open “.txt” files
automatically on your computer when their icons are clicked or their names are typed
alone on a command line (if you can bear to part with Notepad, that is).


Main implementation file


And finally, the module in Example 11-4 is PyEdit’s implementation. This file may run
directly as a top-level script, or it can be imported from other applications. Its code is
organized by the GUI’s main menu options. The main classes used to start and embed
a PyEdit object appear at the end of this file. Study this listing while you experiment
with PyEdit, to learn about its features and techniques.


696 | Chapter 11: Complete GUI Programs

Free download pdf