[Tutor] os.getcwd() confusion
G'day, I have a comprehension issue here! I have made two simple scripts: ## script1 import os print os.getcwd() - ## script 2 import os f = open('test', 'wb') f.write(os.getcwd()) f.close() _ Both scripts are in my home directory. Using bash I cd to some other directory and call script 1: > python ../../script1.py and I get this result printed to the screen: > users/scriptdir/dir1/dir2 i.e. the script returns the name of the directory that I'm currently working in. However if I call script2: > python ../../script2.py I get a result that to me seems inconsistent: the script writes the directory that IT is in (i.e., NOT the name of the directory I'm currently working in), to the file 'test' in the home directory. I don't quite understand what is happening here! Any explanation would be much appreciated. Cheers, CSS ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Retrieving data from a web site
On 19/05/13 18:05, Peter Otten wrote: The original Python 2 code: $ cat parse.py import urllib2 import json url = "http://*/goldencasket"; s = urllib2.urlopen(url).read() s = s.partition("latestResults_productResults")[2].lstrip(" =") s = s.partition(";")[0] data = json.loads(s) lotto = data["GoldLottoSaturday"] print lotto["drawDayDateNumber"] print map(int, lotto["primaryNumbers"]) print map(int, lotto["secondaryNumbers"]) $ python parse.py Sat 18/May/13, Draw 3321 [14, 31, 16, 25, 6, 3] [9, 35] It turns out that urllib2 and 3 are both built into python so I didn't have to stress over the dependency error. However, I do have an error and I'm not completely certain that I understand how the code provided by Peter works. The following is the error message: Traceback (most recent call last): File "/home/phil/Python/lotto.py", line 10, in data = json.loads(s) File "/usr/lib/python2.7/json/__init__.py", line 338, in loads return _default_decoder.decode(s) File "/usr/lib/python2.7/json/decoder.py", line 365, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib/python2.7/json/decoder.py", line 383, in raw_decode raise ValueError("No JSON object could be decoded") ValueError: No JSON object could be decoded -- Regards, Phil ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] from import works but I'm flubbing a package import
On 05/19/2013 09:30 PM, Jim Mooney wrote: Still puzzling on imports. I have the jimlib module in Lib with the proper __init__.py . Inside it is the program bark.py, with data item zarf that contains string 'fraz' It also contains the function barker. def barker(): print 'bark, bark' If I do the below everything works: from jimlib import bark print bark.zarf bark.barker() But if I just do import jimlib and chain the program and its functions or data Syntax error. Be more specific, don't just paraphrase. nothing works. If I try jimlib.bark.barker() after importing jimlib or print jimlib.bark.zarf I get the error that the module has no attribute 'bark' that's because you never imported jimlib.bark . I'm doing the from statement right but what am I doing wrong with just importing the whole module and chaining out bark (for bark.py) and the function or data following? Using Py27 and Win 7 Try: import jimlib import jimlib.bark -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] from import works but I'm flubbing a package import
Still puzzling on imports. I have the jimlib module in Lib with the proper __init__.py . Inside it is the program bark.py, with data item zarf that contains string 'fraz' It also contains the function barker. def barker(): print 'bark, bark' If I do the below everything works: from jimlib import bark print bark.zarf bark.barker() But if I just do import jimlib and chain the program and its functions or data nothing works. If I try jimlib.bark.barker() after importing jimlib or print jimlib.bark.zarf I get the error that the module has no attribute 'bark' I'm doing the from statement right but what am I doing wrong with just importing the whole module and chaining out bark (for bark.py) and the function or data following? Using Py27 and Win 7 -- Jim Mooney There is no such thing as a failed experiment ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] model methods in Django
On Sun, May 19, 2013 at 10:49 AM, Matthew Ngaha wrote: > On Sun, May 19, 2013 at 3:34 PM, Steven D'Aprano wrote: >> Matthew, who are you quoting? Your email program should automatically insert >> an attribution line, such as the one just below. Without that attribution >> line, it is hard to follow the conversation, as we can't tell who you are >> quoting. > > ok thanks i didnt think about that. I was quoting eryksun. I'll > includethat line from now on I think this was in reference to your reply to John Steedman. Here's the archive thread (based on the "In-Reply-To" header field): http://mail.python.org/pipermail/tutor/2013-May/thread.html#95521 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] model methods in Django
On Sun, May 19, 2013 at 3:34 PM, Steven D'Aprano wrote: > Matthew, who are you quoting? Your email program should automatically insert > an attribution line, such as the one just below. Without that attribution > line, it is hard to follow the conversation, as we can't tell who you are > quoting. > > On 20/05/13 00:23, Matthew Ngaha wrote: ok thanks i didnt think about that. I was quoting eryksun. I'll includethat line from now on ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Beginner level: Why doesn't my code work?
Rafael Knuth wrote: > Thank you, I am using Python 3.3.0 [Oscar] > In Python 3 you should use input(). In Python 2 you should use > raw_input(). I'm guessing that you're using Python 2. In Python 2 the > input() function tries to evaluate whatever the user types in as if it > was Python code. Since Rafael is not a defined variable it fails. The > fix is to use raw_input() which just returns a string. [Rafael] > I am not sure I understand. > "Rafael" is the user's in put, and that value is assigned to the variable > "name". > I made sure only a string is accepted as input > > name = (str(input("What's your name?")) > > Can you clarify? Thank you in advance. As Oscar says you are invoking your script with Python 2. Python 2's input() function evals user input as a Python expression. For example if you run a script print input("your input please: ") and you type 1 + 1 the script will print 2 Likewise if you type Rafael the script will look up the value of a variable named Rafael. This doesn't exist and therefore you get an exception. But this is all a distraction -- how exactly are you invoking what you think is Python 3.3.0? What is your operating system? If you are using Linux or OSX open a terminal window and try to run your script from that terminal window with python3.3 ~/Documents/3_Tufcik.py ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] model methods in Django
Matthew, who are you quoting? Your email program should automatically insert an attribution line, such as the one just below. Without that attribution line, it is hard to follow the conversation, as we can't tell who you are quoting. On 20/05/13 00:23, Matthew Ngaha wrote: class Poll(models.Model): [...] -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Beginner level: Why doesn't my code work?
On 19/05/13 23:38, Rafael Knuth wrote: Thank you, I am using Python 3.3.0 Based on the error you show, I doubt that very much. As for the HTML ... I copied the code from the Python Shell - should I post code as a screenshot? Would that resolve that issue you mentioned? No. It has nothing to do with the Python shell, it has to do with your email program. Your email program will probably have an option somewhere to send "Rich Text" or "Styled Text" or "HTML Text". Turn it off. There are many reasons to avoid it, but as far as this mailing list goes, the main one is that it mangles the code you send and makes it harder to answer your questions. "Rafael" is the user's in put, and that value is assigned to the variable "name". I made sure only a string is accepted as input name = (str(input("What's your name?")) The call to str() is unnecessary. In Python 3, this works as you would expect: # Python 3.3 py> name = input("What's your name? ") What's your name? Raphael py> print(name) Raphael But when you run it, that's not the result you get. You get this result: # Python 2.7 py> name = input("What's your name? ") What's your name? Raphael Traceback (most recent call last): File "", line 1, in File "", line 1, in NameError: name 'Raphael' is not defined This tells me very strongly that you are actually using Python 2, not Python 3. Try this: at the very beginning of your file 3_Tufcik.py, put these two lines: import sys print(sys.version) then run the file as you would normally, and see what it prints. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] model methods in Django
> options.py is the biggest module in the admin package. The link I > posted is to the get_actions method of ModelAdmin. In the tutorial, > PollAdmin extends this class. > oh ok thanks, yes i will definately look through it > I'm not coming from any framework. My knowledge of web development is > scattered from bits learned here and there, out of curiosity rather > than necessity. With Python 3 you're a bit limited, but you still have > options. Obviously there's Django -- arguably the most popular, > batteries-included framework. Pyramid is a leaner alternative. Bottle > and CherryPy (also a WSGI server) are micro frameworks. There's also > Tornado if you want an asynchronous framework based on callbacks and > coroutines. As there are a lot more guides for Django i think i will stick with it rather than Pyramid. Maybe after ive learnt it well i can pick up Cherrypy as i like the sounds of a small framework with a server. But Django will be my main focus. Thanks for detailing the options for Python 3 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] model methods in Django
> class Poll(models.Model): > > question = models.CharField(max_length=200) > pub_date = models.DateTimeField('date published') > > > > def was_published_recently(self): > return self.pub_date >= timezone.now() - datetime.timedelta(days=1) > > # > > > was_published_recently.admin_order_field = 'pub_date' > was_published_recently.boolean = True > was_published_recently.short_description = 'Published recently?' > > > Source: > https://docs.djangoproject.com/en/dev/intro/tutorial01/ > https://docs.djangoproject.com/en/dev/intro/tutorial02/ > > > I find the Django (and this fragment) very elegant UP TO the comment. > is the dislike after the comment more to do with the python code rather than django itself? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] model methods in Django
On Sun, May 19, 2013 at 7:20 AM, Matthew Ngaha wrote: > Thanks that does clear it up. Also thats a huge script you linked, can options.py is the biggest module in the admin package. The link I posted is to the get_actions method of ModelAdmin. In the tutorial, PollAdmin extends this class. > i ask which framework you're coming from, and why you have decided to > try out django? When i asked around, people's opinions of it weren't > good and i was recommended to try flask but as i only use Python 3, i > won't be able to use Flask. I'm not coming from any framework. My knowledge of web development is scattered from bits learned here and there, out of curiosity rather than necessity. With Python 3 you're a bit limited, but you still have options. Obviously there's Django -- arguably the most popular, batteries-included framework. Pyramid is a leaner alternative. Bottle and CherryPy (also a WSGI server) are micro frameworks. There's also Tornado if you want an asynchronous framework based on callbacks and coroutines. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Beginner level: Why doesn't my code work?
Hello, please post in plain text (not html) in future. Also you should mention what version of Python you're using as it makes a dfference in this case. Thank you, I am using Python 3.3.0 As for the HTML ... I copied the code from the Python Shell - should I post code as a screenshot? Would that resolve that issue you mentioned? In Python 3 you should use input(). In Python 2 you should use raw_input(). I'm guessing that you're using Python 2. In Python 2 the input() function tries to evaluate whatever the user types in as if it was Python code. Since Rafael is not a defined variable it fails. The fix is to use raw_input() which just returns a string. I am not sure I understand. "Rafael" is the user's in put, and that value is assigned to the variable "name". I made sure only a string is accepted as input name = (str(input("What's your name?")) Can you clarify? Thank you in advance. On Sun, May 19, 2013 at 3:16 PM, Oscar Benjamin wrote: > On 19 May 2013 14:04, Rafael Knuth wrote: > > Hello, > > Hello, please post in plain text (not html) in future. Also you should > mention what version of Python you're using as it makes a dfference in > this case. > > > > > here's a tiny little program I wrote: > > > > import random > > > > print(""" > > > > This is a magic super computer. > > > > He will ask you a couple of questions. > > > > An ultra-complicated algorithm will then figure out what your favorite > meal > > is. > > > > """) > > > > name = str(input("What is your name? ")) > > In Python 3 you should use input(). In Python 2 you should use > raw_input(). I'm guessing that you're using Python 2. In Python 2 the > input() function tries to evaluate whatever the user types in as if it > was Python code. Since Rafael is not a defined variable it fails. The > fix is to use raw_input() which just returns a string. > > An alternative fix is to write > > input = raw_input > > at the top of your script. That way you won't need to change anything > else to have it work with Python 3. In fact if you write it like this > > try: > input = raw_input > except NameError: > pass > > then it will work in both Python 2 and 3. > > > Here's the error message I am getting: > > > > Traceback (most recent call last): > > File "/home/rafael/Documents/3_Tufcik.py", line 13, in > > name = str(input("What is your name? ")) > > File "", line 1, in > > NameError: name 'Rafael' is not defined > > > Oscar > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] model methods in Django
For the benefit of others,I believe the full class (from the Django Tutorial) is class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) # was_published_recently.admin_order_field = 'pub_date' was_published_recently.boolean = True was_published_recently.short_description = 'Published recently?' Source: https://docs.djangoproject.com/en/dev/intro/tutorial01/ https://docs.djangoproject.com/en/dev/intro/tutorial02/ I find the Django (and this fragment) very elegant UP TO the comment. On Sat, May 18, 2013 at 8:16 PM, Matthew Ngaha wrote: > im following the official docs and after learning Python im sure of > how methods work, but the model example on the beginners guide has me > really confused. > > The model definition is omitted but can anyone explain how this methed > (was_published_recently) is given these attributes: > > class Poll(models.Model): > # ... > def was_published_recently(self): > return self.pub_date >= timezone.now() - datetime.timedelta(days=1) > was_published_recently.admin_order_field = 'pub_date' > was_published_recently.boolean = True > was_published_recently.short_description = 'Published recently?' > > are the names of the attributes already attached to these > functions/methods, or are they being created on the fly with whatever > name you want? As i am unable to comprehend what is going on, i dont > really have a clue as to what each definition is doing and how it > affects the model, even after reading this section of the docs over > and over again im still lost. > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Beginner level: Why doesn't my code work?
On 19 May 2013 14:04, Rafael Knuth wrote: > Hello, Hello, please post in plain text (not html) in future. Also you should mention what version of Python you're using as it makes a dfference in this case. > > here's a tiny little program I wrote: > > import random > > print(""" > > This is a magic super computer. > > He will ask you a couple of questions. > > An ultra-complicated algorithm will then figure out what your favorite meal > is. > > """) > > name = str(input("What is your name? ")) In Python 3 you should use input(). In Python 2 you should use raw_input(). I'm guessing that you're using Python 2. In Python 2 the input() function tries to evaluate whatever the user types in as if it was Python code. Since Rafael is not a defined variable it fails. The fix is to use raw_input() which just returns a string. An alternative fix is to write input = raw_input at the top of your script. That way you won't need to change anything else to have it work with Python 3. In fact if you write it like this try: input = raw_input except NameError: pass then it will work in both Python 2 and 3. > Here's the error message I am getting: > > Traceback (most recent call last): > File "/home/rafael/Documents/3_Tufcik.py", line 13, in > name = str(input("What is your name? ")) > File "", line 1, in > NameError: name 'Rafael' is not defined Oscar ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Retrieving data from a web site
On 19/05/13 21:46, Dave Angel wrote: Have you simply tried using urlib.request ? That should be built into Python 3.3 without any outside packages from Kubuntu. (I haven't used Kubuntu, just making some bald assumptions) Thanks Dave, Thanks Dave, The urllib.request package has the same dependency problem. I haven't checked to see if it's built into Python yet, it's getting a bit late here. A job for tomorrow. -- Regards, Phil ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Beginner level: Why doesn't my code work?
Hello, here's a tiny little program I wrote: import random print(""" This is a magic super computer. He will ask you a couple of questions. An ultra-complicated algorithm will then figure out what your favorite meal is. """) name = str(input("What is your name? ")) age = int(input("How old are you? ")) birthplace = str(input("Where are you born? ")) meal = random.randint(1, 3) if meal == 1: print("Well, " + name + " as a " + str(age) + " year old human being born in " + birthplace + " you probably like hamburgers.") elif meal == 2: print("Well, " + name + " as a " + str(age) + " year old human being born in " + birthplace + " you probably like sushi.") elif meal == 3: print("Well, " + name + " as a " + str(age) + " year old human being born in " + birthplace + "you probably like pizza.") Here's the error message I am getting: Traceback (most recent call last): File "/home/rafael/Documents/3_Tufcik.py", line 13, in name = str(input("What is your name? ")) File "", line 1, in NameError: name 'Rafael' is not defined Can anyone help? Thanks in advance! Rafael ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Fwd: spyder
Original Message Subject:spyder Date: Sat, 18 May 2013 19:20:12 -0400 From: bob gailer To: ricar...@gmail.com Following your recommendation I installed spyder using the Windows installer. Now what do I do to run it. I found no useful guidance in the online documentation. -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Retrieving data from a web site
On 05/19/2013 07:30 AM, Phil wrote: On 19/05/13 18:05, Peter Otten wrote: Phil wrote: My apatite having been whetted I'm now stymied because of a Ubuntu dependency problem during the installation of urllib3. This is listed as a bug. Has anyone overcome this problem? Perhaps there's another library that I can use to download data from a web page? You mean you are using Python 3? The replacement for urllib2 in Python 3 is urllib.request and a few others. There is a tool called 2to3 that can help you with the transition. Thank you once again Peter for a very helpful reply. Under Ubuntu (I'm actually using Kubuntu) the packages are python-urllib3 (for python 2) and python3-urllib3. Unfortunately neither will install because of a dependency issue with libbz2-1.0. So I'll have to put this project on hold until the bug is resolved. Have you simply tried using urlib.request ? That should be built into Python 3.3 without any outside packages from Kubuntu. (I haven't used Kubuntu, just making some bald assumptions) -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Retrieving data from a web site
On 19/05/13 18:05, Peter Otten wrote: Phil wrote: My apatite having been whetted I'm now stymied because of a Ubuntu dependency problem during the installation of urllib3. This is listed as a bug. Has anyone overcome this problem? Perhaps there's another library that I can use to download data from a web page? You mean you are using Python 3? The replacement for urllib2 in Python 3 is urllib.request and a few others. There is a tool called 2to3 that can help you with the transition. Thank you once again Peter for a very helpful reply. Under Ubuntu (I'm actually using Kubuntu) the packages are python-urllib3 (for python 2) and python3-urllib3. Unfortunately neither will install because of a dependency issue with libbz2-1.0. So I'll have to put this project on hold until the bug is resolved. -- Regards, Phil ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] model methods in Django
> The default description is the name with underscores removed, unless > you set a custom description in the function's "short_description" > attribute. I'm not experienced with Django, so I can't ramble off lots > of examples, but hopefully you get the gist. Thanks that does clear it up. Also thats a huge script you linked, can i ask which framework you're coming from, and why you have decided to try out django? When i asked around, people's opinions of it weren't good and i was recommended to try flask but as i only use Python 3, i won't be able to use Flask. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] model methods in Django
On Sun, May 19, 2013 at 6:35 AM, Matthew Ngaha wrote: > > if you look at the diagram under that function, why is the value of > "was_published_recently.short_description" the title of that field? > replacing the old title? is a "short_desccription" attribute set > somewhere in django being inactive, but once you make use of this > attribute(or keyword), whatever the value is automatically becomes the > field title? is it the same for boolean being the value of the field > with the checked or unchecked symbol? For example, see line 586 in admin/options.py: https://github.com/django/django/blob/1.5.1/django/contrib/admin/options.py#L586 # Gather actions from the admin site first for (name, func) in self.admin_site.actions: description = getattr(func, 'short_description', name.replace('_', ' ')) actions.append((func, name, description)) The default description is the name with underscores removed, unless you set a custom description in the function's "short_description" attribute. I'm not experienced with Django, so I can't ramble off lots of examples, but hopefully you get the gist. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] why is unichr(sys.maxunicode) blank?
- Original Message - > From: Steven D'Aprano > To: tutor@python.org > Cc: > Sent: Sunday, May 19, 2013 3:34 AM > Subject: Re: [Tutor] why is unichr(sys.maxunicode) blank? > > On 19/05/13 02:45, Albert-Jan Roskam wrote about locales: > >> It is pretty sick that all these things can be adjusted separately (what is > the use of having: danish collation, russian case conversion, english decimal > sign, japanese codepage ;-) > > Well obviously there is no point to such a mess, but the ability to make a > mess > comes from having the flexibility to have less silly combinations. > > By the way, I'm not sure what you mean by "pretty sick", since in > Australian slang "sick" can mean "fantastic, excellent", as > in "Mate, that's a pretty sick sub-woofer!". I was under the impression that all these locale categories created a degree of flexibility that is far greater than one would need in daily practice. Eryksun's non-esoteric (note the lack of use of the term "sick" ;-) example convinced me that this is not the case. So all in all, the flexibility is sick after all, not in the literal sense, but in the Australian sense of the word. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] model methods in Django
Thanks guys i had no idea about these method attributes and also these underlying oop __objects__ @ eryksun i understand your explanation, im still having trouble figuring out how django is being used in the tutorial. class Poll(models.Model): # ... def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) was_published_recently.admin_order_field = 'pub_date' was_published_recently.boolean = True was_published_recently.short_description = 'Published recently?' list_filter = ['pub_date'] search_fields = ['question'] date_hierarchy = 'pub_date' if you look at the diagram under that function, why is the value of "was_published_recently.short_description" the title of that field? replacing the old title? is a "short_desccription" attribute set somewhere in django being inactive, but once you make use of this attribute(or keyword), whatever the value is automatically becomes the field title? is it the same for boolean being the value of the field with the checked or unchecked symbol? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Retrieving data from a web site
Phil wrote: > My apatite having been whetted I'm now stymied because of a Ubuntu > dependency problem during the installation of urllib3. This is listed as > a bug. Has anyone overcome this problem? > > Perhaps there's another library that I can use to download data from a > web page? You mean you are using Python 3? The replacement for urllib2 in Python 3 is urllib.request and a few others. There is a tool called 2to3 that can help you with the transition. The original Python 2 code: $ cat parse.py import urllib2 import json url = "http://*/goldencasket"; s = urllib2.urlopen(url).read() s = s.partition("latestResults_productResults")[2].lstrip(" =") s = s.partition(";")[0] data = json.loads(s) lotto = data["GoldLottoSaturday"] print lotto["drawDayDateNumber"] print map(int, lotto["primaryNumbers"]) print map(int, lotto["secondaryNumbers"]) $ python parse.py Sat 18/May/13, Draw 3321 [14, 31, 16, 25, 6, 3] [9, 35] Now let's apply 2to3 (I'm using the version that comes with python3.3). The -w option tells the script to overwrite the original source: $ 2to3-3.3 parse.py -w [noisy output omitted] The script now looks like this: $ cat parse.py import urllib.request, urllib.error, urllib.parse import json url = "http://*/goldencasket"; s = urllib.request.urlopen(url).read() s = s.partition("latestResults_productResults")[2].lstrip(" =") s = s.partition(";")[0] data = json.loads(s) lotto = data["GoldLottoSaturday"] print(lotto["drawDayDateNumber"]) print(list(map(int, lotto["primaryNumbers"]))) print(list(map(int, lotto["secondaryNumbers"]))) $ python3.3 parse.py Traceback (most recent call last): File "parse.py", line 7, in s = s.partition("latestResults_productResults")[2].lstrip(" =") TypeError: expected bytes, bytearray or buffer compatible object After manually changing the line s = urllib.request.urlopen(url).read() to s = urllib.request.urlopen(url).read().decode() $ python3.3 parse.py Sat 18/May/13, Draw 3321 [14, 31, 16, 25, 6, 3] [9, 35] $ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tutor Digest, Vol 111, Issue 61
On Sun, May 19, 2013 at 3:37 AM, Jim Mooney wrote: > > Since Python on Win 7 can already find modules in Lib (and in > site-packages, under Lib) can I assume that it will find any > directories fabricated as mentioned, that are put in Lib or one of its > subdirectories, without doing anything further? > > Also, I didn't have a PYTHONPATH so I made one, but are you allowed > multiple directory entries separated by a semicolon, as in the plain > Windows Path? Putting packages directly in the standard Lib isn't a good idea. Even the main Lib/site-packages should be reserved for installed packages (i.e. setup.py, pip, exe/msi). Use the environment variable PYTHONPATH to add your own list of directories to sys.path. For NT the list is delimited by a semicolon. > And just how detailed must PYTHONPATH be? Can it just > be the PYTHON27 and PYTHON33 directories, or does it have to drill > down to Lib or directories beneath that? Since there was no PYTHONPATH Those directories are already on sys.path. By the way Python's sys.path for importing modules/packages isn't related to the PATH environment variable. NT uses PATH to find and open files and DLLs, e.g. to find python.exe, python33.dll, and your .py scripts run from the command line. > I figured the win path was enough, but I put one in anyway. Or does > Win 7 put something in the registry? (I'm not sure which I dislike > more - IE or the Registry ;') Python does use NT's registry (either HKLM or HKCU, depending on how you installed) for some for some of the base paths, but don't mess with this: C:\>reg query hklm\software\python\pythoncore\2.7\PythonPath HKEY_LOCAL_MACHINE\software\python\pythoncore\2.7\PythonPath (Default)REG_SZ C:\Python27\Lib;C:\Python27\DLLs;C:\Python27\Lib\lib-tk C:\>reg query hklm\software\python\pythoncore\3.3\PythonPath HKEY_LOCAL_MACHINE\software\python\pythoncore\3.3\PythonPath (Default)REG_SZC:\Python33\Lib;C:\Python33\DLLs Alternatively you can use your user profile site-packages. On NT, this defaults to "{userbase}/Python{py_version_nodot}/site-packages", where userbase is "%appdata%\Python". You can change the latter by setting the environment variable PYTHONUSERBASE. Check your current setup as follows: userbase = sysconfig.get_config_var('userbase') usersite = sysconfig.get_path('purelib', '%s_user' % os.name) This is the directory pip uses if you install --user. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tutor Digest, Vol 111, Issue 61
> 1) The directory must be somewhere that Python will see it, no different from > a single file module. That means, in the current directory, or your > PYTHONPATH. Since Python on Win 7 can already find modules in Lib (and in site-packages, under Lib) can I assume that it will find any directories fabricated as mentioned, that are put in Lib or one of its subdirectories, without doing anything further? Also, I didn't have a PYTHONPATH so I made one, but are you allowed multiple directory entries separated by a semicolon, as in the plain Windows Path? And just how detailed must PYTHONPATH be? Can it just be the PYTHON27 and PYTHON33 directories, or does it have to drill down to Lib or directories beneath that? Since there was no PYTHONPATH I figured the win path was enough, but I put one in anyway. Or does Win 7 put something in the registry? (I'm not sure which I dislike more - IE or the Registry ;') Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor