I've written a class, with some methods. I then want to be able to
call
the class repeatedly, to create some objects. The number of objects,
and
some of their initialisation parameters need to be specified later
(i.e.
at run-time).
Not quite sure what you mean by the last bit but I'll come
Have you looked at the ConfigParser module that was mentioned earlier
today?
Your file fits its format exactly...
But regular expressions can be used, try the intro in my tutorial,
or the excellent HowTo on the Python web site...
Alan G.
- Original Message -
From: kumar s [EMAIL
I'm having trouble understanding the difference between eval and
exec.
eval evaluates an *expression* - that is something that returns a
value.
exec executes a piece of code, it need not return a value.
eval is slightly safer than exec (but not much).
Some examples:
print 'hello' # use
I am new to programming and so don't know anything much, yet.
I am having problem with implementing a simple RPN calculator
in python.
I'm not surprised. While an RPN vcalculator is one of the easier
calculators to build its not exactly trivial. It sounds like the
kind of thing an ambitious
It must be cummulative error over 10s of thousands of seconds.
Just so, and depends on howm many other processes are running,
how busy the CPU is etc.
bodge ( cron or at are better) but I suppose I could calculate
seconds
to 8:05 sleep(seconds*0.95), re calculate secs to 8:05
sleep(seconds)
Is there any function where I can specify to python
buit-in function to select specific line (such as
starting from segment: page 22 TO the next new line)
instead of the whole lines until EOF.
e.g.:
a = readlines (From , TO )
Not quite, but you can do:
readlines()[from:to]
With the
- MS allows Outlook to run scripts when mail is open, if
those scripts are harmful we have a virus!
That is (was, they've improved it a lot) the number one cause
of script kiddie virii. Simply viewing a mail message in the
preview pane was enough to trigger a script. They have
improved
CC'd back to tutor list.
- Original Message -
From: Vincent Nijs [EMAIL PROTECTED]
To: Alan Gauld [EMAIL PROTECTED]
Sent: Tuesday, December 07, 2004 10:56 PM
Subject: Re: [Tutor] Connecting to interactive program
Alan,
Sorry if I was unclear.
I would like to have python program
Traceback: usual bit about in module..
Line 39: seg=codeSt[element:endInd+len(endStr]
MemoryError
Hehe. Helpful, no?
Sometimes seeing the whole traceback gives clues as
to whats throwing the wobbly, without the full stack
its hard to tell.
However before worrying about that I'd add a
out = open('sa_int_2.txt','w')
for ele1 in range(len(spot_cor)):
x = spot_cor[ele1]
replace this with
for x in spot_cor:
for ele2 in range(len(spot_int)):
cols = split(spot_int[ele2],'\t')
and this with
for item in spot_int:
cols = split(item,'\t')
y = (cols[0]+'\t'+cols[1])
if x
When I run the script from my bash shell it creates the videodb
database file, but when I run it from the browser it doesn't
create no file whatsoever.
This is usually due to wrong file permissions.
The script runs under the web server and this usually
has restricted access for security
Here is my code:
spot_cor=[]
for m in cor:
... cols = split(cor,'\t')
You are splitting the list not the item
cols = split(m, '\t')
Better to use a meaningful name too:
for line in cor:
would probably have made the mistake more obvious.
However, when I tried that
Personally I am getting weary of a lot of requests that to me seem
to come
from a lack of understanding of Python..
To be fair that is what the tutor list is for - learning Python.
Would you be willing to take a good tutorial so you understand
basic Python concepts and apply them to your
Hey there. Does anyone know of a way to output PDFs with python? I
have some
data that I have processed from a series of textfiles that I would
like to
provide PDF format reports for..
I can't recall what its called but a couple of years ago I found a
module on the Parnassus site for
Are these numerical approximation methods pythonically possible?
Yes and that's how they are normally found - not necessarily with
Python,
but by applying computer simulations of the equations. Generally you
calculate values in ever decreasing increments until you get enough
accuracy. eg you
I know how to limit google search results to a single site, but is
it
possible to google just one section of a site?
Can't speak for Google but...
I'd like to be able to search just the 2.4 tutorial,
http://www.python.org/doc/2.4/tut/tut.html
Possible? And if so, how to?
Have you tried
def combination(items)
list = []
for i in range(0,len(items)):
for j in range(0,len(items)):
for i in items:
for j in items:
Is both shorter and faster - no len() function calls.
Or if you want to use indices:
size = len(items) # only calculate once, it won't
everything was global, how you guys handle a modern structured
language
Don't worry this is one of the hardest bad habits to break.
You are not alone. The easiest way is to just pass the data
from function to function in the function parameters. Its not
at all unusual for functions to have
I far prefer the Brian's version, because it lets me set a single
breakpoint while I'm debugging, and I can look at the return value
before returning it,
In most debiggers(including Pythons) you can still do that
with a boolean condition provided the condition does not
itself contain a
For what it's worth, it seems to me to be perfectly normal to have
classes that are only ever intended to have a single instance. For
example, you're never likely to need more than one HTML parser, and
yet htmllib.HTMLParser is a class...
That's true but the argument for a class in that case
I got some Tkinter related questions for a project that I'm making:
1. How to add an image to a button ?
I find the easiest way is to create an PhotoImage object attach
the graphic file(jpg,bmp,gif) to that and assign the PhotoImage
object to the Button.image property. You can animate the image
That is, filename globbing doesn't seem to work. Looks like I'll
have to
use map/filter to do this. Is there a better way?
It does if you use the glob module :-)
Python, with batteries included.
But sometimes finding the right battery can be challenging...
Alan G.
Thanks,
N
--
Nandan
def getjlistrenderer(opname):
def listrender():
# use opname, eg ops=getlist(opname)
# or set local fn variable
return renderer;
return listrender;
#?or f=listrender(); return f;
Is it really as simple as this?
Assuming your indentation is actually OK then yes, it is
as easy as that.
I'm looking for any good link or tutorial of flow charting
A good resource for all notations related to software design
is at smartdraw.com:
http://www.smartdraw.com/exp/tec/tutorials/software.htm
But flow charts are more generic so info about them can
be found here:
junk = []
for arg in sys.argv:
junk.append(arg)
junk = junk[1:]
Why not
for arg in sys.argv[1:]:
junk.append(arg)
Or even easier and faster:
junk = sys.argv[1:]
All I had time to look at, sorry.
Alan G.
___
Tutor maillist - [EMAIL
A little while ago, someone posted a message about an error and
something about modifying the windows registry key
HKEY_CURRENT_USER\Control
Panel\Desktop so that the value Wallpaper was changed periodically.
I wonder
if anyone could tell me how to do that? I tried something, and it
didn't
these mailing lists
work - someone posts a problem, everyone looks at it and
everyone should see the answer. That way *everyone*
improves their chances of not making the same mistake.
Alan G.
Jason Child wrote:
Alan Gauld wrote:
oops, I forgot to add the s = 1 and s=0 lines to the example
gets an OSError: [Errno 9] Bad File Descriptor
on os.read(tmp_fp,10)
I'm thinking that, if I don't keep a reference to the file object,
it gets automatically closed.
How pythonic.
Yes it is. After all that's how garbage collection works for
all objects in Python, when nothing is using
example. The only thing I'm not clear about is how 'trashcan' can be
a
local variable inside main() when it's required by both trash() and
can()
It's not local. It is a global variable. It is defined outside
of any of the functions.
The only thing that's missing is that this script can't
Marilyn,
I seemed to have missed the start of this one, but which debugger
are you trying to use? There is plain ole Python pdb, the IDLE
debugger and the Pythonwin debugger (and probably more!)
The pdb debugger is fashioned on the gdb debugger and works
very like that if you've ever sen it
I tried to do this:
import os
import cgitb; cgitb.enable()
print Content-type: text/html\n\n
print Hi there, ,os.system(echo %USERNAME%)
If you ignore the environment variable bit, does
it work with a hard coded name?
If so then try using the function os.getenv() to
fetch the variable,
print Hi there, ,os.environ[USERNAME]
Oops, sorry, I said os.getenv(), looks like
my C background showing through :-)
Alan g.
___
Tutor maillist - Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
file. This allows me to pass a single object that contains loads of
conf
data to the important init functions (which my, indeed, change the
data
depending on various factors). Now, memory wise this may not be the
best
thing to do.
As a matter of interest why do you think its a problem memory
I am trying to use a least squares method (the one written by Konrad
Hinsen),
but I do not want the method to be able to generate negative values.
Is there
a way to stop least squares programs from doing so?
def _leastSquare():
# do the thing that might generate negatives
def
root = Tk()
cv = Canvas(root, width=400, height=300, bg=blue)
cv.pack()
cv.create_rectangle(50,30,320,290,outline=yellow,fill=red,width=10
)
mainloop()
any way what i would like to do is create a programme that would run
my text
programme from this graphical box
You need to use a Text
I'm not sure what exa ctly you are trying to do here,
but I'll take a guess.
def addvirt(): pass
def remvirt(): pass
PROVISION_ACTIONS=[('addvirt','Add Virt'),('remvirt','Remove
Virt'),]
Not sure why you have the list of tuples of strings, but it
shouldn't be a problem.
formhandlers={}
#
Thanks alot Jeff. This worked for me:
formhandlers={}
for verb,verb_desc in PROVISION_ACTIONS:
try:
formhandlers[verb]=globals()[verb]
except KeyError:
pass
I'm slightly confused about why you need to do this?
You create a list of names (PROVISION_ACTIONS), then
you add the
I am trying to supply input to another program using
pipes. I can read from it just fine, but writing to
its stdin doesn't seem to be working.
I'm guessing here so take with a pinch of salt...
cmd = listen.py
#stdout, stdin
r, w = popen2(cmd)
w.write(Message sent)
I think you need a
def _leastSquare():
# do the thing that might generate negatives
def leastSquare():
firstTry = _leastSquare()
if firstTry 0:
return leastSquare() # try again
else:
return firstTry
Primitive but it works. If you want more a efficient/elegant
for x in ['string', 10, True, [1,2,3] ]:
... print '%s' %x
...
string
10
True
[1, 2, 3]
That's cool! I didn't know that. I guess I'm crazy... : )
(We already knew that here.)
The difference is in how the formatting details work.
For numbers the formatting digits
I have a list consisting of about 250 items, I need to know if a
particular item is in the list. I know this is better suited to a
dictionary but thats not the way it ended up ;-)
I could do a for loop to scan the list compare each one, but I
have a
suspission that there is a better way ?
Patric,
How do you go about setting up a new application?
Thats a great question, and I hope we get a few responses.
For example, suppose I need a script that will collect order
information
for a set of items ona page. Its output will go to a mail program
so the
artist can be notified.
I
It seems that to do a good job of dumping the data, I need to tell
it
what this class looks like.
Are there alternatives? Does the pickle format really not provide a
way to inspect the data without the class definitions?
I suspect that loading the file into a good text editror like vim
or
I'm already confused! Seriously, I never done oop before, so even
the
Python tutorial examples are extremely confusing to me atm.
Which tutor are you using? If its the standard Python tutor then its
not really for beginners to OOP, you might be better looking at some
of the more basic tutors
Sorry if I missed something obvious, but how do I execute a python
script file in the interpreter? I have Using the Python
Interpreter in
the Python tutorial but not much is said...
You can import a script at the prompt as you would under
Pythonwin.
Or you can run IDLE much as you did
This function removes HTML formatting codes from a text email
Using regex to remove HTML is usually the wrong approach unless
you can guarantee the format of the HTML in advance. The
HTMLparser is usually better and simpler. I think theres an example
in the module doc of converting HTML to
Finally, another serialization format that is eminently readable is
YAML (YAML Ain't Markup Language). Besides Python, it works for
Ruby et al., can be used as an alternative to xml, etc.
A new one on me but I'll take a klook, thanks for posting.
Alan G.
(Who hates XML almost as much as
I want to move all the 1's move to the right, 1 index at a time,
preserving any spacing.
So you want to insert a zero at the front and delete the first
zero from the back? That doesn't require iterating over all
the entries just enough to find the first zero...
[1,0,0,0,0,1,1,1,0,1,1,0,1,0]
I want to move all the 1's move to the right, 1 index at a time,
preserving any spacing.
So you want to insert a zero at the front and delete the first
zero from the back? That doesn't require iterating over all
the entries just enough to find the first zero...
Playing with this for a
Using regex to remove HTML is usually the wrong approach unless
Thanks. This is one of those projects I've had in mind for a long
time, decided it was a good way to learn some python.
It's a good way to write increasingly complex regex! Basically
because HTML is recursive in nature it
I'm _very_ used to using C style constants (preprocessor #define
directives) or C++ const keyword style, for a variety of reasons.
I've yet to see anything covering 'how to work around the lack of
constants in Python'...can anyone point me in the right direction
here?
Define Constants in
Pixels - just ones and zeroes? Pack them as integers and apply the
right shift operator:
i=1
But you have to remember to overflow right hand ones into
the next integer if there are more than 32 bits...
Although Python long integers migfht work, dunno what the
speed of shifting a long
I searched freshmeat.net but couldn't find anything interesting
I guess that depends a bit on what you find intersting!
But rather than frshmeat why not search source-forge?
There are far more projects on source forge than those
that get announced on freshmeat. And many are looking
or people
Compared to Java and C++, Python has very meager facilities
for controlling how code is used. There is no const, and only
the slightest nod to access control my
suggestion is, just relax and try the Python way!
I'll second that. I came to Python after years of C++
(and Pascal - even
def write_list(list_to_write, file_name):
Writes elements of a list, seperated by spaces, to a file
for each in list_to_write:
file_name.write(str(list_to_write[each]) + ' ')
This is the problem.(I think)
You are taking each element of the list then using
it(either 0 or
But now I have much weirder problem...
I got this error:
C:\maillist.py
File C:\maillist.py, line 84
^
SyntaxError: invalid syntax
And the weird thing is that the program has only 83 lines...
For some reason python
I have many python scripts in various directories of
varying depth under my home directory, and I need to
change one line in each of these files.
personally I'd use find and sed in Linux, right tool
for the job etc...
But if you really must wheel out a howitzer to shoot
a squirrel...
I
I'm trying to import classes and functions across
several directories.
Here's a simple example of my filesystem:
/Defs
base.py
/One
a.py
b.py
/Two
c.py
In a.py I have:
###
import b
###
This results in an error:
ImportError: No
Hello I can't seem to get the IDLE to start up in my windows XP by
clicking
...
Also I can't seem to get xp to recognize .py files belonging to
python.
This is all fixable but it suggests maybe other problems in the
installation. Personally I'd recommend reinstalling Python
and that should
Hi David,
Its probably the kind of thing you could put on the
Useless Python website. Useless is a collection of
not-too-serious software written in Python which,
despite the name, is actually quite useful for beginners
to download and look at and learn. They can try
improving it, or using the
I've been forcing myself to learn Java, and I was wondering if
anyone's used Jython.
To clarify - Jython generates Java bytecode?
I'm learning its vagaries as a way of testing objects
being written by my develoment teams in Java.
Personally, I should've learnt Java first (although my success
Actually, I have the Intel assembler manuals at home, haven't even
looked at 'em. If we're going for speed...
Actually modern C compilers usually mean that well written C
can outperform even assembler, to write good assembler is just
so hard that very few people can outsmart a good comiler...
...on Java ...
quite like, much superior to C++, although it does lack the elegance
of
Python and Ruby.
Superior is a relative term. Java has lots of huge restrictions
compared to C++ - the lack of operator overloading being maybe
the biggest, since it prevents true sub typing of builtins and
I just wanted to let everyone know a detail about Jython. It is
not
in
fact an interpreter written in Java it is a dynamic Python to
JavaByteCode compiler.
Its several things, it includes jythonc (note the last letter)
which is a JVM compiler. But jython is also a full implementation
of
Good point John,
As I pointed out in another thread its best to use the right
tool for the job and in this case that is [ng]awk...
Alan G.
(a HUGE Awk fan! :-)
- Original Message -
From: [EMAIL PROTECTED]
To: tutor@python.org
Sent: Tuesday, January 11, 2005 9:07 PM
Subject: Re: [Tutor]
3) For the same reason, it will save bandwidth. The XML data will
probably take less space than the fully-formatted stuff I'd have
to
spit out with regular HTML, and the XSL stylesheet can probably
be
cached by the user's browser.
This is a common misperception that should have been
I ask that because I'm writting a little program that will make
queries over a 1500 entries database, with very simple queries. I
need
an answer in 1 or 2 seconds. I'm using SQLite now, but i wanted
something that depends as little as possible of external
dependencies
(as a database).
1500
descript You are standing in front of a stump. A path leads north.
/descript
exits N /exits
Probably more like:
description name=primary
personyou/person
location
relationin front of/relation
objectstump/object
/location
situation
objectpath/object
I have not been able to find any recent XML/Python tutorial on the
web. Does the xml.dom library have a XPath and XQuery or any
SQL-like
support? I've understood that it's a pretty basic library...
I don't thoink there's XPath or XQuery in Python yet. There
is a thread on this on
My opinion is : this is a very dangerous and stupid thing to do
!!!
No its quite common. Its why C++ for example allows you to write
your own type convcersion functions! One area where I've used this
is to convert faults to orders in a service management application.
Its fairly common for a
print '\n','siday_q', key, '.wav'# event
i get:
siday_q 515 .wav
how can you eliminate the spaces to get:
siday_q515.wav
Use the os path facilities to join file names etc together,
its portable and safer(more reliable).
However to join strings without spaces I find it
Where did my 'ooo' go?
#! /usr/bin/env python
import os
fobj = open('/tmp/xxx','w')
fobj.write('ooo\n')
fobj.flush()
File objects use buffered IO and by changing from using file
objects to file descriptors half way through the buffer
could be in any state. You need to flush() to force
My list looks like this: List name = probe_pairs
Name=AFFX-BioB-5_at
Cell1=96 369 N control AFFX-BioB-5_at
Cell2=96 370 N control AFFX-BioB-5_at
Cell3=441 3 N control AFFX-BioB-5_at
Cell4=441 4 N control AFFX-BioB-5_at
...
My Script:
name1 = '[N][a][m][e][=]'
Why not just: 'Name=' - the
I have looked into many books including my favs(
Larning python and Alan Gaulds Learn to program using
Yes this is pushing regex a bit further than I show in my book.
What I want to extract:
I want to extract 164:623:
Which always comes after _at: and ends with ;
You should be able to use
I'm not yet used to search in the cookbook... and I though such
basic widget would have been implemented directly in Tk or Tix...
A bit of historic perspective. John Ousterhout invented TCl/Tk
to provide a control language for his electrical engineering
projects. Thus its focus is on GUIs to
class _macroString(object):
def __init__(self,s):
self.macro=s
self.list=self.macro.split(\n)
for n,v in enumerate(self.list):
self.list[n]=v+'\n'
def readline(self,n=[-1]):
n[0]+=1
return self.list[n[0]]
Why not just create a
for n,v in enumerate(self.list):
self.list[n]=v+'\n'
Is this for loop a safe technique, where the list you're enumerating
over
in the for statement is the same as the one being updated in the
loop
body? I always avoid things like that.
Its not changing the list, its
I'm am bored and people are not asking enough questions/answering
them to
keep my mind busy. Is there any other mailing list that I can
subscribe to
like this one that lets anyone ask and answer questions?
I assume you'vve checked the Python newsgroup?
It should be busy enough for anyone! Of
I'm trying to use Python to start the dos-box (cmd.exe) and be
able to
call commands on it and receive output from it.
The Command window is just a terminal, there is no output to
be had other than an exit code when it closes.
However, none of the documentation for popen and
spawn cover this
Well, ultimately, what I want to be able to do is open Audacity
(http://audacity.sourceforge.net/) at a predetermined time and have
it
begin recording wave mix out (the default i have it set to anyway),
and
then have it stop again when i send it a command.
This will be much easier from python
It this correct? Python lists are not linked-lists (as in Scheme,
for
example). They are more like arrays (or vectors in C++/Java) with a
little more sofistication built into them to allow, for example, to
amortize over time a sequence of append operations. But in a
nutshell,
len is actually
GR len is actually a field in the underlying C object so len() is a
GR constant (O(1)) and as-fast-as-it-can-be operation.
TP ...n integers), but (ignoring the range() complication) there's no
TP difference in O() behavior between the two.
OK, The timbot's word is good enough for me, I won't
Hoo boy . . . Looking at the 'help' of the win32api has left this
newbie
hopelessly confused . . . Anyone who knows of a good Win32 tutorial,
please let me know!
Frankly, anyone doing anything serious on Win32 in Python should
buy Mark Hammond's book. It covers most things to do with Windows
import os
os.system('c:\\abaqus\\5.8-14\\abaqus.exe post')
, where post was a command, *not* a file. Now, I tried something
similar, since essentially what I wish to be able to do is have
Audacity
think I typed the 'R' key:
os.system(r'c:\progra~1\audacity/audacity.exe R')
All this
I guess my question is, would it be acceptable to post this much
code to the
list?
Probably about the limit for posting, but if you can put it on
a web site somewhere and post a URL that would be fine...
the body of the message or as an attachment? I would think an
attachment
would be better
foo.py -
import parrot
class Bar(model.Background):
def __initialize__(self, event):
#Just a pythoncard variant on init
self.config=self.loadCfg()
def loadCfg():
#get some cfg stuff, return as dict
return cfgDict
def
How well would a multi user texed based game created in just Python
run if there were over 300 - 400 players (Just a hypathetical
question) Would python be to slow to handle that amount of traffic?
That depends entirely on how it was designed and what kind
of hardware you ran it on. If you
1. Why does the assignment-and-test in one line not allowed in
Python?
For example, while ((content = fd.readline()) != ):
Because Guido didn't write it that way? ;-)
And that may have been because it is such a common source of bugs.
So common in fact that many compilers now offer to emit a
Whether or not it's positive or negative depends on which side of
GMT/UTC
you are, of course :) Note that the result in is seconds, too:
Which is insane since timezones have nothing to do with time offsets.
Especially at the second level!
Oh well, nothing is perfect!
Alan G.
(Feeling picky
This is something I've been trying to figure out for some time. Is
there a way in Python to take a string [say something from a
raw_input] and make that string a variable name? I want to to this
so
that I can create class instances on-the-fly, using a user-entered
string as the instance
Greetings all, I'm new to python and thought I'd pop in here for
advice.
Good decisions both :-)
I've done object oriented design and programmed in perl, java, c++,
basic, etc.
...
I'm curious about good tutorial websites and books to buy.
With your background the standard Python tutorial
I hear that Alan Gauld's tutorial is also very good, but geared more
towards people new to programming.
Yes, I try to take folks to the point where they can understand the
official tutor (well maybe a wee bit further than that, but that
was the original target...)
(which itself should be in
for i in range(len(a)):
for k in range(len(a)):
for k in range(i,len(a)):
is faster, and if you calculate len before starting the
loops that will speed it up too. (You calculate len for
each iteration of each loop!)
if i != k:
if a[i] == a[k]:
print a[i]
break
HTH
Alan G.
functions with initial capital letters. In many languages, this
implies
a new type (like your Water class). so CombineWater should be
combineWater.
Do you mean implies by the dominant coding conventions, or by
language
syntax? (Indulging the curious pedant in me.)
Coding convention. Its
Does anyone happen to know how to turn of the syntax checking in
python? I've been working on a module driven preprocessor but I'd
like to not have to use comment strings.
So don't use them! They aren't mandatory.
I'm not sure I understand youir problem? Why would turning
off syntax
I don't get this joke, but it sounds like the basis for it
would be interesting. Can you explain?
After sending my last message I was browsing the Eiffel site and
found an example of the IDE.
Its here:
http://archive.eiffel.com/eiffel/nutshell.html
and you scroll down to the question:
SEveral solutions here.
The best is to restructure the code a little:
def go_jogging():
# go out and jog
return
if not bad_weather == 'y': # where is this initially set BTW?
go_jogging()
else
# ask user only if weather is bad.
b = input ( Weather is really bad,
print Percent completed: + str(percent) + \r
Which should send me back to the beginning of the line and overwrite
it
with a new line. But instead I get:
Percent completed: 50
Percent completed: 51
Print always adds a newline unless you put a comma at the end.
Unfortunately that results in
a Nutshell. In the chapter of exception handling, it says: Note
that
the try/finally form is distinct from the try/except form: a try
statement cannot have both except and finally clauses, as execution
order might be ambiguous.
I don't understand the reason why except and finally clauses
histograms for. I'd like to round the data to the nearest 10, i.e if
the value is 15.34 should we round down to 10? and conversely
rounding
say 19.30 to 20. I'm thinking 15.5 and above would round up. Can
anyone
point me a at a quick and painless way of achieving this?
divide by 10, round
1 - 100 of 9336 matches
Mail list logo