Re: [Tutor] Printing Problem python 3
Dave Crouse wrote: I got the same thing with idle, but when running as a script, it's not the same, it errors. I tried it on Windows and Linux. --- [da...@arch64 Python]$ less test.py #/usr/bin/python3 print ('The \"This is a test \" {') [da...@arch64 Python]$ sh test.py test.py: line 3: syntax error near unexpected token `'The \"This is a test \" {'' test.py: line 3: `print ('The \"This is a test \" {')' Maybe I'm missing something, but this error is because you're running a Python script using the Linux shell, probably bash as the interpreter instead of Python. Also, if you're running it on its own as a script, you'd want to add a '!' after the '#' - otherwise it's just a comment, not setting the interpreter. To run a Python file as a script, you'd need to do: [da...@arch64 Python]$ python3 test.py (or just ./test.py if it's executable and the interpreter is set using '#!/usr/bin/python3') When I do that, it works for me just fine without doubling the '{' Cheers, Vern -- This time for sure! -Bullwinkle J. Moose - Vern Ceder, Director of Technology Canterbury School, 3210 Smith Road, Ft Wayne, IN 46804 vce...@canterburyschool.org; 260-436-0746; FAX: 260-436-5137 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Add newline's, wrap, a long string
"David" wrote I don't know how else to describe it, that is so cool :) :-) Couple of comments below. import textwrap data = {'CBUILD':None, 'CFLAGS':None, 'MAKEOPTS':None} def get_use(): fname = open('/tmp/comprookie2000/emerge_info.txt') for line in fname: for keyphrase in data: if keyphrase in line: output = line.split('"')[1] data[keyphrase] = textwrap.fill(output, 80) fname.close() get_use() It would be better practice to put data inside the function and then return the result. Also I'd pass the filename into the function. def get_use(fname): data = for line in open(fname): return data data = get_use('/tmp/foo/bar/baz.txt') That makes the function, and therefore the module, more easily reusable and allows you to call the function several times on different files wityhout overwriting the results. You may not need to do that now but it might be useful in the future. CBUILD = data['CBUILD'] CFLAGS = data['CFLAGS'] MAKEOPTS = data['MAKEOPTS'] Don't bother storing in variables just use the dictionary directly in your print statements. Learn to love and use Python's collections. They are the secret of much of Python's power. Just some thoughts, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to Extend a class in another file in same directory
sudhanshu gautam wrote: 2.Now another file in which I want to extend that same parent class is here .First code running successfully but in another one having problem 'This another source code will represent the new Entry of database' import title class Newstudent(Studentdatabase): def __init__(self,name,age,standard,place,dateofbirth,sex,marks): Studentdatabase.__init__(self,name,age,standard,place,dateofbirth,sex) self.marks=marks print 'The new data base has name of new students',self.name def tell(self): Studentdatabase.tell(self) print 'The marks of the student is',self.marks s1=Newstudent('Rajiv',21,'M.B.A','MUMBAI','12 JAN,1987','MALE',267) s2=Newstudent('VIKASH',22,'M.B.A','DELHI','12 JAN 1985','MALE',234) s3=Newstudent('SAURAV',23,'B.TECH','BIHAR','12 JAN 1984','MALE',233) new=[s1,s2,s3] for newstudent in new: newstudent.tell() Now tell me that how I can extend it You should tell the error message that you get, not just say "an error". So we must guess. If you want to refer to a name (Studentdatabase) in another module, you must import that module. Assuming some things about your sys.path, that could be as simple as import title This you did correctly. Then referencing the name inside that other module is done by using class Newstudent(title.Studentdatabase): Note there is another choice, suitable if there's really only a single name you want to import: from title import Studentdatabase That way, the name can be used without a prefix. I usually prefer the first form, but the second has definite uses, especially if the import is of a module several levels down in a package hierarchy. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Printing Problem python 3
I got the same thing with idle, but when running as a script, it's not the same, it errors. I tried it on Windows and Linux. --- [da...@arch64 Python]$ less test.py #/usr/bin/python3 print ('The \"This is a test \" {') [da...@arch64 Python]$ sh test.py test.py: line 3: syntax error near unexpected token `'The \"This is a test \" {'' test.py: line 3: `print ('The \"This is a test \" {')' [da...@arch64 Python]$ python3 Python 3.0.1 (r301:69556, Feb 22 2009, 14:12:04) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print ('The \"This is a test \" {') The "This is a test " { >>> --- However the double quotes was exactly what the doctor ordered ! :) 2009/4/29 "Shantanoo Mahajan (शंतनू महाजन)" : > print ('The \"This is a test \" {') ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Printing Problem python 3
On 30-Apr-09, at 12:12 AM, Dave Crouse wrote: Trying to print something with a { in it. Probably extremely simple, but it's frustrating me. :( print ('The \"This is a test \" {') i get this error ValueError: Single '{' encountered in format string Worked perfectly for me. === $ python3.0 Python 3.0 (r30:67503, Jan 14 2009, 09:13:26) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> print ('The \"This is a test \" {') The "This is a test " { >>> === - shantanoo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Conventional Y Axis Label in pylab plot
I'd like to label the plot axes as x and y. All I see is xlabel and ylabel. ylabel puts y on its side, rotated 90 degrees from the horizontal. Is there way to put it in a normal reading position? -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39° 15' 7" N, 121° 2' 32" W, 2700 feet All the neutrons, and protons in the human body occupy a cube whose side is 5.52*10**-6 meters (tiny!). That adds up to a 150 pound person. It's not a surprise that we are mostly space. (Calculation by WTW) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Printing Problem python 3
The double {{ }} worked perfectly, THANK YOU ! :) This was driving me crazy. On Wed, Apr 29, 2009 at 2:03 PM, Kent Johnson wrote: > print ('The \"This is a test \" {') > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Printing Problem python 3
On Wed, Apr 29, 2009 at 2:42 PM, Dave Crouse wrote: > Trying to print something with a { in it. > Probably extremely simple, but it's frustrating me. :( > > print ('The \"This is a test \" {') > > i get this error > > ValueError: Single '{' encountered in format string It works for me: Python 3.0.1 (r301:69561, Feb 13 2009, 20:04:18) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> print ('The \"This is a test \" {') The "This is a test " { I guess you have redefined print() to use the latest style of string formatting: http://www.python.org/dev/peps/pep-3101/ Try using double braces {{ Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] How to Extend a class in another file in same directory
I made a program named as a title.py inside it used Inheritance , now I want to Extend the Parent Class in another program(file also) but having an Error lets check ,my code 1.first file title .py class global Studentdatabase: def __init__(self,name,age,standard,place,dateofbirth,sex): self.name=name self.age=age self.standard=standard self.place=place self.dateofbirth=dateofbirth self.sex=sex print 'Initalizing',self.name def tell(self): 'TELL DETAILS' print 'NAME,AGE,STANDARD,PLACE,DATEOFBIRTH,SEX',self.name ,self.age,self.standard,self.place,self.dateofbirth,self.sex class Teacher(Studentdatabase): def __init__(self,name,age,standard,place,dateofbirth,sex,salary): Studentdatabase.__init__(self,name,age,standard,place,dateofbirth,sex) self.salary=salary print 'name is ',self.name def tell(self): Studentdatabase.tell(self) print 'The salary is',self.salary class Student(Studentdatabase): def __init__(self,name,age,standard,place,dateofbirth,sex,marks): Studentdatabase.__init__(self,name,age,standard,place,dateofbirth,sex) self.marks=marks print 'The name',self.name def tell(self): Studentdatabase.tell(self) print 'The marks is',self.marks t=Teacher('Mr.sudhanshu',21,'B.E','Jaipur','12/02/1986','MALE',21000) s=Student('Anirudh',19,'Engineering','Delhi','12/3/1989','MALE',65) members=[t,s] for member in members: member.tell() 2.Now another file in which I want to extend that same parent class is here .First code running successfully but in another one having problem 'This another source code will represent the new Entry of database' import title class Newstudent(Studentdatabase): def __init__(self,name,age,standard,place,dateofbirth,sex,marks): Studentdatabase.__init__(self,name,age,standard,place,dateofbirth,sex) self.marks=marks print 'The new data base has name of new students',self.name def tell(self): Studentdatabase.tell(self) print 'The marks of the student is',self.marks s1=Newstudent('Rajiv',21,'M.B.A','MUMBAI','12 JAN,1987','MALE',267) s2=Newstudent('VIKASH',22,'M.B.A','DELHI','12 JAN 1985','MALE',234) s3=Newstudent('SAURAV',23,'B.TECH','BIHAR','12 JAN 1984','MALE',233) new=[s1,s2,s3] for newstudent in new: newstudent.tell() Now tell me that how I can extend it regards sudhanshu :) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Printing Problem python 3
Trying to print something with a { in it. Probably extremely simple, but it's frustrating me. :( print ('The \"This is a test \" {') i get this error ValueError: Single '{' encountered in format string ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary, integer, compression
Alan I want to perform test runs on my local machine with very large numbers of integers stored in a dictionary. As the Python dictionary is an built-in function I thought that for very large dictionaries there could be compression. Done correctly, integer compression wouldn't affect performance but could enhance it. Weird, I know! I'll check in with the comp.lang.python lot. Dinesh Message: 3 Date: Wed, 29 Apr 2009 17:35:53 +0100 From: "Alan Gauld" Subject: Re: [Tutor] Dictionary, integer, compression To: tutor@python.org Message-ID: Content-Type: text/plain; format=flowed; charset="iso-8859-1"; reply-type=original "Dinesh B Vadhia" wrote > Say, you have a dictionary of integers, are the integers stored > in a compressed integer format or as integers ie. are integers > encoded before being stored in the dictionary and then > decoded when read? I can't think of any reason to compress them, I imagine they are stored as integers. But given the way Python handlers integers with arbitrarily long numbers etc it may well be more complex than a simple integer (ie 4 byte number). But any form of compression would be likely to hit performamce so I doubt that they would be compressed. Is there anything that made you think they might be? HTH -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Fw: imported scope
Le Wed, 29 Apr 2009 12:32:57 -0400, Kent Johnson s'exprima ainsi: > On Wed, Apr 29, 2009 at 10:54 AM, spir wrote: > > Le Wed, 29 Apr 2009 10:05:04 -0400, > > Kent Johnson s'exprima ainsi: > >> There is some discussion here: > >> http://mail.python.org/pipermail/python-3000/2007-March/006161.html > >> > >> Short answer: __builtins__ is an implementation detail that you should > >> ignore. > >> > >> Kent > >> > > > > Right, thank you, Kent. > > The issue here is I cannot ignore __buitins__ (or __builtin__). Or maybe > > I don't understand your answer properly. > > > > Yop, sorry, I get it now. It's the same dict in both cases -- except > > __buitins__ is expanded in the second case... Not obvious! (Is that what > > you mean?) > > What are you trying to do? Why can't you ignore __builtins__? Actually, I don't mind of __builtins__, but of vars() or locals(). The issue is that __builtins__ were monstruously ;-) obfuscating a scope dict I needed. In fact, I printed it out to check it contains what I want; when I saw all that stuff there I thought there was something wrong in my method. Actually the dict contains what I need, and only 4 elements. Simply one of them is veeery BIG. For the sake of information, the reason for this is I need a kind of dynamic scoping, i.e. getting the vars from the caller scope; while python is statically scoped. I cannot find any other way than passing e.g. vars(). Hints welcome. By the way, I asked previously about the difference between vars() and locals() (couldn't find a situation where they differ). Still have no idea, and there seems to be nothing about that in docs. So why both? [...] > Kent Denis -- la vita e estrany -- la vita e estrany ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Add newline's, wrap, a long string
Alan Gauld wrote: "Sander Sweers" wrote What you can do is define all the variables upfront. This way you can get rid of the else. Below is an example how you can do this with only looping once over the fle. And you can put the variables as keys of a dictionary and avoid all the if tests: data = {'CBUILD':None, 'ACCEPT_KEYWORDS: None, } for line in fname: for keyphrase in data: if keyphrase in line: output = line.split('"')[1] data[keyphrase] = textwrap.fill(output, 80) I don't know how else to describe it, that is so cool :) [code] #!/usr/bin/python import textwrap data = {'CBUILD':None, 'CFLAGS':None, 'MAKEOPTS':None} def get_use(): fname = open('/tmp/comprookie2000/emerge_info.txt') for line in fname: for keyphrase in data: if keyphrase in line: output = line.split('"')[1] data[keyphrase] = textwrap.fill(output, 80) fname.close() get_use() CBUILD = data['CBUILD'] CFLAGS = data['CFLAGS'] MAKEOPTS = data['MAKEOPTS'] print 'CBUILD =',CBUILD print 'CFLAGS =',CFLAGS print 'MAKEOPTS =',MAKEOPTS [output] CBUILD = x86_64-pc-linux-gnu CFLAGS = -march=opteron -O2 -pipe MAKEOPTS = -j3 Thanks Alan Martin, Sander, hope I did it correctly. -- Powered by Gentoo GNU/Linux http://linuxcrazy.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Add newline's, wrap, a long string
"Sander Sweers" wrote What you can do is define all the variables upfront. This way you can get rid of the else. Below is an example how you can do this with only looping once over the fle. And you can put the variables as keys of a dictionary and avoid all the if tests: data = {'CBUILD':None, 'ACCEPT_KEYWORDS: None, } for line in fname: for keyphrase in data: if keyphrase in line: output = line.split('"')[1] data[keyphrase] = textwrap.fill(output, 80) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary, integer, compression
Dinesh B Vadhia wrote: > Say, you have a dictionary of integers, are the integers stored in a > compressed integer format or as integers ie. are integers encoded before > being stored in the dictionary and then decoded when read? Integer objects are not special cased in dictionaries. They are stored as normal int/long objects. Dictionaries do not use any kind of compression in Python. Stefan ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary, integer, compression
"Dinesh B Vadhia" wrote Say, you have a dictionary of integers, are the integers stored in a compressed integer format or as integers ie. are integers encoded before being stored in the dictionary and then decoded when read? I can't think of any reason to compress them, I imagine they are stored as integers. But given the way Python handlers integers with arbitrarily long numbers etc it may well be more complex than a simple integer (ie 4 byte number). But any form of compression would be likely to hit performamce so I doubt that they would be compressed. Is there anything that made you think they might be? HTH -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] imported scope
On Wed, Apr 29, 2009 at 10:54 AM, spir wrote: > Le Wed, 29 Apr 2009 10:05:04 -0400, > Kent Johnson s'exprima ainsi: >> There is some discussion here: >> http://mail.python.org/pipermail/python-3000/2007-March/006161.html >> >> Short answer: __builtins__ is an implementation detail that you should >> ignore. >> >> Kent >> > > Right, thank you, Kent. > The issue here is I cannot ignore __buitins__ (or __builtin__). Or maybe I > don't understand your answer properly. > > Yop, sorry, I get it now. It's the same dict in both cases -- except > __buitins__ is expanded in the second case... Not obvious! (Is that what you > mean?) What are you trying to do? Why can't you ignore __builtins__? In your first example __builtins__ is a reference to a module. In the second example it is the module's __dict__. The email thread I linked to indicates that this is most likely a historical accident or oversight. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Dictionary, integer, compression
This could be a question for the comp.lang.python list but I'll try here first: Say, you have a dictionary of integers, are the integers stored in a compressed integer format or as integers ie. are integers encoded before being stored in the dictionary and then decoded when read? Dinesh ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] testing framework
Hello Spir! On Thursday 23 April 2009, spir wrote: > I would like to refactor tests of an application in a consistent > form. I have a ton of tests for each module, but they are all ad > hoc things. doctest looks great. The issue is it seems based on > command line-like testing: I have researched a workable solution based on the "py.test" framework. http://codespeak.net/py/dist/test/test.html (The nose framework works in a very similar way http://code.google.com/p/python-nose/) I think doctests are only for small examples that illustrate the docstrings. The "unittest" library has problems with library modules that use each other; one has to tweak "sys.path" prior to testing. (Doctests probably have this problem with "sys.path" too.) To use the "py.test" script you put all your test code into separate files. The filenames must start with "test_". These files contain test functions; their names must must also start with "test_". The "py.test" script searches for test files and uses a lot of magic to do the right thing, especially it fiddles with "sys.path" Here is your example done with "py.test": start file "test_example.py" def test_factorial(): import example #The import my also fail fact5 = example.factorial(5) assert fact5 == 120 end file "py.test" can also execute tests written with the "unittest" library (important for me). The test files are then structured like this: start file "test_unittest_example.py" import unittest pytest_plugins = "pytest_unittest" class TestExample(unittest.TestCase): #your existing unittest implementation goes here pass end file - "py.test" writes nicely formated stack traces, and code snippets into the terminal window. On Linux at least, it even uses a bit of color and bold text. If you are spoiled by graphical debuggers and clickable error messages (like me), you can also use the test files for debugging with your IDE. You put something like this at the end of the test file: if __name__ == '__main__': test_factorial() #This test triggers the error So, the simplicity of its main concepts makes "py.test" quite convenient. Kind regards, Eike. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] imported scope
On Wed, Apr 29, 2009 at 9:56 AM, spir wrote: > Hello, > > I have an issue with scopes (namespaces). > Say I have a source file 'test.py' with the single line: > print vars() # same with locals() > > Now, from the command-line: > > s...@o:~/prog/pijnu$ python test.py > {'__builtins__': , '__name__': '__main__', > '__file__': 'test.py', '__doc__': None} > > Right, but when imported (my question is at the bottom of the output ;-): > > s...@o:~/prog/pijnu$ python > Python 2.5.2 (r252:60911, Oct 5 2008, 19:24:49) > [GCC 4.3.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information. import test > {'__builtins__': {'IndexError': , 'all': > , 'vars': , 'SyntaxError': > , 'unicode': , > [... here 5918 characters ...] > 'AttributeError': , 'OverflowError': 'exceptions.OverflowError'>}, '__name__': 'test', '__file__': 'test.pyc', > '__doc__': None} > > Can someone explain? There is some discussion here: http://mail.python.org/pipermail/python-3000/2007-March/006161.html Short answer: __builtins__ is an implementation detail that you should ignore. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] imported scope
Hello, I have an issue with scopes (namespaces). Say I have a source file 'test.py' with the single line: print vars() # same with locals() Now, from the command-line: s...@o:~/prog/pijnu$ python test.py {'__builtins__': , '__name__': '__main__', '__file__': 'test.py', '__doc__': None} Right, but when imported (my question is at the bottom of the output ;-): s...@o:~/prog/pijnu$ python Python 2.5.2 (r252:60911, Oct 5 2008, 19:24:49) [GCC 4.3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import test {'__builtins__': {'IndexError': , 'all': , 'vars': , 'SyntaxError': , 'unicode': , [... here 5918 characters ...] 'AttributeError': , 'OverflowError': }, '__name__': 'test', '__file__': 'test.pyc', '__doc__': None} >>> Can someone explain? Denis -- la vita e estrany ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Regular Expresions instances
Thanks to all for the responses. I've filled a bug report as you pointed out. http://bugs.python.org/msg86803 Thanks Emilio - Mensaje original > De: Kent Johnson > Para: Emile van Sebille > CC: tutor@python.org > Enviado: miércoles, 29 de abril, 2009 13:06:49 > Asunto: Re: [Tutor] Regular Expresions instances > > On Tue, Apr 28, 2009 at 7:24 PM, Emile van Sebille wrote: > > Emile van Sebille wrote: > > > Possibly a case of the documentation not keeping up with the release... > > It's pretty easy to file a bug report against the docs. Minor fixes > like this are often incorporated fairly quickly. See > http://docs.python.org/3.0/bugs.html > > Kent > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Add newline's, wrap, a long string
Sander Sweers wrote: > 2009/4/29 David : >> Here is the whole program so far, what it does is it logs into a druple web >> site and posts. I would like to make it better, as you can see I do the same >> thing over and over. >> >> http://linuxcrazy.pastebin.com/m7689c088 > > What you can do is define all the variables upfront. This way you can > get rid of the else. Below is an example how you can do this with only > looping once over the fle. > > CBUILD = '' > ACCEPT_KEYWORDS = '' > > for line in fname: > if 'ACCEPT_KEYWORDS' in line: > output = line.split('"')[1] > ACCEPT_KEYWORDS = textwrap.fill(output, 80) > > if 'CBUILD' in line: > output = line.split('"')[1] > CBUILD = textwrap.fill(output, 80) What is particularly important to note here is that Sander is iterating over the file 'fname' only once. When you loop thru the lines of a file with this form it is consumed, and you get nothing back for subsequent attempts, unless you re-open the file, or explicitly move back to the beginning, ie. fname.seek(0). HTH, Marty > > etc etc > > Greets > Sander > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Add newline's, wrap, a long string
David wrote: > Martin Walsh wrote: >>> ... but, you don't need to use subprocess at all. How about (untested), >>> >>> # grep USE /tmp/comprookie2000/emerge_info.txt |head -n1|cut -d\" -f2 >>> infof = open('/tmp/comprookie2000/emerge_info.txt') >>> for line in infof: >>> if 'USE' in line: >>> USE = line.split('"')[1] >>> break >>> else: >>> USE = '' >>> infof.close() >>> > > Thanks Martin works perfect. So I understand correctly, line.split('"') > splits the list on " so [1] grabs after USE = " and up till [2] starts. That's right, in other words it emulates the behavior of 'cut -d\" -f2'. Python having 0-based indexing, you use 1 instead of 2, etc. > Again thanks, I like the comments :) > -david > Welcome, glad it helped. Marty ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Add newline's, wrap, a long string
2009/4/29 David : > Here is the whole program so far, what it does is it logs into a druple web > site and posts. I would like to make it better, as you can see I do the same > thing over and over. > > http://linuxcrazy.pastebin.com/m7689c088 What you can do is define all the variables upfront. This way you can get rid of the else. Below is an example how you can do this with only looping once over the fle. CBUILD = '' ACCEPT_KEYWORDS = '' for line in fname: if 'ACCEPT_KEYWORDS' in line: output = line.split('"')[1] ACCEPT_KEYWORDS = textwrap.fill(output, 80) if 'CBUILD' in line: output = line.split('"')[1] CBUILD = textwrap.fill(output, 80) etc etc Greets Sander ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Add newline's, wrap, a long string
David wrote: Martin Walsh wrote: Just one more comment, string.join is deprecated, yet join is a method of str objects. So ... Lines = '\n'.join(L) ... or use textwrap.fill which returns a string with the newlines already in place ... Lines = textwrap.fill(USE, 80) HTH, Marty Again thanks, I like the comments :) -david Ok here is what I have now; #!/usr/bin/python import textwrap def get_use(): fname = open('/tmp/comprookie2000/emerge_info.txt') for line in fname: if 'USE' in line: output = line.split('"')[1] USE = textwrap.fill(output, 80) break else: USE = '' fname.close() get_use() Here is the whole program so far, what it does is it logs into a druple web site and posts. I would like to make it better, as you can see I do the same thing over and over. Also I don't think this is a python problem but I can only post one line or I get HTTP/1.1 417 Expectation Failed. I thought the problem was because it was one long string, but that is solved, may be it is looking for return/Enter to be pressed, not sure. http://linuxcrazy.pastebin.com/m7689c088 thanks -david -- Powered by Gentoo GNU/Linux http://linuxcrazy.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] loops
Norman Khine wrote: hello, i have the following code: Uhh... 5 levels deep of nesting, and from the hint that you used self.blah earlier this is inside a class which adds a minimum of two extra levels, in total of 7 levels nesting... We're in deep trouble. is there a way to optimise the loop for 'formats' In this loop: for item in result: print item.abspath item = self.get_handler(item.abspath) namespace['item_title'] = item.get_property('dc:title') if isinstance(training, Training): namespace['item_url'] = item.abspath else: # Need to strip the '/companies' from the path #namespace['item_url'] = Path(item.abspath)[1:] namespace['item_url'] = Path(item.abspath) You assigned namespace['item_title'] and namespace['item_url'] several times throughout the loop, which means only the last item in result would have any lasting significance to the value of namespace['item_title'] and namespace['item_url']. You may be able to just use result[-1] to directly get the last item. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Can not run under python 2.6?
Jianchun Zhou wrote: Hi, there: I am new to python, and now I got a trouble: I have an application named canola, it is written under python 2.5, and can run normally under python 2.5 But when it comes under python 2.6, problem up, it says: Traceback (most recent call last): File "/usr/lib/python2.6/site- packages/terra/core/plugin_manager.py", line 151, in _load_plugins classes = plg.load() File "/usr/lib/python2.6/site-packages/terra/core/plugin_manager.py", line 94, in load mod = self._ldr.load() File "/usr/lib/python2.6/site-packages/terra/core/module_loader.py", line 42, in load mod = __import__(modpath, fromlist=[mod_name]) ImportError: Import by filename is not supported. Any body any idea what should I do? Maybe your problem is related to this: http://mail.python.org/pipermail/python-dev/2008-January/076024.html ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Add newline's, wrap, a long string
Martin Walsh wrote: ... but, you don't need to use subprocess at all. How about (untested), # grep USE /tmp/comprookie2000/emerge_info.txt |head -n1|cut -d\" -f2 infof = open('/tmp/comprookie2000/emerge_info.txt') for line in infof: if 'USE' in line: USE = line.split('"')[1] break else: USE = '' infof.close() Thanks Martin works perfect. So I understand correctly, line.split('"') splits the list on " so [1] grabs after USE = " and up till [2] starts. Just one more comment, string.join is deprecated, yet join is a method of str objects. So ... Lines = '\n'.join(L) ... or use textwrap.fill which returns a string with the newlines already in place ... Lines = textwrap.fill(USE, 80) HTH, Marty Again thanks, I like the comments :) -david -- Powered by Gentoo GNU/Linux http://linuxcrazy.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] loops
On Wed, Apr 29, 2009 at 3:05 AM, Norman Khine wrote: > hello, > i have the following code: > > if unique_id is not None: > training = self.get_site_root() > from training import Training > # link back to news item > root = context.root > formats = ['itinerary', 'news'] > for document in formats: > results = root.search(format=document, unique_id=unique_id) What is root here? What are the allowed parameters for root.search()? Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Regular Expresions instances
On Tue, Apr 28, 2009 at 7:24 PM, Emile van Sebille wrote: > Emile van Sebille wrote: > Possibly a case of the documentation not keeping up with the release... It's pretty easy to file a bug report against the docs. Minor fixes like this are often incorporated fairly quickly. See http://docs.python.org/3.0/bugs.html Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Can not run under python 2.6?
On Wed, Apr 29, 2009 at 2:19 AM, Jianchun Zhou wrote: > Hi, there: > > I am new to python, and now I got a trouble: > > I have an application named canola, it is written under python 2.5, and can > run normally under python 2.5 > > But when it comes under python 2.6, problem up, it says: > > Traceback (most recent call last): > File "/usr/lib/python2.6/site- > packages/terra/core/plugin_manager.py", line 151, in _load_plugins > classes = plg.load() > File "/usr/lib/python2.6/site-packages/terra/core/plugin_manager.py", line > 94, in load > mod = self._ldr.load() > File "/usr/lib/python2.6/site-packages/terra/core/module_loader.py", line > 42, in load > mod = __import__(modpath, fromlist=[mod_name]) > ImportError: Import by filename is not supported. > > Any body any idea what should I do? What's New in Python 2.6 says, "Due to an implementation accident, if you passed a file path to the built-in __import__() function, it would actually import the specified file. This was never intended to work, however, and the implementation now explicitly checks for this case and raises an ImportError." It looks like imp.load_source() may do what you want. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] finding mismatched or unpaired html tags
Lie / Alan re: If the source document was generated by a computer, and it produces invalid markup, shouldn't that be considered a bug in the producing program? Yes, absolutely but we don't have access to the producing program only the produced xhtml files. Dinesh Message: 7 Date: Wed, 29 Apr 2009 08:35:16 +0100 From: "Alan Gauld" Subject: Re: [Tutor] finding mismatched or unpaired html tags To: tutor@python.org Message-ID: Content-Type: text/plain; format=flowed; charset="iso-8859-1"; reply-type=response "Lie Ryan" wrote >> documents were generated by another computer ie. they are not web page >> documents. > > If the source document was generated by a computer, and it produces > invalid markup, shouldn't that be considered a bug in the producing Elementree parses xml, the source docs are html. Valid html may not be valid xml so the source could be correct even though it doesn't parse properly in elemtree. OTOH you could be right! :-) Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] loops
Le Wed, 29 Apr 2009 09:42:44 +0200, "A.T.Hofkamp" s'exprima ainsi: > Norman Khine wrote: > > hello, > > i have the following code: > > > > if unique_id is not None: > > training = self.get_site_root() > > from training import Training > > # link back to news item > > root = context.root > > formats = ['itinerary', 'news'] > > for document in formats: > > results = root.search(format=document, unique_id=unique_id) > > if results: > > Instead of processing results from each search directly, why not first > collect results from all formats, followed by processing of the collected > results? > > ie something like > > results = [] > for doc in formats: > results.extend(root.search()) > > for result in results: > > > This does not give you better performance. However, it does give you the > room to re-organize the searching. > > > In the above, you can now replace the first loop by something like > > results = root.search_all_formats(formats, unique_id) > > > Does this help? > > Albert I find the logic far too complicated, as shown by the outline of the code. You can be sure that in most cases (but not all?) the major complications do not lie in the problem, but in the programmer's views on it. So I would try and find other approaches to simplify the algorithm. Also, you can abstract some of the problematic aspects of the process into funcs, that can each cope with a "limited and well-delimited" part of the problem's field. Hope I'm clear and this helps... def foo(...): ... def bar(...): ... def bazzz(...): ... def blurp(...): ... if blurp(): foo(...) while bazzz(...): bar(...) Denis -- la vita e estrany ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Regular Expresions instances
Le Tue, 28 Apr 2009 22:51:09 + (GMT), Emilio Casbas s'exprima ainsi: > > Hi, > > following the example from > http://docs.python.org/3.0/howto/regex.html > > If I execute the following code on the python shell (3.1a1): > > >>> import re > >>> p = re.compile('ab*') > >>> p > > I get the msg: > <_sre.SRE_Pattern object at 0x013A3440> So do I using python 1.5.2. Slightly better than the version below (at least they tell you you got a %?$£^pattern). > instead of the msg from the example: > I guess this pure question of vocabulary. At a remote point in time the regex package has changed, especially the name of the type for patterns -- and the doc did not follow. > Why I get an SRE_Patterns object instead of a RegexObject instance? Actually, there are loads of lexical issues in the world of programming ;-) What you need to know is, IMO (comments welcome): (1) A pure string is used to describe how source text should be structured. (2) This string is then used to construct an object able to check that. There is a high confusion with terms like 'format', 'pattern', 'rule', 'expression'; and 'regex' itself is used for every other notion, including the *language* used to write strings in (1). I personly use 'pattern' for objects (2) -- but it's far to be a norm. When parsing with regexes, then 'RegexObject' can be a synonym for 'pattern'. On the other hand, you will find all other words, even 'pattern', used in sense (1). > Regards > Emilio Denis -- la vita e estrany ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Add newline's, wrap, a long string
David wrote: I am getting information from .txt files and posting them in fields on a web site. I need to break up single strings so they are around 80 characters then a new line because when I enter the info to the form on the website it has fields and it errors out with such a long string. here is a sample of the code; #!/usr/bin/python import subprocess import os u_e = subprocess.Popen( 'grep USE /tmp/comprookie2000/emerge_info.txt |head -n1|cut -d\\"-f2', shell=True, stdout=subprocess.PIPE,) os.waitpid(u_e.pid, 0) USE = u_e.stdout.read().strip() Why not do the above command sequence entirely in Python instead of this sub-process trickery with its shell quoting problems? It seems a much nicer solution to me. L = len(USE) print L print USE L returns 1337 First stop for any problem that you have: The Python standard library. A search told me that Python has a textwrap module in stdlib. Would that be of use to you? Albert ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] loops
Norman Khine wrote: hello, i have the following code: if unique_id is not None: training = self.get_site_root() from training import Training # link back to news item root = context.root formats = ['itinerary', 'news'] for document in formats: results = root.search(format=document, unique_id=unique_id) if results: Instead of processing results from each search directly, why not first collect results from all formats, followed by processing of the collected results? ie something like results = [] for doc in formats: results.extend(root.search()) for result in results: This does not give you better performance. However, it does give you the room to re-organize the searching. In the above, you can now replace the first loop by something like results = root.search_all_formats(formats, unique_id) Does this help? Albert ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] finding mismatched or unpaired html tags
"Lie Ryan" wrote documents were generated by another computer ie. they are not web page documents. If the source document was generated by a computer, and it produces invalid markup, shouldn't that be considered a bug in the producing Elementree parses xml, the source docs are html. Valid html may not be valid xml so the source could be correct even though it doesn't parse properly in elemtree. OTOH you could be right! :-) Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] loops
hello, i have the following code: if unique_id is not None: training = self.get_site_root() from training import Training # link back to news item root = context.root formats = ['itinerary', 'news'] for document in formats: results = root.search(format=document, unique_id=unique_id) if results: result = results.get_documents() for item in result: print item.abspath item = self.get_handler(item.abspath) namespace['item_title'] = item.get_property('dc:title') if isinstance(training, Training): namespace['item_url'] = item.abspath else: # Need to strip the '/companies' from the path #namespace['item_url'] = Path(item.abspath)[1:] namespace['item_url'] = Path(item.abspath) else: namespace['item_title'] = None namespace['item_url'] = None is there a way to optimise the loop for 'formats' thanks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor