[FAQTS] Python Knowledge Base Update -- May 10th, 2000
Fiona Czuczman
fiona at sitegnome.com
Wed May 10 10:27:43 EDT 2000
Hi Guys,
I've started entering some of the questions, with answers, that make it
onto the newsgroup into http://python.faqts.com . I'm planning on doing
this on a daily basis.
However, I'm not an expert (novice is a more apt word) so if I've made
any blunders it would be great if someone would take the time to point
me in the right direction.
Thanks, Fiona Czuczman
## New Entries #################################################
-------------------------------------------------------------
When running sets of python scripts how can I cleanup all variables (globals) from the last one run?
http://www.faqts.com/knowledge-base/view.phtml/aid/2596
-------------------------------------------------------------
Fiona Czuczman
Moshe Zadka
Run them with "exec <script> in {}"
Then all the global variables will be in a nameless dictionary.
-------------------------------------------------------------
Is it possible to create constant integers, floats etc?
http://www.faqts.com/knowledge-base/view.phtml/aid/2605
-------------------------------------------------------------
Fiona Czuczman
David Goodger
Nope. Just variables. UPPERCASE is often used as a convention for
constant-equivalent variable names (meaning: "don't touch this!").
-------------------------------------------------------------
Does python have a sleep function? e.g. sleep(60) to wait 60 seconds?
http://www.faqts.com/knowledge-base/view.phtml/aid/2609
-------------------------------------------------------------
Nathan Wallace, Fiona Czuczman
Andreas Jung
Try the sleep function in the time module.
import time
time.sleep(60)
-------------------------------------------------------------
How do you interrupt a program running under PythonWin?
How can I stop or break out of my Windows Python program?
http://www.faqts.com/knowledge-base/view.phtml/aid/2608
-------------------------------------------------------------
Fiona Czuczman, Nathan Wallace
Mark Hammond
Right-click on the Pythonwin taskbar icon, and select "Break into
running code"
-------------------------------------------------------------
How can I use the smtplib module to send email from Python?
How can I send mail using the os module?
How can I send mail through python?
http://www.faqts.com/knowledge-base/view.phtml/aid/2607
-------------------------------------------------------------
Nathan Wallace, Fiona Czuczman
http://www.python.org/doc/FAQ.html#4.71,Justin Sheehy
On Unix, it's very simple, using sendmail. The location of the sendmail
program varies between systems; sometimes it is /usr/lib/sendmail,
sometime /usr/sbin/sendmail. The sendmail manual page will help you out.
Here's some sample code:
SENDMAIL = "/usr/sbin/sendmail" # sendmail location
import os
p = os.popen("%s -t" % SENDMAIL, "w")
p.write("To: cary at ratatosk.org\n")
p.write("Subject: test\n")
p.write("\n") # blank line separating headers from body
p.write("Some text\n")
p.write("some more text\n")
sts = p.close()
if sts != 0:
print "Sendmail exit status", sts
Check out the os module doc for more info:
http://www.python.org/doc/current/lib/module-os.html
On non-Unix systems (and on Unix systems too, of course!), you can use
SMTP to send mail to a nearby mail server. A library for SMTP
(smtplib.py) is included in Python 1.5.1; in 1.5.2 it will be documented
and extended. Here's a very simple interactive mail sender that uses it:
import sys, smtplib
fromaddr = raw_input("From: ")
toaddrs = string.splitfields(raw_input("To: "), ',')
print "Enter message, end with ^D:"
msg = ''
while 1:
line = sys.stdin.readline()
if not line:
break
msg = msg + line
# The actual mail send
server = smtplib.SMTP('localhost')
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
This method will work on any host that supports an SMTP listener;
otherwise, you will have to ask the user for a host.
http://www.python.org/doc/current/lib/module-smtplib.html
-------------------------------------------------------------
How can I call Python scripts from C/C++ program?
http://www.faqts.com/knowledge-base/view.phtml/aid/2633
-------------------------------------------------------------
Fiona Czuczman
Phil Austin
Here's a solution using CXX (http://CXX.sourceforge.net).
Note: put FibSeries into a file called myfun.py:
callable.cxx:
#include "Python.h"
#include "CXX_Objects.h"
#include <iostream>
using namespace Py;
using namespace std;
extern "C" void Py_Initialize();
extern "C" void Py_Finalize();
int
main(int argc, char* argv[])
{
Py_Initialize();
Module myfun("myfun");
Callable fib = myfun.getAttr("FibSeries");
Tuple argtuple(3);
argtuple[0]=Int(2);
argtuple[1]=Int(2);
argtuple[2]=Int(30);
Object output = fib.apply(argtuple);
cout << List(output) << endl;
Py_Finalize();
return 0;
}
Compiling and executing this gives:
<peacock ~> callable
2
4
6
10
16
26
[2, 4, 6, 10, 16, 26]
-------------------------------------------------------------
How can I get the week and dates in the following format "Week 19 (8.5. - 14.5.)"?
http://www.faqts.com/knowledge-base/view.phtml/aid/2636
-------------------------------------------------------------
Fiona Czuczman
Scott Kain
You could use the mxDateTime module
(http://starship.python.net/~lemburg/mxDateTime.html) and the calendar
module that comes with the Python distribution. Use xmDateTime for easy
date and time addition and pass the month and year values to the
calendar.monthcalendar() function that gives a matrix of weeks.
-------------------------------------------------------------
Is there some way to refer to the + and * operators as functions?
http://www.faqts.com/knowledge-base/view.phtml/aid/2637
-------------------------------------------------------------
Fiona Czuczman
Alex, Nathan Froyd
Yeah, use the operator module
>>> import operator
>>> operator.add (5, 2)
7
>>> operator.mul (5, 2)
10
>>>
example::
If I want to have the length of a
vector v writing
reduce(lambda x,y:x+y,map(lambda x:x*x,v))
is not really nice. Instead I can write
something like:
reduce(operator.add, map(operator.mul, v))
-------------------------------------------------------------
How do I find the byte length of a float, double or an int?
Are all standard python float, double, ints, etc of a fixed format?
http://www.faqts.com/knowledge-base/view.phtml/aid/2638
-------------------------------------------------------------
Fiona Czuczman
Tim Peters
You can't find the byte length short of reading the source code.
A Python float is a C double.
Python doesn't have a double type.
A Python int is a C long.
Every Python object also comes with some amount of object hair, like a
refcount and a pointer to its type object ... again, you have to read
the source to get the full story.
-------------------------------------------------------------
How can I create an object instance giving its classname at runtime?
http://www.faqts.com/knowledge-base/view.phtml/aid/2635
-------------------------------------------------------------
Fiona Czuczman, Nathan Wallace
Alex, Emile van Sebille, Manus Hand, Michal Wallace
This sort of thing works:
>>> class C: pass
...
>>> c = eval ('C') ()
>>> c
<__main__.C instance at 103e18>
>>>
-----OR TRY-----
You could also play with changing the instance's class or bases
attributes, e.g.:
>>> class T1:
def __repr__(self):
return "T1"
>>> class P1:
def __repr__(self):
return "P1"
>>> a = P1()
>>> a
P1
>>> a.__class__ = T1
>>> a
T1
--- or try things like:
>>> class T3:
def __str__(self):
return "T3"
>>> a.__class__.__bases__=(T3,)
>>> a
T1
>>> print a
T3
----OR TRY----
After dynamically realizing that "object" should be an instance of a
particular "className" found in a certain "moduleName":
code = __import__(moduleName)
object = code.__dict__[className](initParam1, initParam2, etc.)
----OR TRY----
>>> class C:
... pass
...
>>> def makeNew(className):
... return getitem(globals(),className)()
...
>>> makeNew('C')
<__main__.C instance at 80dac50>
-------------------------------------------------------------
Is there a recursive glob?
http://www.faqts.com/knowledge-base/view.phtml/aid/2682
-------------------------------------------------------------
Fiona Czuczman
Fredrik Lundh
No, but you can easily roll your own using os.path.walk
and the fnmatch module.
Or, you can use this iterator class, adapted from an example
in the eff-bot library guide (see below):
#
# adapted from os-path-walk-example-3.py
import os
import fnmatch
class GlobDirectoryWalker:
# a forward iterator that traverses a directory tree
def __init__(self, directory, pattern="*"):
self.stack = [directory]
self.pattern = pattern
self.files = []
self.index = 0
def __getitem__(self, index):
while 1:
try:
file = self.files[self.index]
self.index = self.index + 1
except IndexError:
# pop next directory from stack
self.directory = self.stack.pop()
self.files = os.listdir(self.directory)
self.index = 0
else:
# got a filename
fullname = os.path.join(self.directory, file)
if os.path.isdir(fullname) and not
os.path.islink(fullname):
self.stack.append(fullname)
if fnmatch.fnmatch(file, self.pattern):
return fullname
for file in GlobDirectoryWalker(".", "*.py"):
print file
</F>
<!-- (the eff-bot guide to) the standard python library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->
-------------------------------------------------------------
Is there a way for the script to get the path of the file it's in?
http://www.faqts.com/knowledge-base/view.phtml/aid/2683
-------------------------------------------------------------
Fiona Czuczman
William Park
What you want are
sys.argv[0]
os.environ['PWD']
-------------------------------------------------------------
Is there a way to do a large output of text using print?
http://www.faqts.com/knowledge-base/view.phtml/aid/2684
-------------------------------------------------------------
Fiona Czuczman
Fredrik Lundh
use triple-quoted strings:
print """
Content-type: text/html
<html>
<head>
<title>
.....
</html>
"""
-------------------------------------------------------------
Is there a way to load a module given a full filepath?
http://www.faqts.com/knowledge-base/view.phtml/aid/2685
-------------------------------------------------------------
Fiona Czuczman
Fredrik Lundh
Given something like:
driver = LoadModule("C:\\Stuff\\sample.py")
driver.someFunction()
ANSWER::
start here:
http://www.deja.com/=dnc/getdoc.xp?AN=621152936
and add something like:
def import_file(filename):
name = os.path.splitext(os.path.basename(filename))[0]
return do_import(name, filename)
driver = import_file("c:/Stuff/sample.py")
driver.someFunction()
hope this helps!
-------------------------------------------------------------
If an instance of an object passes a reference to one of its methods, how does python keep track of the instance?
http://www.faqts.com/knowledge-base/view.phtml/aid/2686
-------------------------------------------------------------
Fiona Czuczman
Quinn Dunkan, Stefan Franke
A method is a wrapper around a normal python function. It has the attrs
im_func, im_class, and im_self. im_func is a normal function object,
and im_class is the method's class. When you pull a method from an
instance: instance.method.im_self, the instance is magically stored in
im_self. If you look at the im_self of a class: Class.method.im_self,
it will be None (which is what makes an unbound method an unbound
method).
When you call a bound method wrapper, it calls its im_func with im_self
prepended to the argument list.
So that's where python is hiding 'self'. You can think of a method as a
little closure.
A "bound method" basically keeps a pair of references - to the method
and the instance:
>>> class C: pass
>>> class C:
... def a(): pass
>>> C.a
<unbound method C.a>
>>> C().a
<method C.a of C instance at 1a20e10>
More information about the Python-list
mailing list