Why do this?
Ok, not really python focused, but it feels like the people here could
explain it for me :)
Now, I started programming when I was 8 with BBC Basic.
I never took any formal classes however, and I have never become an
expert programmer. I'm an average/hobbyist programmer with quite a few
languages under my belt but I cant do any really fancy tricks with any
of them. (although Python might be nudging me into more advanced things,
now I'm starting to get what all the __method__ thingies and operators
are all about)
I learned over the years to do things like the following, and I like
doing it like this because of readability, something Python seems to
focus on :-
Print "There are "+number+" ways to skin a "+furryanimal
But nowadays, I see things like this all over the place;
print("There are %s ways to skin a %s" % (number, furryanimal))
Now I understand there can be additional formatting benefits when
dealing with numbers, decimal places etc.. But to me, for strings, the
second case is much harder to read than the first.
I hope I'm not being dense.
The result is that I have pathalogically avoided print "%s" % (thing)
because it seems to just over complicate things.
Ta, :)
Matt.
This email is confidential and may be privileged. If you are not the intended
recipient please notify the sender immediately and delete the email from your
computer.
You should not copy the email, use it for any purpose or disclose its contents
to any other person.
Please note that any views or opinions presented in this email may be personal
to the author and do not necessarily represent the views or opinions of Digica.
It is the responsibility of the recipient to check this email for the presence
of viruses. Digica accepts no liability for any damage caused by any virus
transmitted by this email.
UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK
Reception Tel: + 44 (0) 115 977 1177
Support Centre: 0845 607 7070
Fax: + 44 (0) 115 977 7000
http://www.digica.com
SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South
Africa
Tel: + 27 (0) 21 957 4900
Fax: + 27 (0) 21 948 3135
http://www.digica.com
--
http://mail.python.org/mailman/listinfo/python-list
RE: Why do this?
>
> | Now, I started programming when I was 8 with BBC Basic.
>
> Hey, likewise! (Except I was 12 when it came out!)
I think it came out before I was 8, and I started out with print and
input. Not sure if that's 'real' programming - I don't think I graduated
to ifs and thens and gotos and gosubs for a while.. Uhm, Or was it 'def
proc' et al for BBC Basic? Brain holes leaking old stuff out :)
> | Print "There are "+number+" ways to skin a "+furryanimal
>
> perfectly sound Python code, as far as it goes, altho' obviously
> "Print" is spelt "print" in Python, and if that number is in fact
> a number it'll need to be str ()-ed first.
Blame outlook and AutoCaps. If number were a number I would write
print "There are",number,"ways to skin a "+furryanimal
..something I like about python, 'cause having been pathalogically
avoiding %'s etc.. I have learned to hate going "string "+str(number)+"
string"
>
> | But nowadays, I see things like this all over the place;
> |
> | print("There are %s ways to skin a %s" % (number, furryanimal))
>
> The outermost brackets are (at the moment) unnecessary in python,
Oops :)
> altho' print is slated for replacement by a function in Python 3.0
> at which point they'll be necessary.
? Why do that, point me at a PEP if required and I'll read it :)
>
> number = 3
> animal = "cat"
> print "There are %d ways to skin a %s" % (number, animal)
>
> | Now I understand there can be additional formatting benefits when
> | dealing with numbers, decimal places etc.. But to me, for
> strings, the
> | second case is much harder to read than the first.
>
> I think what it comes down to is just what's most readable in the
> situation in which you're using it. Imagine a rather longer
> string, and one where and are not short names,
> but calls to some function. Sometimes, since %s will call __str__
> on anything it's passed, it's a quick way to get a string
> representation
> of a more complex object, which you'd otherwise have to str () at
> least.
>
> Also, for me, substitution often reads more naturally because you're
> not breaking the string up with lots of " + + "..." +
> yyy + "...
> stuff. Again, though, depends on what your code looks like, and how
> readable you find it. Certainly, I wouldn't advocate *pathologically*
> avoiding the "%s" % blah style, but it needn't always be the right
> thing.
>
I am a big fan of easily human readable meaningful names for things, to
the extent that I will quite readily use var or function names
ThatCanBeQuiteLongAndExplanatory() For me, it helps retain the
readbility say, when breaking up a string with lots of + xxx + "etc..
Etc.." + lalala
>It may be easier
> to use the
> dictionary form of the substitution then, eg:
>
> print """
> Long string with %(valueA)s and %(valueB)s and %(valueC)s embedded in
> it at some distance from the end...
> ...
> """ % dict (valueA=1, valueB="blah", valueC=datetime.datetime.now ())
>
> Obviously that dict would likely be defined elsewhere, or could even
> be locals (). Once you get to this stage, though, you might want to
> start looking at templating toolkits like Cheetah, Genshi or any of
> the many others knocking around.
>
That's something I wasn't aware of, and I think I'll try if I find
myself going
"something"+dict['thingummy']+" red ones and "+dict['colour']+" ones"
The dict substitution does feel a bit easier to read compared to the
concatenation, because of the dict[''] noise.
Matt.
This email is confidential and may be privileged. If you are not the intended
recipient please notify the sender immediately and delete the email from your
computer.
You should not copy the email, use it for any purpose or disclose its contents
to any other person.
Please note that any views or opinions presented in this email may be personal
to the author and do not necessarily represent the views or opinions of Digica.
It is the responsibility of the recipient to check this email for the presence
of viruses. Digica accepts no liability for any damage caused by any virus
transmitted by this email.
UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK
Reception Tel: + 44 (0) 115 977 1177
Support Centre: 0845 607 7070
Fax: + 44 (0) 115 977 7000
http://www.digica.com
SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South
Africa
Tel: + 27 (0) 21 957 4900
Fax: + 27 (0) 21 948 3135
http://www.digica.com
--
http://mail.python.org/mailman/listinfo/python-list
RE: Why do this?
> Also, having a variable of type str called 'number' seems > perverse (and > probably error prone), so I suspect I might need something like: > And not something I would normally do, but for hastily written contrived examples I might :) >print "There are "+str(number)+" ways to skin a "+furryanimal > > but the format string does the conversion for free. > > The other main reason for preferring format strings is that > they make it > easier to refactor the code. If you ever want to move the > message away from > where the formatting is done then it's a lot easier to > extract a single > string than it is to clean up the concatenation. > -- This is a benefit of pythons implementation of format strings I hadn't considered, that __str__() is called to get the representation. And something I like about python, althgouh at the moment the __xxx__ methods available and their use is something I'm just getting into This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. You should not copy the email, use it for any purpose or disclose its contents to any other person. Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica. It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK Reception Tel: + 44 (0) 115 977 1177 Support Centre: 0845 607 7070 Fax: + 44 (0) 115 977 7000 http://www.digica.com SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South Africa Tel: + 27 (0) 21 957 4900 Fax: + 27 (0) 21 948 3135 http://www.digica.com -- http://mail.python.org/mailman/listinfo/python-list
RE: Why do this?
> Duncan Booth wrote: > > > print "There are"+number+"ways to skin a"+furryanimal > > > > or at least something equivalent to it. If I try to make > the same mistake > > with a format string it jumps out to me as wrong: > > > > "There are%sways to skin a%s" % (number, furryanimal) > > Related to this, formatting with sequences is also much more readable > when there are complex interpunction and quoting characters present, > like this: > > print "'"+var1+"','"+var2'"+","+var3 > > the above is much more readable as > > print "'%s', '%s', %s" % (var1, var2, var3) Hmm, with my hastily written contrived example, I had forgotten about sequences like that. Oddly, in the case above I prefer reading the bottom example, And shouldn't that top one be print "'"+var1+"','"+var2+"',"+var3 ;) So to conclude, in future I will read it, and see how readable it is before I decide. But now at least I do see a reason not to pathalogically avoid such string formatting :) Matt. This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. You should not copy the email, use it for any purpose or disclose its contents to any other person. Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica. It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK Reception Tel: + 44 (0) 115 977 1177 Support Centre: 0845 607 7070 Fax: + 44 (0) 115 977 7000 http://www.digica.com SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South Africa Tel: + 27 (0) 21 957 4900 Fax: + 27 (0) 21 948 3135 http://www.digica.com -- http://mail.python.org/mailman/listinfo/python-list
RE: Why do this?
> [Matthew Warren] > > | Blame outlook and AutoCaps. If number were a number I would write > | > | print "There are",number,"ways to skin a "+furryanimal > > You see now that strikes me as a bit mixed up. Why not simply use? > > print "a", number, "c", string > Habit (not always a good thing..), and it helps keep the distinction as to what is a number and what is s a string. > > Ultimately it's down to you, but I think you may be doing > your code a disservice by so assiduously avoiding the %s-style > of string building. Your last example suggests that you > see the dict-subtitution flavour simply as an alternative to doing > "a" + dict[key1] + "b" + dict[key2] etc. I doubt if I've *ever* > started with the one and ended with the other; rather I've seen that > my code would be more readable if I put/had what I wanted into a > dict (or a dict-like object; just has to support __getitem__). Not quite. I was meaning that where I had things naturally in a dict and found myself concatenating the string, I would now probably use the substitution method. > > An easy example of this is where -- like many, I believe -- I > prefer my > database rows to come in dict-like objects, rather than the > tuples which > the dbapi stipulates. Again, like many, I've used or rolled my own > wrapper > which means I can do things like this, where my dbutils.fetch function > returns some kind of object which traps __getitem__ calls for column > names and returns the appropriate entry in the underlying tuple: > > > import dbutils > db = db_module.connect (...) > for row in dbutils.fetch (db, "SELECT * FROM blah"): > print "Customer %(name)s (%(id)d) has %(n_orders)d > outstanding orders > since %(last_order_date)s" % row > > > > TJG I'm only just really looking into the effects of using things like __getitem__ etc.., I imagine my approach will become more sophisticated once I have looked into them. This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. You should not copy the email, use it for any purpose or disclose its contents to any other person. Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica. It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK Reception Tel: + 44 (0) 115 977 1177 Support Centre: 0845 607 7070 Fax: + 44 (0) 115 977 7000 http://www.digica.com SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South Africa Tel: + 27 (0) 21 957 4900 Fax: + 27 (0) 21 948 3135 http://www.digica.com -- http://mail.python.org/mailman/listinfo/python-list
RE: dictionary of list from a file
> -> > Python 2.5 introduced a dictionary type with automatic
> > creation of values,
> > ala Perl:
> >
> > ===
> > from collections import defaultdict
> >
> > d = defaultdict(list)
> > for line in fl:
> > k, v = line.strip().split()
> > d[k].append(v)
> >
> > for k,v in d.items():
> > print k, v
> > ===
> >
> > Notice that Python is always more strongly typed, so you have
> > to specify a
> > factory function.
>
>
> Yay! Python2.5 fixed my approach to this, I tried
>
> from collections import defaultdict
> f=file('c:\\test.txt')
> lines=f.readlines()
> f.close()
> d=defaultdict(list)
> [ d[l.split()[0]].append(l.split()[1]) for l in lines ]
>
> But, if I try your (to see if I've actually got it right)
>
> For k,v in d.items():
> print k,v
>
> I get
>
> AttributeError: 'list' object has no attribute 'items'
>
Okok, I'm silly.
This email is confidential and may be privileged. If you are not the intended
recipient please notify the sender immediately and delete the email from your
computer.
You should not copy the email, use it for any purpose or disclose its contents
to any other person.
Please note that any views or opinions presented in this email may be personal
to the author and do not necessarily represent the views or opinions of Digica.
It is the responsibility of the recipient to check this email for the presence
of viruses. Digica accepts no liability for any damage caused by any virus
transmitted by this email.
UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK
Reception Tel: + 44 (0) 115 977 1177
Support Centre: 0845 607 7070
Fax: + 44 (0) 115 977 7000
http://www.digica.com
SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South
Africa
Tel: + 27 (0) 21 957 4900
Fax: + 27 (0) 21 948 3135
http://www.digica.com
--
http://mail.python.org/mailman/listinfo/python-list
RE: dictionary of list from a file
> -Original Message- > From: > [EMAIL PROTECTED] > [mailto:[EMAIL PROTECTED] > rg] On Behalf Of Giovanni Bajo > Sent: 04 October 2006 15:17 > To: [email protected] > Subject: Re: dictionary of list from a file > > [EMAIL PROTECTED] wrote: > > > while(){ > > @info=split(/ +/,$_); > > push (@{$tmp{$info[0]}},$info[1]); > > } > > > > and then > > foreach $key (keys %tmp){ > >print "$key -> @{$tmp{$key}}\n"; > > } > > Python 2.5 introduced a dictionary type with automatic > creation of values, > ala Perl: > > === > from collections import defaultdict > > d = defaultdict(list) > for line in fl: > k, v = line.strip().split() > d[k].append(v) > > for k,v in d.items(): > print k, v > === > > Notice that Python is always more strongly typed, so you have > to specify a > factory function. Yay! Python2.5 fixed my approach to this, I tried from collections import defaultdict f=file('c:\\test.txt') lines=f.readlines() f.close() d=defaultdict(list) [ d[l.split()[0]].append(l.split()[1]) for l in lines ] But, if I try your (to see if I've actually got it right) For k,v in d.items(): print k,v I get AttributeError: 'list' object has no attribute 'items' This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. You should not copy the email, use it for any purpose or disclose its contents to any other person. Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica. It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK Reception Tel: + 44 (0) 115 977 1177 Support Centre: 0845 607 7070 Fax: + 44 (0) 115 977 7000 http://www.digica.com SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South Africa Tel: + 27 (0) 21 957 4900 Fax: + 27 (0) 21 948 3135 http://www.digica.com -- http://mail.python.org/mailman/listinfo/python-list
RE: building strings from variables
> -Original Message- > From: > [EMAIL PROTECTED] > [mailto:[EMAIL PROTECTED] > rg] On Behalf Of Gal Diskin > Sent: 05 October 2006 16:01 > To: [email protected] > Subject: building strings from variables > > Following a discussion with an associate at work about various ways to > build strings from variables in python, I'd like to hear your opinions > and preferred methods. The methods we discussed are: > 1. some_string = "cd %s ; %s %d %s %s" % ( working_dir, ssh_cmd, > some_count, some_param1, some_param2) > > 2. import string > template = string.Template("cd $dir ; $cmd $count $param1 > $param2") > some_string = template.substitute(dict(dir=working_dir, > > cmd=ssh_cmd, > > count=some_count, > > pararm1=some_param1, > > param2=some_param2)) > here you can use a couple of nice tricks by using class.__dict__ and > globals() \ locals() dictionaries. > > 3. some_string = "cd "+working_dir+" ; "+ssh_cmd+ " > "+str(some_count)+" "+some_param1+" "+some_param2 > (all these are supposed to produce the same strings) > > Which methods do you know of \ prefer \ think is better because...? > I will appreciate any opinions about the matter. :D I think, it would depend really on what your aims are (readable code, fast string generation...), and how the vars you want to build the string from are respresented in your code (is it natural to use a dict etc..) I kicked off a conversation similar to this earlier today, and that was my conclusion after helpful debate & advice. Matt. This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. You should not copy the email, use it for any purpose or disclose its contents to any other person. Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica. It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK Reception Tel: + 44 (0) 115 977 1177 Support Centre: 0845 607 7070 Fax: + 44 (0) 115 977 7000 http://www.digica.com SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South Africa Tel: + 27 (0) 21 957 4900 Fax: + 27 (0) 21 948 3135 http://www.digica.com -- http://mail.python.org/mailman/listinfo/python-list
Using twisted, not telnetlib for interactive telnet (WAS: RE: Improving telnetlib)
> >The trouble is, I havent got a clue where to start and would > appreciate > >a couple of pointers to get me going... > > > > I'd suggest taking a look at Twisted, which contains a more complete > telnet implementation (not as important for being able to launch vi), > an ssh implementation (which you might want to use instead of telnet), > a VT102 implementation (which is actually what will help you > run programs > that want to fiddle around with the cursor in fancy ways), as > well as a > fair amount of work towards a simple terminal emulator (to > help you keep > track of what vi has done to your virtual terminal). > > API docs for insults: > > http://twistedmatrix.com/documents/current/api/twisted.conch.i > nsults.html > > And for the telnet implementation: > > http://twistedmatrix.com/documents/current/api/twisted.conch.t > elnet.html > Looking through those docs quickly leads me into quite a bewildering maze. As a kind of way to perhaps get me heading in the right direction and understanding how I start to hang all that together to get what I want, I would appreciate it if anyone could look at this little code snippet I have, and illustrate how I can end up doing the same thing with twisted, but end up with an interactive connection that can handle vi... From there I will happily trundle off by myself. I think I'm looking for help in getting that AhA! moment :) Snippet; C=telnetlib.Telnet(self.TCPAddress) . . ((connection / password handling etc..)) . . if AliasedSubbedCmd=='__interact': if system=='UNIX': retkey='^D' else: retkey='^Z' print '\nTELNET entity '+self.Name+' entering interactive mode. Use '+retkey+' to come back\n' C.mt_interact() ...at this point I am essentially on the remote system command line, with a very dumb terminal. How could I do this in twisted and end up with a fairly clever terminal? Thanks, Matt. This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. You should not copy the email, use it for any purpose or disclose its contents to any other person. Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica. It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK Reception Tel: + 44 (0) 115 977 1177 Support Centre: 0845 607 7070 Fax: + 44 (0) 115 977 7000 http://www.digica.com SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South Africa Tel: + 27 (0) 21 957 4900 Fax: + 27 (0) 21 948 3135 http://www.digica.com -- http://mail.python.org/mailman/listinfo/python-list
Bad Code (that works) help me re-write!
I have the following piece of code, taken from a bigger module, that
even as I was writing I _knew_ there were better ways of doing it, using
a parser or somesuch at least, but learning how wasn't as fun as coding
it... And yes alarm bells went off when I found myself typing eval(),
and I'm sure this is an 'unusual' use of for: else: . And I know it's
not very robust. As an ex cuse/planation, this is what happens when you
get an idea in your head and code it until it works, rather than doing
any kind of planning / designing first :)
I have a file that indicates the syntax of commands. User input is
checked against this file until it matches one of the lines in the file.
Then the indicated commands are run.
I think what I have ended up doing is writing a kind of a brute-force
parser for the file format I have defined. The trouble is, I'm sure
there are much more 'agile' and 'elegant' ways of achieveing this, and
also getting rid of eval() !
I'm posting here in the hope that it will criticised, laughed at, picked
apart and hence I shall learn a bit about python and how to do this
properly :)
The code follows, followed by the file defining the syntax of commands.
import re
def dbg(Msg,Fn):
try:
if (TRACE[Fn] or TRACE["ALL"]):
print 'DBG:'+Fn+': '+Msg
except KeyError:
pass
def processsubstitutions(RawCmd):
DBGBN='processsubstitutions'
infprotect=1
subhit=1
while subhit==1:
subhit=0
for sub in Substitutions:
SubCheck=RawCmd
RawCmd=re.sub('~'+sub,' '.join(Substitutions[sub]),RawCmd)
if SubCheck!=RawCmd:
#dbg('Made Substitution '+sub+' to get '+RawCmd,DBGBN)
subhit=1
infprotect=infprotect+1
if infprotect>100:
return "ERROR: Infinitely deep substitution levels
detected."
return RawCmd
#
#...processcommand is called with a string entered by the user.
#
def processcommand(Command):
DBGBN='processcommand'
dbg('Before Substitution: '+Command,DBGBN)
Command=processsubstitutions(Command) # if ! aliascmd then flow
is, RawCmd->subbed->executed
# is IS aliascmd
then flow is RawCmd->Subbed->aliashit->subbed->executed
dbg('After Substitution: '+Command,DBGBN)
AliasHit=0
CommandHit=0
SplitCmd=Command.split()
SplitLen=len(SplitCmd)
Cmd=SplitCmd[0]
InEtcRun=0
Error=0
CommandDefs=file(installroot+'FatControllerCommands.sav','r')
for Def in CommandDefs:
dbg("Scanning cdef ::"+Def,DBGBN)
if Def!='ENDCOMMANDDEFS':
DefTokens=Def.split()
ctr=0
for Token in DefTokens:
dbg("Doing token "+Token,DBGBN)
if re.search('input:',Token):
if SplitLen>ctr:
dbg("Is an input tag. ValExp=",DBGBN)
ValidateExpression=Token.replace('input:','').replace('<<',SplitCmd[ctr]
).replace('::SPACE::',' ')
dbg(ValidateExpression,DBGBN)
else:
Error=1
ErrorText='Error: Missing parameter.'
break
if not eval(ValidateExpression):##NOT SAFE NOT SAFE.
Need to come up with entirely new
##way to do all this
Error=1
ErrorText='Error: Parameter incorrect.'
break
elif re.search('create:',Token):
CreateExpression=Token.replace('create:','').replace('::SPACE::',' ')
elif Token!='+*':
if ctr>=SplitLen:
Error=1
ErrorText='Error: Bad command.'
break
if Token!=SplitCmd[ctr]:
Error=1
ErrorText='Error: Bad command.'
break
ctr+=1
CommandHit=1
else: #{EndOf for Token} all tokens found for else
eval(CreateExpression)
break
else: #{EndOf for Def} Check aliases
for AliasName in Aliases:
if Cmd==AliasName: #then, make cmdstring alias cmd string
and re-process
AliasCmd=' '.join(Aliases[AliasName])
AliasHit=1
dbg('Made alias hit to get '+AliasCmd,DBGBN)
break
else: #FOR loop else not an alias, so try execute as last
entity command
if not CommandHit:
global LastExecutedEntity
if LastExecutedEntity!='':
#global LastExecutedEntity
EntityManager.execute(LastExecutedEntity,SplitCmd[0:])
else:
print '\nError: Dont know which entity to use.\n'
else:
print '\nError: Bad command.\n'
if
RE: Bad Code (that works) help me re-write!
> -Original Message- > From: > [EMAIL PROTECTED] > [mailto:[EMAIL PROTECTED] > rg] On Behalf Of Giles Brown > Sent: 11 October 2006 12:38 > To: [email protected] > Subject: Re: Bad Code (that works) help me re-write! > > Matthew Warren wrote: > > I have the following piece of code, > > No doubt you will get some kind soul to suggest some things, > but if you > want really good > answers I think you need explain why you want this command file (as > opposed to using > say a python script itself). Are you attempting to create a simpler > syntax than Python? > A restricted set of operations? > The code is from a larger project called the FatController. FatController is currently a cli based utility for administering & monitoring devices & applications in an enterprise environment. Users enter commands at the prompt do things such as, define a managed entity, execute instructions against that entity, etc The processcommand() function and the command file are my attempt at implementing the 'commands' that are available to the user. Rather than hard-code all of the syntax and commands inside the module, I wanted an external file to maintain the definitions of the commands available to the user. The idea is that users will be able to implement their own 'entity' modules, which FatController will import and then use to manage devices & applications the given entty applies to. So, at the time of writing the code thought It would be a good idea to have the command definitions file external to the code, so and-users who write their own modules can also extend the cammands available to Fatcontroller for using those modules, if required. Matt. This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. You should not copy the email, use it for any purpose or disclose its contents to any other person. Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica. It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK Reception Tel: + 44 (0) 115 977 1177 Support Centre: 0845 607 7070 Fax: + 44 (0) 115 977 7000 http://www.digica.com SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South Africa Tel: + 27 (0) 21 957 4900 Fax: + 27 (0) 21 948 3135 http://www.digica.com -- http://mail.python.org/mailman/listinfo/python-list
RE: Any idea how to do this in Python?
> On 17 Oct 2006 02:56:45 -0700, Lad <[EMAIL PROTECTED]> wrote: > > > > Dennis, > > Thank you for your reply > > You say: > > >Pretend you are the computer/application/etc. How would YOU > > > perform such a ranking? > > That is what I do not know , how to perform such ranking. > > Do you have any idea? > Maybe something like, As you capture the input from the web form in your python app on the server, pull out the keywords you are interested in and store those together with logon/user information in a database. Alongside that, store the text for all your adverts in a database along with a list of keywords for each advert. Then, when it comes to displaying the targeted adverts on a webpage, grab the user keywords from the database, use them to match against adverts that have the same keywords stored in the database, then choose from those adverts and include the output into your webpage. Something like that should at least ensure the relevant ad's turn up on the page. As to a more sophisticated 'weighting' scheme, you could start doing things like associating values with keywords, matching up which keywords a user has used against the keywords stored against different ads, sum up the total score for each ad, the ads with the highest scores based on the user keywords given should be displayed first.. I havent a clue if there are 'official' ways of doing it, but that's the kind of thing I'd start looking at, anyhoo Matt. To the list: apologies for appended text, I cant get to google groups to post today :/ This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. You should not copy the email, use it for any purpose or disclose its contents to any other person. Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica. It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK Reception Tel: + 44 (0) 115 977 1177 Support Centre: 0845 607 7070 Fax: + 44 (0) 115 977 7000 http://www.digica.com SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South Africa Tel: + 27 (0) 21 957 4900 Fax: + 27 (0) 21 948 3135 http://www.digica.com -- http://mail.python.org/mailman/listinfo/python-list
Return returns nothing in recursive function
Hallo people,
I have the following code that implements a simple recursive tree like
structure.
The trouble is with the GetTreeBranch function, the print statement
prints a valid value but the return immediatley afterward doesn't return
anything.
Can anyone help me with why?
Thanks,
Matt.
Code and output follow;
'''
dirtree
A simple implementation of a filesystem-like tree
datastructure.
'''
def MakeNewTree(rootname='root'):
'''MakeNewTree
Creates an empty tree with a 'root' node.
If the parameter rootname is not given, it
defaults to 'root'.
'''
return [{rootname:[]}]
def DoThingsToTree(path,value,tree,delete=False):
'''_DoThingsToTree
You should not use this function.
'''
if type(path)==type(''):
path=path.lstrip('/').rstrip('/').split('/')
for item in tree:
if type(item)==type({}) and item.has_key(path[0]):
if len(path)==1:
if not delete:
try:
item[path[0]].append(value)
except KeyError:
item[path[0]]=value
else:
if value is not None:
del(item[path[0]][value])
else:
del(tree[tree.index(item)])
break
else:
_DoThingsToTree(path[1:],value,item[path[0]],delete)
def GetTreeBranch(path,tree):
if type(path)==type(''):
path=path.lstrip('/').rstrip('/').split('/')
for item in tree:
if type(item)==type({}) and item.has_key(path[0]):
if len(path)==1:
print 'returning',tree[tree.index(item)]
return tree[tree.index(item)]
else:
GetTreeBranch(path[1:],item[path[0]])
def AddItemToTree(path,value,tree):
'''AddITemToTree
Add an item onto a 'branch' of the tree.
pathshould be a '/' separated string that
defines a path to the branch required.
value an object to put onto the branch
treethe tree to operate on.
'''
DoThingsToTree(path,value,tree)
def AddBranchToTree(path,branch,tree):
'''AddBranchToTree
Add a new branch to the tree.
pathshould be a '/' separated string that
defines a path to the branch required.
branch an object used as the branch identifier
(usually a string)
treethe tree to operate on
'''
DoThingsToTree(path,{branch:[]},tree)
def DelItemFromTree(path,index,tree):
'''DelItemFromTree
Remove an item from the tree.
pathshould be a '/' separated string that
defines a path to the branch required.
index the numeric index of the item to delete
on the branch to delete. items are indexed
in the order they are added, from 0
'''
DoThingsToTree(path,index,tree,delete=True)
def DelBranchFromTree(path,tree):
'''DelBranchFromTree
Remove a branch and all items and subbranches.
pathshould be a '/' separated string that
defines a path to the branch required.
treeThe tree to delete the branch from.
'''
DoThingsToTree(path,None,tree,delete=True)
OUTPUT;
>>> from dirtree import *
>>> MyTree=MakeNewTree('Matt')
>>> AddBranchToTree('Matt','Good',MyTree)
>>> AddBranchToTree('Matt','Bad',MyTree)
>>> AddItemToTree('Matt/Good','Computers',MyTree)
>>> AddItemToTree('Matt/Bad','Drinking',MyTree)
>>> a=GetTreeBranch('Matt/Bad',MyTree)
returning {'Bad': ['Drinking']}
>>> a
>>>
This email is confidential and may be privileged. If you are not the intended
recipient please notify the sender immediately and delete the email from your
computer.
You should not copy the email, use it for any purpose or disclose its contents
to any other person.
Please note that any views or opinions presented in this email may be personal
to the author and do not necessarily represent the views or opinions of Digica.
It is the responsibility of the recipient to check this email for the presence
of viruses. Digica accepts no liability for any damage caused by any virus
transmitted by this email.
UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK
Reception Tel: + 44 (0) 115 977 1177
Support Centre: 0845 607 7070
Fax: + 44 (0) 115 977 7000
http://www.digica.com
SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South
Africa
Tel: + 27 (0) 21 957 4900
Fax: + 27 (0) 21 948 3135
http://www.digica.com
--
http://mail.python.org/mailman/listinfo/python-list
RE: Return returns nothing in recursive function
> break > else: > _DoThingsToTree(path[1:],value,item[path[0]],delete) > The '_' in front of DoThingsToTree shouldn't be there. That's what I get for trimming off the '_' elsewhere after I pasted the code in. Matt. This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. You should not copy the email, use it for any purpose or disclose its contents to any other person. Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica. It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK Reception Tel: + 44 (0) 115 977 1177 Support Centre: 0845 607 7070 Fax: + 44 (0) 115 977 7000 http://www.digica.com SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South Africa Tel: + 27 (0) 21 957 4900 Fax: + 27 (0) 21 948 3135 http://www.digica.com -- http://mail.python.org/mailman/listinfo/python-list
RE: making a valid file name...
>
> Hi I'm writing a python script that creates directories from user
> input.
> Sometimes the user inputs characters that aren't valid
> characters for a
> file or directory name.
> Here are the characters that I consider to be valid characters...
>
> valid =
> ':./,^0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ '
>
> if I have a string called fname I want to go through each character in
> the filename and if it is not a valid character, then I want
> to replace
> it with a space.
>
> This is what I have:
>
> def fixfilename(fname):
> valid =
> ':.\,^0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ '
> for i in range(len(fname)):
> if valid.find(fname[i]) < 0:
> fname[i] = ' '
>return fname
>
> Anyone think of a simpler solution?
>
I got;
>>> import re
>>> badfilename='£"%^"£^"£$^ihgeroighroeig3645^£$^"knovin98u4#346#1461461'
>>> valid=':./,^0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ '
>>> goodfilename=re.sub('[^'+valid+']',' ',badfilename)
>>> goodfilename
' ^ ^ ^ihgeroighroeig3645^ ^ knovin98u4 346 1461461'
This email is confidential and may be privileged. If you are not the intended
recipient please notify the sender immediately and delete the email from your
computer.
You should not copy the email, use it for any purpose or disclose its contents
to any other person.
Please note that any views or opinions presented in this email may be personal
to the author and do not necessarily represent the views or opinions of Digica.
It is the responsibility of the recipient to check this email for the presence
of viruses. Digica accepts no liability for any damage caused by any virus
transmitted by this email.
UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK
Reception Tel: + 44 (0) 115 977 1177
Support Centre: 0845 607 7070
Fax: + 44 (0) 115 977 7000
http://www.digica.com
SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South
Africa
Tel: + 27 (0) 21 957 4900
Fax: + 27 (0) 21 948 3135
http://www.digica.com
--
http://mail.python.org/mailman/listinfo/python-list
RE: Tkinter--does anyone use it for sophisticated GUI development?
> -Original Message- > From: > [EMAIL PROTECTED] > [mailto:[EMAIL PROTECTED] > rg] On Behalf Of Fredrik Lundh > Sent: 20 October 2006 06:43 > To: [email protected] > Subject: Re: Tkinter--does anyone use it for sophisticated > GUI development? > > Kevin Walzer wrote: > > > Coming from Tcl/Tk, where there are a huge number of > extension packages > > to enhance the Tk widgets and which allow you to make > really polished > > GUI's, I'm struck mainly by how little of this stuff has > made it over > > into Tkinter/Python. For instance, I've developed several Tcl > > applications that use the core Tk widgets, the Tile theming > package, the > > Bwidget set (great tree widget and listbox, which allows > you to embed > > images), and tablelist (an extremely flexible muti-column listbox > > display). I've found Python wrappers for some of this > stuff, but almost > > no documentation on how to use them, and very little in the way of > > actual applications making use of them--which is itself a red flag. > > on the other hand, such wrappers are usually extremely > simple, and the > mapping between Python and Tk is trivial. there's simply not much to > add to the existing Tk module docs. > > > Am I better off biting the bullet and learning wxPython--a > different GUI > > paradigm to go with the new language I'm trying to learn? > > that's almost designed to get "wx rul3z d00d" replies from > the wx crowd. > let's see if they bite. > Weell, I'm in no position to evangelise it, but alongised other things for the past two or three weeks I've been looking into different gui building tools for python, wxDesigner, BoaConstructor, pythonCard and a couple of others using both tkInter and wxPython. I've given up trying to find a good one who's method of operation was quick to pick up, and I've since written the basics of my GUI by hand in TkInter and now wxPython (was doing that last night as it goes). ..aand so far wxPython is winning easily on the hand-coded front, especially once you find the demo package and use it. TkInter took me 3 or 4 days without help to work out and build what I needed. WxPython took an evening and 1 usenet post. And I think it looks much nicer. I've yet to see what happens with the event loop of either when I start to use the threaded scheduler I need in the app but hey... Matt. (in wrong place to get to google groups again.. As always apologies for appended text) -- This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. You should not copy the email, use it for any purpose or disclose its contents to any other person. Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica. It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK Reception Tel: + 44 (0) 115 977 1177 Support Centre: 0845 607 7070 Fax: + 44 (0) 115 977 7000 http://www.digica.com SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South Africa Tel: + 27 (0) 21 957 4900 Fax: + 27 (0) 21 948 3135 http://www.digica.com -- http://mail.python.org/mailman/listinfo/python-list
RE: [Tutor] How to get the width of teh button widget..??
Folks, Sorry for asking you such a trivial question.!!! But i want to size up all the buttons with the same size as the largest one in the interface.. And thats why I am asking this question.. Regards, Asrarahmed Hi Asrarahmed. I think, from your recent posts asking questions regarding help with python on this list, you may benefit from reading this document; http://catb.org/~esr/faqs/smart-questions.html You'll find you wont feel a need to apologise so much for your questions too. As to this question, people will really need to know which gui toolkit you are using, and how you have used it to build your buttons. So please post more information regarding the problem, and code you have written and tried to use so far. :) Matt. -- This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. You should not copy the email, use it for any purpose or disclose its contents to any other person.Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica.It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UKReception Tel: + 44 (0) 115 977 1177Support Centre: 0845 607 7070Fax: + 44 (0) 115 977 7000http://www.digica.com SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South AfricaTel: + 27 (0) 21 957 4900Fax: + 27 (0) 21 948 3135http://www.digica.com This message has been scanned for viruses by BlackSpider in Partnership with Digica -- http://mail.python.org/mailman/listinfo/python-list
Telnetlib to twisted
Hallo,
>>> import telnetlib
>>> l=telnetlib.Telnet('dbprod')
>>> l.interact()
telnet (dbprod)
Login:
Could anyone show how the above would be written using the twisted
framework? All I'm after is a more 'intelligent' interactive telnet
session (handles 'vi' etc..) rather than the full capabilities of the
twisted framework.
Thanks,
Matt.
This email is confidential and may be privileged. If you are not the intended
recipient please notify the sender immediately and delete the email from your
computer.
You should not copy the email, use it for any purpose or disclose its contents
to any other person.
Please note that any views or opinions presented in this email may be personal
to the author and do not necessarily represent the views or opinions of Digica.
It is the responsibility of the recipient to check this email for the presence
of viruses. Digica accepts no liability for any damage caused by any virus
transmitted by this email.
UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK
Reception Tel: + 44 (0) 115 977 1177
Support Centre: 0845 607 7070
Fax: + 44 (0) 115 977 7000
http://www.digica.com
SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South
Africa
Tel: + 27 (0) 21 957 4900
Fax: + 27 (0) 21 948 3135
http://www.digica.com
--
http://mail.python.org/mailman/listinfo/python-list
BoaConstructor
..I'm just about to start a project, I have a threaded python app currently around 3000 lines / 12-15 source files that is cli driven, and I am about to start using boaConstructor to build a GUI around it. Has anyone here any advice on wether boaConstructor is actually a good tool for this? The only IDE I have used before was netbeans with Java, and not very extensivley. I'm not neccesarily into getting a boat-load of bells and whistles with my IDE, to start I will be using it generally just as a tool to build a GUI and edit the code. eventually, the App will become big and complicated. Thanks, MattW This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. You should not copy the email, use it for any purpose or disclose its contents to any other person.Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica.It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UKReception Tel: + 44 (0) 115 977 1177Support Centre: 0845 607 7070Fax: + 44 (0) 115 977 7000http://www.digica.com SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South AfricaTel: + 27 (0) 21 957 4900Fax: + 27 (0) 21 948 3135http://www.digica.com This message has been scanned for viruses by BlackSpider in Partnership with Digica -- http://mail.python.org/mailman/listinfo/python-list
RE: Problems with Python 2.5 installer.
-Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of paw Sent: 29 September 2006 11:01 To: [email protected] Subject: Re: Problems with Python 2.5 installer. John Machin wrote: > paw wrote: > > I have ran the MSI installer for Python 2.5 several times attempting to > > install to C: > > Python, however all of the files are placed in C:\ . The installer is > > told to only install files for me, beyond that I have only chosen the > > defaults. > > What do you mean by "install to C: Python"? Can you tell us > (unambiguously, on one line) what directory you chose? Is there any > good reason why you didn't take the default, which is > C:\Python25 > ? Could this happen if c:\python does not exists and creating it fails for some reason, or if permissions are incorrect? This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. You should not copy the email, use it for any purpose or disclose its contents to any other person. Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica. It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK Reception Tel: + 44 (0) 115 977 1177 Support Centre: 0845 607 7070 Fax: + 44 (0) 115 977 7000 http://www.digica.com SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South Africa Tel: + 27 (0) 21 957 4900 Fax: + 27 (0) 21 948 3135 http://www.digica.com -- http://mail.python.org/mailman/listinfo/python-list
RE: Making sure script only runs once instance at a time.
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Hari SekhonSent: 29 September 2006 14:55To: [email protected]: Re: Making sure script only runs once instance at a time. I'm not sure if that is a very old way of doing it, which is why I was reluctant to do it. My way actually uses the process list of the os (linux) and counts the number of instances. If it is more than 0 then another process is running and the script exits gracefully.Also, apart from the fact the using lockfiles feels a bit 1970s, I have found that in real usage of other programs within the company that use lockfiles, it sometimes causes a bit of troubleshooting time when it stops working due to a stale lockfile. This especially happens when the program is killed, the lockfile remains and causes minor annoyance (to somebody who knows that is, more annoyance to somebody who doesn't). This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. You should not copy the email, use it for any purpose or disclose its contents to any other person.Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica.It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UKReception Tel: + 44 (0) 115 977 1177Support Centre: 0845 607 7070Fax: + 44 (0) 115 977 7000http://www.digica.com SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South AfricaTel: + 27 (0) 21 957 4900Fax: + 27 (0) 21 948 3135http://www.digica.com This message has been scanned for viruses by BlackSpider in Partnership with Digica -- http://mail.python.org/mailman/listinfo/python-list
RE: Making sure script only runs once instance at a time.
Apologies for repost. not sure what happened. This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. You should not copy the email, use it for any purpose or disclose its contents to any other person.Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica.It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UKReception Tel: + 44 (0) 115 977 1177Support Centre: 0845 607 7070Fax: + 44 (0) 115 977 7000http://www.digica.com SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South AfricaTel: + 27 (0) 21 957 4900Fax: + 27 (0) 21 948 3135http://www.digica.com This message has been scanned for viruses by BlackSpider in Partnership with Digica -- http://mail.python.org/mailman/listinfo/python-list
Raw strings and escaping
Hi, I would expect this to work, rawstring=r'some things\new things\some other things\' But it fails as the last backslash escapes the single quote. ..although writing this I think I have solved my own problem. Is \' the only thing escaped in a raw string so you can place ' in a raw string? Although I thought the correct thing in that case would be; rawstring=r"rawstring'with single-quote" This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. You should not copy the email, use it for any purpose or disclose its contents to any other person. Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica. It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK Reception Tel: + 44 (0) 115 977 1177 Support Centre: 0845 607 7070 Fax: + 44 (0) 115 977 7000 http://www.digica.com SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South Africa Tel: + 27 (0) 21 957 4900 Fax: + 27 (0) 21 948 3135 http://www.digica.com -- http://mail.python.org/mailman/listinfo/python-list
RE: Escapeism
> -Original Message- > From: > [EMAIL PROTECTED] > [mailto:[EMAIL PROTECTED] > rg] On Behalf Of Kay Schluehr > Sent: 30 September 2006 18:02 > To: [email protected] > Subject: Re: Escapeism > > Sybren Stuvel wrote: > > Kay Schluehr enlightened us with: > > > Usually I struggle a short while with \ and either > succeed or give up. > > > Today I'm in a different mood and don't give up. So here is my > > > question: > > > > > > You have an unknown character string c such as '\n' , > '\a' , '\7' etc. > > > > > > How do you echo them using print? > > > > > > print_str( c ) prints representation '\a' to stdout for c = '\a' > > > print_str( c ) prints representation '\n' for c = '\n' > > > ... > > > > > > It is required that not a beep or a linebreak shall be printed. > > > > try "print repr(c)". > > This yields the hexadecimal representation of the ASCII character and > does not simply echo the keystrokes '\' and 'a' for '\a' ignoring the > escape semantics. One way to achieve this naturally is by prefixing > '\a' with r where r'\a' indicates a "raw" string. But unfortunately > "rawrification" applies only to string literals and not to string > objects ( such as c ). I consider creating a table consisting of pairs > {'\0': r'\0','\1': r'\1',...} i.e. a handcrafted mapping but maybe > I've overlooked some simple function or trick that does the same for > me. > > Kay > > -- > http://mail.python.org/mailman/listinfo/python-list > > > > This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. You should not copy the email, use it for any purpose or disclose its contents to any other person. Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica. It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK Reception Tel: + 44 (0) 115 977 1177 Support Centre: 0845 607 7070 Fax: + 44 (0) 115 977 7000 http://www.digica.com SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South Africa Tel: + 27 (0) 21 957 4900 Fax: + 27 (0) 21 948 3135 http://www.digica.com -- http://mail.python.org/mailman/listinfo/python-list
RE: Escapeism
> -Original Message- > From: > [EMAIL PROTECTED] > [mailto:[EMAIL PROTECTED] > rg] On Behalf Of Matthew Warren > Sent: 03 October 2006 16:07 > To: [email protected] > Subject: RE: Escapeism > > > > > -Original Message- > > From: > > [EMAIL PROTECTED] > > [mailto:[EMAIL PROTECTED] > > rg] On Behalf Of Kay Schluehr > > Sent: 30 September 2006 18:02 > > To: [email protected] > > Subject: Re: Escapeism > > > > Sybren Stuvel wrote: > > > Kay Schluehr enlightened us with: > > > > Usually I struggle a short while with \ and either > > succeed or give up. > > > > Today I'm in a different mood and don't give up. So here is my > > > > question: > > > > > > > > You have an unknown character string c such as '\n' , > > '\a' , '\7' etc. > > > > > > > > How do you echo them using print? > > > > > > > > print_str( c ) prints representation '\a' to stdout for c = '\a' > > > > print_str( c ) prints representation '\n' for c = '\n' > > > > ... > > > > > > > > It is required that not a beep or a linebreak shall be printed. > > > > > > try "print repr(c)". > > > > This yields the hexadecimal representation of the ASCII > character and > > does not simply echo the keystrokes '\' and 'a' for '\a' > ignoring the > > escape semantics. One way to achieve this naturally is by prefixing > > '\a' with r where r'\a' indicates a "raw" string. But unfortunately > > "rawrification" applies only to string literals and not to string > > objects ( such as c ). I consider creating a table > consisting of pairs > > {'\0': r'\0','\1': r'\1',...} i.e. a handcrafted mapping but maybe > > I've overlooked some simple function or trick that does the same for > > me. > > > > Kay > > ((I have no idea why the following was missing from my first attempt to post, and since posting the thread has gone over my head, but wasn't the OP just after a way to print user-inputted strings with '\' in them?))... I cant test this where I am, but would the following work We have our literal user-inputted strings in a list, l=['\a','\b','\c']etc.. For s in l: for c in s: print c, print This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. You should not copy the email, use it for any purpose or disclose its contents to any other person. Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica. It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK Reception Tel: + 44 (0) 115 977 1177 Support Centre: 0845 607 7070 Fax: + 44 (0) 115 977 7000 http://www.digica.com SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South Africa Tel: + 27 (0) 21 957 4900 Fax: + 27 (0) 21 948 3135 http://www.digica.com -- http://mail.python.org/mailman/listinfo/python-list
Improving telnetlib
Hi, I use telnetlib in an app I am writing, and would like to add functionality to it to support interactive terminal sessions , IE: be able to 'vi' a file. Currently it seems telnetlib isnt quite sophisticated enoguh to support such a thing. The trouble is, I havent got a clue where to start and would appreciate a couple of pointers to get me going... Thanks, Matt. This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. You should not copy the email, use it for any purpose or disclose its contents to any other person. Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica. It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK Reception Tel: + 44 (0) 115 977 1177 Support Centre: 0845 607 7070 Fax: + 44 (0) 115 977 7000 http://www.digica.com SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South Africa Tel: + 27 (0) 21 957 4900 Fax: + 27 (0) 21 948 3135 http://www.digica.com -- http://mail.python.org/mailman/listinfo/python-list
RE: Raw strings and escaping
> -Original Message- > From: > [EMAIL PROTECTED] > [mailto:[EMAIL PROTECTED] > rg] On Behalf Of Scott David Daniels > Sent: 03 October 2006 18:11 > To: [email protected] > Subject: Re: Raw strings and escaping > > Matthew Warren wrote: > > Hi, > > > > I would expect this to work, > > > > rawstring=r'some things\new things\some other things\' > > > > But it fails as the last backslash escapes the single quote. > > Note something many people don't when looking over the string rules: > > astring = r'some things\new things\some other things' '\\' > > gives you exactly what you want, doesn't imply a string concatenation > at run time, and various other things. Two strings in succession are > concatenated at source translation time. > > Thanks for this and the other explanations. And you hit the nail on the head with this; >By the way, I renamed the result from being rawstring. It > gives people > bad intuitions to refer to some strings as "raw" when what you really > mean is that the notation you are using is a "raw" notation for a > perfectly normal string. This is exactly the mistake I had made. I was assuming I was dealing with 'raw' in this context Matt. This email is confidential and may be privileged. If you are not the intended recipient please notify the sender immediately and delete the email from your computer. You should not copy the email, use it for any purpose or disclose its contents to any other person. Please note that any views or opinions presented in this email may be personal to the author and do not necessarily represent the views or opinions of Digica. It is the responsibility of the recipient to check this email for the presence of viruses. Digica accepts no liability for any damage caused by any virus transmitted by this email. UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK Reception Tel: + 44 (0) 115 977 1177 Support Centre: 0845 607 7070 Fax: + 44 (0) 115 977 7000 http://www.digica.com SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South Africa Tel: + 27 (0) 21 957 4900 Fax: + 27 (0) 21 948 3135 http://www.digica.com -- http://mail.python.org/mailman/listinfo/python-list
