Python Knowledge Base Update -- March 3rd, 2000
Nathan Wallace
nathan at synop.com
Fri Mar 3 23:29:38 EST 2000
Thanks to everyone who is contributing. Remember, every contribution
increases your chances of winning the Palm V. Any contribution, even
spelling fixes or rearranging entries helps improve the Knowledge Base:
http://python.faqts.com
Cheers,
Nathan
## Unanswered Questions ########################################
-------------------------------------------------------------
How do I upload a binary file using ftplib?
http://www.faqts.com/knowledge-base/view.phtml/aid/1457
-------------------------------------------------------------
Mike Hostetler
## New Entries #################################################
-------------------------------------------------------------
How can I use a line printer from Python on different systems?
Is there system independent access to a line printer from Python?
http://www.faqts.com/knowledge-base/view.phtml/aid/1504
-------------------------------------------------------------
Nathan Wallace
Randall Hopper
Well, when you say system-independent, that makes it more of a
challenge:
MSWin: Maybe MSWin provides an abstract API to print to a printer.
But what if there are multiple printers? MSWin progs usually have
a Printer Setup... so the user can set this, among other things
(page parms, orientation, etc.)
UNIX: Is this system using lp? Or lpr? Or ... Assuming we knew,
then the question is which printer (printer queue) does the user
want to use? We might assume the user has already set $PRINTER or
$LPDEST as a preference, but maybe that printer only groks
Postscript and we want to print plain text. Or vice versa.
DOS: How do you know which parallel port has a printer on it, if any?
Maybe none do? Maybe multiple? You could just exec PRINT and take
your chances, but... And you don't know what preamble control
strings might be required. For example, some printers are set to
expect UNIX EOL convention, and some aren't.
For now, it might be best to take your queues off cross-platform apps
like Netscape and let the user configure the command used to print. The
print-to-file option is nice too and useful on occasion.
-------------------------------------------------------------
How can I extract all the keys in a formatting string to a list?
http://www.faqts.com/knowledge-base/view.phtml/aid/1505
-------------------------------------------------------------
Nathan Wallace
Michael Ströder, Johannes Stezenbach
For example, go from:
'%(language)s has %(count)03d quote types.' % vars()
to get:
['language','count']
Try something like this:
------------
class GrabKeys:
def __init__(self):
self.keys = []
def __getitem__(self, name):
self.keys.append(name)
return 0 # 0 is apparently compatible with all % format
characters
gk = GrabKeys()
'%(language)s has %(count)03d quote types.' % gk
print gk.keys
------------
-------------------------------------------------------------
What files do I need on my web server to use Python for CGI?
http://www.faqts.com/knowledge-base/view.phtml/aid/1506
-------------------------------------------------------------
Nathan Wallace
Harry George, Kalle Svensson
Your cgi script is a normal python script -- which means it needs the
normal python infrastructure (e.g., the interpreter and the std
libraries). If your homepage is on an ISP which does not support
python, that could be trouble. You could ask the ISP to install
python, so you can use it.
You will at least need the main script file plus any modules it uses
that are not in the standard library. On some webhosts, you will also
have to rename the main script file with a .cgi extension. If the
script uses any data files, you will have to upload them too.
Also remember, if you usually do
#!/usr/bin/env python
You may have to do:
#!/usr/bin/python (or whatever the actual absolute path may be)
(It is probably a poor idea to try to pick just a few of the std
libraries to upload, since you need the interpreter anyway.)
-------------------------------------------------------------
Are there any bug tracking systems written in Python?
http://www.faqts.com/knowledge-base/view.phtml/aid/1508
-------------------------------------------------------------
Nathan Wallace
Alessandro Bottoni
There is a nice project-management, task-tracking (problem-tracking)
system based on ZOPE (and hence on Python) out there:
http://bits.netizen.com.au/Xen/
XEN seems to be a quite interesting tool, really...
I do hope they will get some sponsorship from software carpentry, CNRI
or GNU.
You might also like to check out:
http://software-carpentry.codesourcery.com/
-------------------------------------------------------------
How can I check that the Python version is recent enough to run my
program?
http://www.faqts.com/knowledge-base/view.phtml/aid/1509
-------------------------------------------------------------
Nathan Wallace
Fredrik Lundh, Oleg Broytmann
Note that [1, 5, 2] < [1, 6]. in other words, this will do what you
want:
import string, sys
version = string.split(string.split(sys.version)[0], ".")
if map(int, version) < [1, 5, 2]:
print "sorry"
I can be better to not check the version - this will bound poor user to
one version. Instead, check for the feature you need. You need a
library? Try to import it and fall back gracefully:
try:
import pagecast_lib
except ImportError:
print_error()
if not pagecast_lib.has_key("I_need_IT"):
print_another_error()
-------------------------------------------------------------
Can I use Python scripting inside a C app?
How can I use Python as an internal scripting language?
http://www.faqts.com/knowledge-base/view.phtml/aid/1512
-------------------------------------------------------------
Nathan Wallace
Jon K Hellan
Download the Python documentation at "http://www.python.org/doc/". You
want "Extending and Embedding" for overview, and "Python/C API" for
more detail. You can also check out the tutorial at
"http://starship.python.net/crew/arcege/extwriting/pyext.html".
There's also a chapter in Mark Lutz' "Programming Python" from
O'Reilly.
-------------------------------------------------------------
How do you redirect stdout to your own place, such as a Win32 anonymous
pipe, before you even call Py_Initialize?
http://www.faqts.com/knowledge-base/view.phtml/aid/1510
-------------------------------------------------------------
Nathan Wallace
Niels Diepeveen
Something like this will probably work:
int stdoutfds[2];
if (_pipe(stdoutfds, 512, _O_BINARY))
....
if (_dup2(stdoutfds[1], 1) /* Redirect stdout */
....
if (_dup2(stdoutfds[1], 2) /* Redirect stderr */
....
_close(stdoutfds[1]);
-------------------------------------------------------------
Is it possible to not have to explicitly do imports?
http://www.faqts.com/knowledge-base/view.phtml/aid/1514
-------------------------------------------------------------
Nathan Wallace
Paul Prescod
I would suggest instead that you add an object to the globals dictionary
in your site setup. It could be called "mods" (for brevity). You would
hook up "mods.__getattr__" so that you would say:
fl=mods.glob.glob('*')
You would use __import__ in mods.__getattr__
I thought about this once and it seemed pretty cool to me as a shortcut.
You could argue that we could dump the import statement...(but I
wouldn't)
Having an explicit object as the root for the dynamically generated
package tree would be more Pythonic than having every module magically
appear in your global package namespace.
Package support needs more thinking through...
-------------------------------------------------------------
How do I format my request to get an url/socket when there is a proxy in
themiddle?
http://www.faqts.com/knowledge-base/view.phtml/aid/1515
-------------------------------------------------------------
Nathan Wallace
David Fisher
urllib has proxy support built-in, but not documented.
>>> import urllib
>>> proxy = { 'http': r'http://192.168.1.1:3128'} #squid proxy on my
local network
>>> u = urllib.URLopener(proxies = proxy)
>>> f = u.open(r'http://www.python.org')
>>> print f.read()
<HTML>
<!-- THIS PAGE IS AUTOMATICALLY GENERATED. DO NOT EDIT. -->
<!-- Mon Feb 28 11:00:24 2000 -->
<!-- USING HT2HTML 1.1 -->
<!-- SEE http://www.python.org/~bwarsaw/software/pyware.html -->
<!-- User-specified headers:
Title: Python Language Website
etc, etc, etc
you can add other proxies for ftp, et al. , i haven't done it, but I'm
known for my blind faith
-------------------------------------------------------------
How can I run another application (non Python) from within a Python
script and
capture its output?
Does os.popen() work from pythonw?
http://www.faqts.com/knowledge-base/view.phtml/aid/1516
-------------------------------------------------------------
Nathan Wallace
Jesper Hertel, Niels Diepeveen
os.popen(command_line) returns a pipe from wich you can read the
standard output from the command given by command_line.
That is, for example,
a = os.popen("dir").read()
runs the command "dir" and puts the entire output from the command in
the variable a.
Another function os.popen2() also returns standard error output from the
command, but this does not work in Windows, unfortunately.
Be careful, os.popen only works in a console session, not from pythonw.
This is a problem in the C library.
## Edited Entries ##############################################
-------------------------------------------------------------
How can I read and interpret email attachments using Python?
http://www.faqts.com/knowledge-base/view.phtml/aid/1324
-------------------------------------------------------------
Sean Blakey, Shae Erisson, Nathan Wallace
Oleg Broytmann,http://starship.python.net/~arcege/modules/index.html
Goto
http://sun.med.ru/~phd/Software/Python/misc.html
and download
extract_mime.tgz
There you'll find an example and some docs. Just feed a MIME message
into the program...
Assuming you have a file pointer to the message, you can create a
mimetools.Message object to access a multipart mime message. Here is a
snippet of code:
def decode_item(item):
'''
Decode an indevidual mime item
item should be a mimetools.Message object.
'''
encoding = item.getencoding()
name = item.getparam('name')
print 'Decoding to', name
outfile = open(name, 'wb') # Write the decoded
# Attatchment to a file
mimetools.decode(item.fp, outfile, encoding)
def decode_multipart(datafile):
'''
Decode a multipart MIME message.
datafile is the filepointer to a MIME mesage.
'''
msg = mimetools.Message(datafile)
boundary = msg.getparam('boundary') # The boundry between
# Message parts
encoding = msg.getencoding()
if encoding != '7bit':
raise 'Unknown encoding!', encoding
if msg.gettype() != 'multipart/mixed':
raise 'Message is not multipart!' # This could probably be
# made more robust
mmsg = multifile.MultiFile(msg.fp) # Abstract the message as
# A multifile object
mmsg.push(boundary)
while 1:
mmsg.next()
if mmsg.last:
break
mime_item = mimetools.Message(mmsg)
decode_item(mime_item)
also check out http://starship.python.net/~arcege/modules/index.html
Mimecntl is a nice way to build and read MIME docs.
-------------------------------------------------------------
How can I trap a keyboard interrupt using Python?
http://www.faqts.com/knowledge-base/view.phtml/aid/1424
-------------------------------------------------------------
Nathan Wallace
Oleg Orlov
import sys
def Worker(argv):
while 1:
pass
try:
if __name__ =='__main__':
Worker(sys.argv)
except KeyboardInterrupt:
print "Saving state..."
-------------------------------------------------------------
What is the best and fastest way to scan a whole list of foldersto see
if something has been added or not?
http://www.faqts.com/knowledge-base/view.phtml/aid/1326
-------------------------------------------------------------
Nathan Wallace
Darrell
If your talking about NT then give this a try.
http://www.dorb.com/darrell/win32WorkSvr/makeThumbsDG.py
def main():
"""
Use events to avoid polling.
A sleep is used to give most files a chance to finish
being writen. Sort of a hack and might not be needed.
The notification event LAST_WRITE seems to trigger
at the start and end of writing. So a single file
will trigger this twice.
"""
hnd=win32file.FindFirstChangeNotification\
(os.path.abspath('.')+os.sep+'incoming'\
,0, winnt.FILE_NOTIFY_CHANGE_LAST_WRITE )
while 1:
int = win32event.WaitForSingleObject( hnd, -1)
# Try to give the file time to finish writing
time.sleep(2)
print 'run'
try:
passed, failed, skipped = makeThumbNails()
except:
if '-d' in sys.argv:
traceback.print_exc()
raise ThumbNailException
win32file.FindNextChangeNotification(hnd)
More information about the Python-list
mailing list