Re: [Help] [Newbie] Require help migrating from Perl to Python 2.7 (namespaces)
By the way, I think I have found the correct "wording". for my understood, the "handover" of objects to imported modules doesn't work because, e.g. trying to hand-over an SQLite connection into a imported module, can't work because the "attributes" are not transfered. I'm sorry for my bad english, it's fascinating. 2 years ago I've written very large english technical documents for my company. As you can see, the last two years I've forgotten a lot and it tooks me some time to get back into. -- http://mail.python.org/mailman/listinfo/python-list
Re: [Help] [Newbie] Require help migrating from Perl to Python 2.7 (namespaces)
secondly, it is absolutely not bad meaned, but, why does people post, their personal meaning, but nothing about the "Posters" Problem? Everybody is free to read or not, but correcting the WWW could became a very very big task, (maybe it's easier to climb the 7 summits) Best Regards. -- http://mail.python.org/mailman/listinfo/python-list
Re: [Help] [Newbie] Require help migrating from Perl to Python 2.7 (namespaces)
On 22Dec2012 12:43, prilisa...@googlemail.com wrote: | I Think I describe my Situation wrong, the written Project is a | Server, that should store sensor data, perfoms makros on lamps according | a sequence stored in the DB and Rule systems schould regulate home devices and plan scheduler jobs so on. | | The System Runs in a threated environment. It looks for me, like the | limits are at the end of file. my core problem also the only one I have | is: I don't know how to get over that limits and enable dataexchange | like a backbone... Maybe you should post some of the Perl code, in small pieces. Then we can suggest ways those poarticular things might be done in Python. Python threads really easily (with some limitations, but for many purposes those limitations are irrelevant). When I have a situation like yours seems to be, I tend to write a few different items, connected together with a main program. Write modules that define a class for the things you need to talk to: the database, the sensors, etc. From the main program, create an instance of the relevant classes, then dispatch threads doing what needs to be done. The main program might be shaped like this: import db_module # use a better name # defines a class called "DB" to talk to a # database import sensors_module # use a better name # defines a class called "Sensors" to report # sensor values def thread_function(db, sensors): ... do something that should happen in a thread ... # get some objects to connect to db and sensors db = db_module.DB(connection-info-here...) sensors = sensors_module.Sensors(sensor-connection-info-here...) # set up a Thread and start it T = Thread(target=thread_function, args=(db, sensors)) T.start() ... create other threads as needed ... You see here that: - the modules do not know _specifics_ about the db or sensors; they are told connection info - instantiating a class instance: db = db_module.DB(connection-info-here...) passes the specifics - you get back a class instance - you pass those instances (db, sensors) to the thread_function; it uses them to access database and sensors So you see that the modules do not directly share information with each other. The main program gets objects from each module and hands them to whoever needs to work with them. Does this clarify your namespace issues? Cheers, -- Cameron Simpson Whatever is not nailed down is mine. What I can pry loose is not nailed down. - Collis P. Huntingdon -- http://mail.python.org/mailman/listinfo/python-list
Re: Python, email temperature
On Saturday, December 22, 2012 9:36:41 PM UTC+1, KarlE wrote: > Hi! > > > > Im totally new to Python, and im using it on my Raspberry pi. I found a > program that sends an email, and one that checks the temperature of my CPU, > but i cant seem to combine the to into the funktion that i want, sending me > the CPU temp via Email. > > > > The two programs work very well on their own, but this doesnt work. > > > > this works: server.sendmail(fromaddr, toaddrs, msg) > > but this doesnt: server.sendmail(fromaddr, toaddrs, cpu_temperature) > > > > despite the command "print cputemp" working in the same program. > > > > When i run the program i get the error: > > > > Traceback (most recent call last): > > File "sendcpu.py", line 36, in > > msg = cpu_temperature > > NameError: name 'cpu_temperature' is not defined > > > > Does anyone know why the program claims that cpu_temperature isnt defined, > when it is? > > > > Thanx! > > > > //Alexander Ok, im back with a little more understanding of python! I got the program working, every time my Raspberry Pi reboots i get an Email containing information about the boot and the CPU temperature. The issue now is that there seems to be a limitation to how long the message string can be, about 32 letters. The code below works well, but when i add more letters to the string "ord" and pass about 32 in size the email comes through emptpy... I cant find any information about limitations to strings in Python, or the email module. can anyone give me a pointer? (the code lines my appear with different tabbings due to beeing copied from my raspberry pi with Putty, but this is not an issue, all the lines are on the same tab) #!/usr/bin/env python from __future__ import division from subprocess import PIPE, Popen import psutil import smtplib def get_cpu_temperature(): process = Popen(['vcgencmd', 'measure_temp'], stdout=PIPE) output, _error = process.communicate() return float(output[output.index('=') + 1:output.rindex("'")]) def main(): cpu_temperature = get_cpu_temperature() cpu_usage = psutil.cpu_percent() ram = psutil.phymem_usage() ram_percent_used = ram.percent disk = psutil.disk_usage('/') disk_percent_used = disk.percent print 'CPU temperature: ', cpu_temperature fromaddr = 'xxx' toaddrs = 'xxx' username = 'xxx' password = 'xxx' ord = "Subject: Pi Boot, CPU: " + str(cpu_temperature) print len(ord) server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() server.login(username,password) server.sendmail(fromaddr, toaddrs, ord) server.quit() main() -- http://mail.python.org/mailman/listinfo/python-list
Re: Python USB control on Windows 7?
On Sunday, December 23, 2012 06:34:41 PM Chris Angelico wrote: > On Sun, Dec 23, 2012 at 6:28 PM, Tim Roberts wrote: > > Duncan Booth wrote: > >>In this year's Christmas Raffle at work I won a 'party-in-a-box' > >>including USB fairy lights. > >> > >>They sit boringly on all the time, so does anyone know if I can toggle > >>the power easily from a script? My work PC is running Win7. > >> > > Not easily, no. It's not really a USB device -- I'm betting it doesn't > > even enumerate. It's just sucking power from the USB wires. There's > > nothing to control. > > Hmm. Can you control whether a particular port is on or off? (I have > no idea what's possible with the underlying API, much less whether > it's exposed.) It should in theory be possible - disable the > appropriate USB port and the device loses power. > > ChrisA If you have the time; Using communication software, you can control a modem to call, hang up, and call again every few seconds. Since you can make a phone do the same thing, there is most likely a way to get those lights to respond the same way, at least by next Christmas. jd -- http://mail.python.org/mailman/listinfo/python-list
Parsing files in python
Hello: I am writing a program that is made up of a collection of POV-Ray macros. POV-Ray is available at povray.org. It is a ray-tracing program that reads a scene description language (SDL) to create photo-realistic images. At this time my program (for modeling building information) is so huge that I am finding it difficult managing the macros and I am not even near completion. I am hoping to move this program to python and am wondering the best way to approach this. I would like to model my program after LaTeX. Basically the user writes a text file using certain key words and numbers and my python program reads this file, calls the classes that will then work together to calculate the information that is needed to create an accurate model. The result of this calculation will be an output to another text file in the appropriate format such as POV-Ray SDL, OpenSCAD script, etc. This file output can then be rendered by the corresponding program to produce the actual 3D model. The macros I have now currently does this but like I said it is getting tedious and most importantly the fun factor is losing its strength for me. I have been advised to check out python-ply and I have come across others. I have not really tried any yet and before I dive into any one of them I was wondering what else I should know. The following is a sample of what the text file that will be processed by this proposed system will contain. I appreciate any pointers and suggestions. Thank you very much. possible user file content for parsing // in the following the python interface program reads //+ the contents of the file "other.file" as if its content //+ were located at this point. include other.file //In the following the python interface makes "snap_size" a //+ global parameter declare snap_size = 10 // In the following "buildingLevel" is a class that is //+ called and passed the parameters in parenthesis. buildingLevel("FirstLevel", 3000) // In the following "snapOffset" is a class that is //+ called and passed the parameters in parenthesis. snapOffset("Closet-S1_r1", "Closet-S2_r3", <0,0,0>) end of user file content It should also be possible to include comments using double-slashes, etc. Sincerely, Kene (kemen...@gmail.com) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python, email temperature
On 12/23/2012 08:46 AM, KarlE wrote: On Saturday, December 22, 2012 9:36:41 PM UTC+1, KarlE wrote: Hi! Im totally new to Python, and im using it on my Raspberry pi. I found a program that sends an email, and one that checks the temperature of my CPU, but i cant seem to combine the to into the funktion that i want, sending me the CPU temp via Email. The two programs work very well on their own, but this doesnt work. this works: server.sendmail(fromaddr, toaddrs, msg) but this doesnt: server.sendmail(fromaddr, toaddrs, cpu_temperature) despite the command "print cputemp" working in the same program. When i run the program i get the error: Traceback (most recent call last): File "sendcpu.py", line 36, in msg = cpu_temperature NameError: name 'cpu_temperature' is not defined Does anyone know why the program claims that cpu_temperature isnt defined, when it is? Thanx! //Alexander Ok, im back with a little more understanding of python! I got the program working, every time my Raspberry Pi reboots i get an Email containing information about the boot and the CPU temperature. The issue now is that there seems to be a limitation to how long the message string can be, about 32 letters. The code below works well, but when i add more letters to the string "ord" and pass about 32 in size the email comes through emptpy... I cant find any information about limitations to strings in Python, or the email module. can anyone give me a pointer? (the code lines my appear with different tabbings due to beeing copied from my raspberry pi with Putty, but this is not an issue, all the lines are on the same tab) #!/usr/bin/env python from __future__ import division from subprocess import PIPE, Popen import psutil import smtplib def get_cpu_temperature(): process = Popen(['vcgencmd', 'measure_temp'], stdout=PIPE) output, _error = process.communicate() return float(output[output.index('=') + 1:output.rindex("'")]) def main(): cpu_temperature = get_cpu_temperature() cpu_usage = psutil.cpu_percent() ram = psutil.phymem_usage() ram_percent_used = ram.percent disk = psutil.disk_usage('/') disk_percent_used = disk.percent print 'CPU temperature: ', cpu_temperature fromaddr = 'xxx' toaddrs = 'xxx' username = 'xxx' password = 'xxx' ord = "Subject: Pi Boot, CPU: " + str(cpu_temperature) print len(ord) server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() server.login(username,password) server.sendmail(fromaddr, toaddrs, ord) server.quit() main() I'm not sure if Raspberry Pi has it, but usually you want to use the email module, as in example on this page: http://docs.python.org/2/library/email-examples.html#email-examples I think what happens is that because your message starts with 'Subject:', it's interpreted as subject header instead of an email. You can try adding two newlines after Subject:, that might help... but using email module is best if possible. -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Python USB control on Windows 7?
Chris Angelico wrote: > On Sun, Dec 23, 2012 at 6:28 PM, Tim Roberts wrote: >> Duncan Booth wrote: >>> >>>In this year's Christmas Raffle at work I won a 'party-in-a-box' >>>including USB fairy lights. >>> >>>They sit boringly on all the time, so does anyone know if I can >>>toggle the power easily from a script? My work PC is running Win7. >> >> Not easily, no. It's not really a USB device -- I'm betting it >> doesn't even enumerate. It's just sucking power from the USB wires. >> There's nothing to control. Yes, I understand that, I was wondering whether the power could be toggled. > > Hmm. Can you control whether a particular port is on or off? (I have > no idea what's possible with the underlying API, much less whether > it's exposed.) It should in theory be possible - disable the > appropriate USB port and the device loses power. > So far as I can tell Windows doesn't let you turn the ports on and off. I found some suggestion that by connecting it to a powered hub it may be possible to toggle the hub power on and off but that many hubs don't bother implementing the functionality. Thanks anyway. -- Duncan Booth http://kupuguy.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Python, email temperature
On 12/23/2012 08:46 AM, KarlE wrote: > On Saturday, December 22, 2012 9:36:41 PM UTC+1, KarlE wrote: >> Hi! >> >> >> >> Im totally new to Python, and im using it on my Raspberry pi. I found a >> program that sends an email, and one that checks the temperature of my CPU, >> but i cant seem to combine the to into the funktion that i want, sending me >> the CPU temp via Email. >> >> >> >> The two programs work very well on their own, but this doesnt work. >> >> >> >> this works: server.sendmail(fromaddr, toaddrs, msg) >> >> but this doesnt: server.sendmail(fromaddr, toaddrs, cpu_temperature) >> >> >> >> despite the command "print cputemp" working in the same program. >> >> >> >> When i run the program i get the error: >> >> >> >> Traceback (most recent call last): >> >> File "sendcpu.py", line 36, in >> >> msg = cpu_temperature >> >> NameError: name 'cpu_temperature' is not defined >> >> >> >> Does anyone know why the program claims that cpu_temperature isnt defined, >> when it is? >> >> >> >> Thanx! >> >> >> >> //Alexander > Ok, im back with a little more understanding of python! I got the program > working, every time my Raspberry Pi reboots i get an Email containing > information about the boot and the CPU temperature. > > The issue now is that there seems to be a limitation to how long the message > string can be, about 32 letters. The code below works well, but when i add > more letters to the string "ord" and pass about 32 in size the email comes > through emptpy... I don't know the email protocols that well, but I can tell you a Python string isn't limited in size to any small value. Maybe a few hundred million characters, but i haven't tried beyond that. i suspect the limit you're hitting is the limit of subject size in an email protocol. In particular, the 3rd argument to sendmail() needs to have newlines in a particular format before you get to the body of the email. The body can be quite large, but you probably are required to have the appropriate headers first. When you send a short message, does it all come out as a subject line? It would be good to look up the docs on smtplib, but if I had to just do some blind testing, I'd try first adding a newline pair, changing the line to something like: ord = "Subject: Pi Boot, CPU: \r\n" + str(cpu_temperature) + WhateverOtherStuffYouWantedToTry -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: [Help] [Newbie] Require help migrating from Perl to Python 2.7 (namespaces)
Thanks to all your answers, I have read a lot about namespaces, but still there's something I do not understood. I have tried your example but as I expected: line 13, in HandoverSQLCursor curs.execute("SELECT * FROM lager") AttributeError: 'builtin_function_or_method' object has no attribute 'execute' I will try my best to write tomorrow a sample as detailed as possible. Good evening -- http://mail.python.org/mailman/listinfo/python-list
Re: Python USB control on Windows 7?
On 12/23/2012 11:11 AM, Duncan Booth wrote: > So far as I can tell Windows doesn't let you turn the ports on and off. I > found some suggestion that by connecting it to a powered hub it may be > possible to toggle the hub power on and off but that many hubs don't bother > implementing the functionality. > > Thanks anyway. Or you might have more fun if you cut off the USB plug, and drive the thing directly using an Arduino board. You can use the USB serial port on it to prgrammatically turn the thing on and off from your computer, or a billion other possible things. -- http://mail.python.org/mailman/listinfo/python-list
Re: [Help] [Newbie] Require help migrating from Perl to Python 2.7 (namespaces)
prilisa...@googlemail.com wrote: > Thanks to all your answers, I have read a lot about namespaces, but still > there's something I do not understood. I have tried your example but as I > expected: > > line 13, in HandoverSQLCursor > curs.execute("SELECT * FROM lager") > AttributeError: 'builtin_function_or_method' object has no attribute > 'execute' You have assigned a built-in function to the curs variable. Example: >>> curs = open >>> curs.execute Traceback (most recent call last): File "", line 1, in AttributeError: 'builtin_function_or_method' object has no attribute 'execute' You can find out the name of the actual function with >>> print curs.__name__ open PS: This question is only loosely related to your previous question. You should have started a new thread. -- http://mail.python.org/mailman/listinfo/python-list
Re: [Help] [Newbie] Require help migrating from Perl to Python 2.7 (namespaces)
In article , prilisa...@googlemail.com wrote: > Thanks to all your answers, I have read a lot about namespaces, but still > there's something I do not understood. I have tried your example but as I > expected: > > line 13, in HandoverSQLCursor > curs.execute("SELECT * FROM lager") > AttributeError: 'builtin_function_or_method' object has no attribute > 'execute' > > I will try my best to write tomorrow a sample as detailed as possible. > > Good evening Polishing up my crystal ball, I'm going to guess you're using one of the Python Database APIs (http://www.python.org/dev/peps/pep-0249/). And that at some point, you tried to generate a cursor by doing: curs = connection.cursor instead of curs = connection.cursor() This left you with curs being (a reference to) the cursor function itself, rather than what the function returns when it's called. You own the oracle 20 minutes spent reading ESR's classic essay, "How To Ask Questions The Smart Way" (http://tinyurl.com/cabqnop). -- http://mail.python.org/mailman/listinfo/python-list
Re: [Help] [Newbie] Require help migrating from Perl to Python 2.7 (namespaces)
Okay, I try to publish this sample, and yes it's not a working piece of code, but I try to "draw" my problem that way. As you will see, I load modules, create cursor,... in the main.py. In the lower section you see, that the modules should execute sqls. In case It could occur that two queries occur at the same time. PS: IT IS NOT A QUESTION ABOUT SQL, etc. I do not understand, how I could handle the part which is marked with Problemsection1 and Problemsection2 I hope really found the right "wording". thank to all your help. main.py import HomeLog # LogHandler import HomeSocketServer # Threaded TCP Socket Server import HomeDatastore # SQLite DB import HomeDaliServer # Connects to USB Device import HomeScheduler # Advanced scheduler functions # Attach Loghandler Loghandler = HomeLog.Logging() # Attach SocketServer HomeSocketServer.HomeSocketServerStart() # Attach Scheduler HomeSched = HomeScheduler.HomeScheduler() HomeSched.SchedulerStart() HomeSched.SchedulerJobs() # Attach Datastore Datastore=HomeDatastore.HomeDBStore() Datastore=Datastore.Startup() #Attach Dali Driver Dali=HomeDaliServer.Startup() # This is a "Sample" that builds 2byte Cmd and transmits it on bus PowerOnLamp1=Dali.send(0,0,1,80) ### HomeDaliServer.py def send (self,DaliAdress,RequestType,Request,RequestValue): # Problemsection1: # Here it's getting Interesting # We're at the HomeDaliServer, and now I want to use QuerySqlite() in the file HomeDatastore.py ### HomeScheduler.py # Problemsection2: # If new workerthread is started, Informations must be queried using QuerySlite() and also update data ### HomeDatastore.py def QuerySqlite(): #doing something here.. # returning Data ### -- http://mail.python.org/mailman/listinfo/python-list
Re: [Help] [Newbie] Require help migrating from Perl to Python 2.7 (namespaces)
On Sun, 23 Dec 2012 21:42:14 -, wrote: Okay, I try to publish this sample, and yes it's not a working piece of code, but I try to "draw" my problem that way. So instead of telling us what your problem is, you're going to give us an artist's impression of your code and leave us to guess? Sorry but I'm not bored enough to try. -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Python, email temperature
On 12/23/2012 12:23 PM, Mitya Sirenef wrote: On 12/23/2012 08:46 AM, KarlE wrote: On Saturday, December 22, 2012 9:36:41 PM UTC+1, KarlE wrote: from __future__ import division Depending on the linux installed, you should be able to run 3.2 or 3.3 instead of 2.7. Though there are still 2.x only modules, some things work better in 3.x (including default division). server.sendmail(fromaddr, toaddrs, ord) server.quit() main() I'm not sure if Raspberry Pi has it, but usually you want to use the email module, as in example on this page: http://docs.python.org/2/library/email-examples.html#email-examples 3.2+ have a separate .send_message method for email message objects. I think what happens is that because your message starts with 'Subject:', it's interpreted as subject header instead of an email. You can try adding two newlines after Subject:, that might help... but using email module is best if possible. The 3.3 SMTP doc says that the fromaddr and toaddrs are only used by the transport layer and do not become part of the email message. The doc example has msg = ("From: %s\r\nTo: %s\r\n\r\n" % (fromaddr, ", ".join(toaddrs))) The body is appended after the double return. A subject line and any other standard headers would go before. OT note: the PSF (Python Software Foundation) has bought a Raspberry PI and another ARM board to test Python on. I am happy to read that it seems to be working so far. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing files in python
On Mon, Dec 24, 2012 at 4:19 AM, Kene Meniru wrote: > Hello: I am writing a program that is made up of a collection of POV-Ray > macros. POV-Ray is available at povray.org. It is a ray-tracing program that > reads a scene description language (SDL) to create photo-realistic images. At > this time my program (for modeling building information) is so huge that I am > finding it difficult managing the macros and I am not even near completion. I love POV-Ray! Great software, but the input language does at times lack something, so I'm not surprised that you're wanting a pre-parser. > possible user file content for parsing > // in the following the python interface program reads > //+ the contents of the file "other.file" as if its content > //+ were located at this point. > include other.file > > //In the following the python interface makes "snap_size" a > //+ global parameter > declare snap_size = 10 > > > // In the following "buildingLevel" is a class that is > //+ called and passed the parameters in parenthesis. > buildingLevel("FirstLevel", 3000) > > // In the following "snapOffset" is a class that is > //+ called and passed the parameters in parenthesis. > snapOffset("Closet-S1_r1", "Closet-S2_r3", <0,0,0>) > end of user file content > > It should also be possible to include comments using double-slashes, etc. Hmm. That's a fairly complex file format you have there. I wonder if it'd be possible to use an actual language parser for it - for instance, to make this a real Python program. You'd have to use # for a comment rather than //, and vector syntax may be a problem, but for the rest, you should be able to do it all with just one extra line at the top: from povray_macros import * You then write all your macros in a file called povray_macros.py and they'll be conveniently available. For instance: def buildingLevel(name, altitude): print("... whatever POV-Ray code is needed ...") Unfortunately POV-Ray doesn't seem to support reading from stdin, so you can't simply pipe your program into the renderer. But you can do it this way: my_file_whatever_it_is.py >temp.pov povray +Itemp.pov ChrisA -- http://mail.python.org/mailman/listinfo/python-list
how to detect the character encoding in a web page ?
how to detect the character encoding in a web page ? such as this page http://python.org/ -- http://mail.python.org/mailman/listinfo/python-list
Forking into the background (Linux)
My goal is to write a script that 1) write something to stdout; then fork into the background, closing the stdout (and stderr, stdin) pipe. I have found this answer (forking -> setsid -> forking) http://stackoverflow.com/a/3356154 However the standard output of the child is still connected to the terminal. I would like that if we execute a subprocess.checkprocess on this program, only "I would like to see this" is captured and that the program terminates when the parent exits. #! /usr/bin/python2 import os,sys,time print "I would like to see this" pid = os.fork() if (pid == 0): # The first child. # os.chdir("/") os.setsid() # os.umask(0) pid2 = os.fork() if (pid2 == 0): # Second child print "I would like not see this" time.sleep(5) else: sys.exit()#First child exists else: # Parent Code sys.exit() # Parent exists -- http://mail.python.org/mailman/listinfo/python-list
urllib.error.HTTPError: HTTP Error 403: Forbidden
>>> import urllib.request >>> response = >>> urllib.request.urlopen('http://en.wikipedia.org/wiki/Internet_media_type') Traceback (most recent call last): File "", line 1, in response = urllib.request.urlopen('http://en.wikipedia.org/wiki/Internet_media_type') File "C:\Python32\lib\urllib\request.py", line 138, in urlopen return opener.open(url, data, timeout) File "C:\Python32\lib\urllib\request.py", line 375, in open response = meth(req, response) File "C:\Python32\lib\urllib\request.py", line 487, in http_response 'http', request, response, code, msg, hdrs) File "C:\Python32\lib\urllib\request.py", line 413, in error return self._call_chain(*args) File "C:\Python32\lib\urllib\request.py", line 347, in _call_chain result = func(*args) File "C:\Python32\lib\urllib\request.py", line 495, in http_error_default raise HTTPError(req.full_url, code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 403: Forbidden why this url generate error ? -- http://mail.python.org/mailman/listinfo/python-list
Re: how to detect the character encoding in a web page ?
On Mon, Dec 24, 2012 at 11:34 AM, iMath wrote: > how to detect the character encoding in a web page ? > such as this page > > http://python.org/ You read part-way into the page, where you find this: That tells you that the character set is UTF-8. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: urllib.error.HTTPError: HTTP Error 403: Forbidden
On Sun, 23 Dec 2012 17:05:47 -0800, iMath wrote: import urllib.request response = urllib.request.urlopen('http://en.wikipedia.org/wiki/ Internet_media_type') > Traceback (most recent call last): > File "", line 1, in > response = > urllib.request.urlopen('http://en.wikipedia.org/wiki/ Internet_media_type') [...] > urllib.error.HTTPError: HTTP Error 403: Forbidden > > > why this url generate error ? Because you are in violation of Wikipedia's terms and services. Please do not try to screen-scrape Wikipedia. Instead, use their API for accessing pages. http://en.wikipedia.org/wiki/Wikipedia:Creating_a_bot -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: how to detect the character encoding in a web page ?
On 24/12/12 01:34:47, iMath wrote: > how to detect the character encoding in a web page ? That depends on the site: different sites indicate their encoding differently. > such as this page: http://python.org/ If you download that page and look at the HTML code, you'll find a line: So it's encoded as utf-8. Other sites declare their charset in the Content-Type HTTP header line. And then there are sites relying on the default. And sites that get it wrong, and send data in a different encoding from what they declare. Welcome to the real world, -- HansM -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing files in python
On 12/23/2012 12:19 PM, Kene Meniru wrote: Hello: I am writing a program that is made up of a collection of POV-Ray macros. POV-Ray is available at povray.org. It is a ray-tracing program that reads a scene description language (SDL) to create photo-realistic images. At this time my program (for modeling building information) is so huge that I am finding it difficult managing the macros and I am not even near completion. I am hoping to move this program to python and am wondering the best way to approach this. I would like to model my program after LaTeX. Basically the user writes a text file using certain key words and numbers and my python program reads this file, calls the classes that will then work together to calculate the information that is needed to create an accurate model. The result of this calculation will be an output to another text file in the appropriate format such as POV-Ray SDL, OpenSCAD script, etc. This file output can then be rendered by the corresponding program to produce the actual 3D model. The macros I have now currently does this but like I said it is getting tedious and most importantly the fun factor is losing its strength for me. I have been advised to check out python-ply and I have come across others. I have not really tried any yet and before I dive into any one of them I was wondering what else I should know. The following is a sample of what the text file that will be processed by this proposed system will contain. I appreciate any pointers and suggestions. Mine is "Don't do that." Seriously. What I understand is that you are proposing to design and write a parser for yet another Domain Specific Language -- that will require knowledge to use that is useless outside the specific domain. I expect that is will come to duplicate the basic facilities of existing languages. Users will want to be able to calculate, make conditional calculations and constructions, iterate*, and define functions (subroutines, macros). Why bother to reinvent all that? It often becomes a mess. (Or you will offer or people will want to mix Python with the dsl. That also can become a mess.) Instead, write a pypovray package incorporating the POV macros, that can be imported into a python program. Write a tutorial for the specific parts of Python that users will need. For instances, someone wants to place duplicate or parameterized models on a rectangular grid, along an arc, or even at random locations. possible user file content for parsing // in the following the python interface program reads //+ the contents of the file "other.file" as if its content //+ were located at this point. # this is a python comment. trivial difference from // include other.file import other.file # with Python's variations # or exec(open('other.file')) # but it is nearly always better to # keep the separate namespace. What if a name in other.file # is the same as used below? import pypovray as ppr //In the following the python interface makes "snap_size" a //+ global parameter > declare snap_size = 10 snap_size = 10 # the extra word is just noise // In the following "buildingLevel" is a class that is //+ called and passed the parameters in parenthesis. buildingLevel("FirstLevel", 3000) // In the following "snapOffset" is a class that is //+ called and passed the parameters in parenthesis. snapOffset("Closet-S1_r1", "Closet-S2_r3", <0,0,0>) Already legal Python # at the end of the file ppr.run(args) # Reads globals(), which python has nicely created for you, to create the master scene description and output whatever is needed for povray. It could be part of a template.py file you provide. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: [Help] [Newbie] Require help migrating from Perl to Python 2.7 (namespaces)
On 12/23/2012 4:32 AM, prilisa...@googlemail.com wrote: By the way, I think I have found the correct "wording". for my understood, the "handover" of objects to imported modules doesn't work because, e.g. trying to hand-over an SQLite connection into a imported module, can't work because the "attributes" are not transfered. I have not followed this thread, and do not know the context of your statement, or the code that did not work, but if you hand a Python object to an imported module, and something within the module can access the object, then all of its attributes are also accessible, the same as from the original module. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Forking into the background (Linux)
On 24/12/12 01:50:24, Olive wrote: > My goal is to write a script that 1) write something to stdout; then > fork into the background, closing the stdout (and stderr, stdin) pipe. > > I have found this answer (forking -> setsid -> forking) > http://stackoverflow.com/a/3356154 > > However the standard output of the child is still connected to the > terminal. I would like that if we execute a subprocess.checkprocess on > this program, only "I would like to see this" is captured and that the > program terminates when the parent exits. > > #! /usr/bin/python2 > import os,sys,time > > print "I would like to see this" > pid = os.fork() > if (pid == 0): # The first child. > # os.chdir("/") >os.setsid() ># os.umask(0) >pid2 = os.fork() >if (pid2 == 0): # Second child > print "I would like not see this" > time.sleep(5) >else: > sys.exit()#First child exists > else: # Parent Code > sys.exit() # Parent exists You could do this before forking: sys.stdin.close() sys.stdin = open('/dev/null', 'r') sys.stdout.close() sys.stdout = open('/dev/null', 'w') sys.stderr.close() sys.stderr = open('/dev/null', 'w') You may want to look at the python-daemon module on Pypy, which appears to do what you need, including some features you haven't asked for, yet. Hope this helps, -- HansM -- http://mail.python.org/mailman/listinfo/python-list
Password hash
I am writing a script that will send an email using an account I set up in gmail. It is an smtp server using tls on port 587, and I would like to use a password hash in the (python) script for login rather than plain text. Is this do-able? Details please. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to detect the character encoding in a web page ?
在 2012年12月24日星期一UTC+8上午8时34分47秒,iMath写道: > how to detect the character encoding in a web page ? > > such as this page > > > > http://python.org/ but how to let python do it for you ? such as this page http://python.org/ how to detect the character encoding in this web page by python ? -- http://mail.python.org/mailman/listinfo/python-list
Re: how to detect the character encoding in a web page ?
在 2012年12月24日星期一UTC+8上午8时34分47秒,iMath写道: > how to detect the character encoding in a web page ? > > such as this page > > > > http://python.org/ but how to let python do it for you ? such as these 2 pages http://python.org/ http://msdn.microsoft.com/en-us/library/bb802962(v=office.12).aspx how to detect the character encoding in these 2 pages by python ? -- http://mail.python.org/mailman/listinfo/python-list
Re: how to detect the character encoding in a web page ?
在 2012年12月24日星期一UTC+8上午8时34分47秒,iMath写道: > how to detect the character encoding in a web page ? > > such as this page > > > > http://python.org/ but how to let python do it for you ? such as these 2 pages http://python.org/ http://msdn.microsoft.com/en-us/library/bb802962(v=office.12).aspx how to detect the character encoding in these 2 pages by python ? -- http://mail.python.org/mailman/listinfo/python-list
?????? compile python 3.3 with bz2 support
Thanks for your reply.According to your advice, I tried again, but still failed. Here is how I do this time: 1. I did not find package "libbz2-dev" in my source, so I still install it from source 2. I carefully checked the output of "./confiruge" this time and find a warning : "configure: WARNING: unrecognized options: --with-bz2"?? so I used a wrong param? 3. I checked the build-in Python 2.4.3 which can successfully "import bz2"??and find a "bz2.so" in it's lib dir(/usr/lib/python2.4/lib-dynload/bz2.so)??I check the dependency of this file [root@localhost lib-dynload]# ldd /usr/lib/python2.4/lib-dynload/bz2.so linux-gate.so.1 => (0x002a) libbz2.so.1 => /usr/lib/libbz2.so.1 (0x00336000) libpthread.so.0 => /lib/libpthread.so.0 (0x00fa5000) libc.so.6 => /lib/libc.so.6 (0x00128000) /lib/ld-linux.so.2 (0x003e5000) it seems that the redhat has already installed the libbz2.so. But I failed to find such a file in my own compiled python 3.3 lib dir(/usr/local/lib/python3.3/lib-dynload/), strangely I see a file named "_bz2.cpython-33m_failed.so", the name indicated that it is not a right file. I renamed it to bz2.so and tried again, finally get a error: >>> import bz2 Traceback (most recent call last): File "", line 1, in ImportError: dynamic module does not define init function (PyInit_bz2) -- -- ??: "Benjamin Kaplan"; : 2012??12??23??(??) 0:06 ??: "Python List"; : Re: compile python 3.3 with bz2 support On Dec 21, 2012 1:31 AM, "Isml" <76069...@qq.com> wrote: > > hi, everyone: > I want to compile python 3.3 with bz2 support on RedHat 5.5 but fail to > do that. Here is how I do it: > 1. download bzip2 and compile it(make??make -f Makefile_libbz2_so??make > install) > 2.chang to python 3.3 source directory : ./configure > --with-bz2=/usr/local/include > 3. make > 4. make install > > after installation complete, I test it?? > [root@localhost Python-3.3.0]# python3 -c "import bz2" > Traceback (most recent call last): > File "", line 1, in > File "/usr/local/lib/python3.3/bz2.py", line 21, in > from _bz2 import BZ2Compressor, BZ2Decompressor > ImportError: No module named '_bz2' > By the way, RedHat 5.5 has a built-in python 2.4.3. Would it be a problem? > > > -- What is the output of configure? The last thing it does is list which modules are not going to be built. Is bz2 on the list? What does configure say when it's looking for bz2?-- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing files in python
On Mon, Dec 24, 2012 at 12:46 PM, Terry Reedy wrote: >> snapOffset("Closet-S1_r1", "Closet-S2_r3", <0,0,0>) > > > Already legal Python > Not quite. This is the one part that *doesn't* work directly. In POV-Ray, a vector eg is used to represent points, transformations, and sometimes colors. The closest Python equivalent is the tuple, but that requires that the brackets be changed: snapOffset("Closet-S1_r1", "Closet-S2_r3", (0,0,0)) It would also require some smart footwork at the export end, recognizing that a tuple needs to be output with angle brackets. But other than that, yes, Python's a good choice for this. (I find it amusing how I said "yeah, good idea to make a DSL, I wonder if you can capitalize on Python" and you said "don't make a DSL, maybe you can capitalize on Python" - opposite opening argument, same conclusion and recommendation.) ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: HTML - WEB FORM running PYTHON SCRIPT
I'll second this. Javascript is pretty comparable to Python in ease of learning, so that should be no obstacle. As for keeping the code from being accessible, you can put the javascript in a separate file that's called from the guest's web page, but that's far from a foolproof method. If you want the guest browser to do the calculation, there's no realistic way to keep the calculation code off of it. -- http://mail.python.org/mailman/listinfo/python-list
Re: [Help] [Newbie] Require help migrating from Perl to Python 2.7 (namespaces)
Hi there, On Sun, Dec 23, 2012 at 01:42:14PM -0800, prilisa...@googlemail.com wrote: > […] In the lower section you see, that the modules should execute > sqls. In case It could occur that two queries occur at the same > time. PS: IT IS NOT A QUESTION ABOUT SQL, etc. I do not understand, > how I could handle the part which is marked with Problemsection1 and > Problemsection2 I actually do not understand the problem you are stating. But, did you have a look at SQLAlchemy? If you are coping a lot with SQL it really makes your life much easier and they also provide the necessary mechanisms for threading. > import HomeLog # LogHandler Modules should be written all lower-case separated by underscores. > # Attach Loghandler > Loghandler = HomeLog.Logging() Have a look at the logging module and tutorial. I don't know what is in HomeLog.Logging, but this doesn't seem right. Variables defined at module level should be written all upper-case. > # Attach SocketServer > HomeSocketServer.HomeSocketServerStart() > > # Attach Scheduler > HomeSched = HomeScheduler.HomeScheduler() > […] > # This is a "Sample" that builds 2byte Cmd and transmits it on bus > PowerOnLamp1=Dali.send(0,0,1,80) You do all this on the module level? These things should go into functions with proper names or at least into a if __name__ == '__main__': pass > ### > HomeDaliServer.py > > def send (self,DaliAdress,RequestType,Request,RequestValue): > # Problemsection1: > # Here it's getting Interesting > # We're at the HomeDaliServer, and now I want to use QuerySqlite() > in the file HomeDatastore.py So, where's the problem? # make sure not to introduce cyclic dependence here! import home_data_store def send (connection,DaliAdress,RequestType,Request,RequestValue): results = home_data_store.query_sqlite(connection, …) return results > ### > HomeScheduler.py > # Problemsection2: > # If new workerthread is started, Informations must be queried using > QuerySlite() and also update data So, here's a first sketch (untested): def query(): data = do_something() return data def update(data): do_something_with(data) > HomeDatastore.py > def QuerySqlite(): > #doing something here.. > # returning Data Have you read the Python tutorial by the way? Regards, Thomas. -- http://mail.python.org/mailman/listinfo/python-list
Re: [Help] [Newbie] Require help migrating from Perl to Python 2.7 (namespaces)
On 12/23/2012 04:42 PM, prilisa...@googlemail.com wrote: > Okay, I try to publish this sample, and yes it's not a working piece of code, > but I try to "draw" my problem that way. As you will see, I load modules, > create cursor,... in the main.py. In the lower section you see, that the > modules should execute sqls. In case It could occur that two queries occur at > the same time. PS: IT IS NOT A QUESTION ABOUT SQL, etc. I do not understand, > how I could handle the part which is marked with Problemsection1 and > Problemsection2 You're miles from being ready to worry about "the same time." Don't start threading till you can get a simple multi-module program understood. > I hope really found the right "wording". thank to all your help. > > > main.py For some reason you capitalize all those filenames, so you're stuck with unpythonic module names. If you want your code readable, use lowercase for module name, and Capitalized for class name. > import HomeLog # LogHandler > import HomeSocketServer # Threaded TCP Socket Server > import HomeDatastore # SQLite DB > import HomeDaliServer # Connects to USB Device > import HomeScheduler # Advanced scheduler functions > > > # Attach Loghandler > Loghandler = HomeLog.Logging() > # Attach SocketServer > HomeSocketServer.HomeSocketServerStart() > > # Attach Scheduler > HomeSched = HomeScheduler.HomeScheduler() > HomeSched.SchedulerStart() > HomeSched.SchedulerJobs() > > # Attach Datastore > Datastore=HomeDatastore.HomeDBStore() > Datastore=Datastore.Startup() > > #Attach Dali Driver > Dali=HomeDaliServer.Startup() > # This is a "Sample" that builds 2byte Cmd and transmits it on bus > PowerOnLamp1=Dali.send(0,0,1,80) > > ### > HomeDaliServer.py import HomeDatastore > > def send (self,DaliAdress,RequestType,Request,RequestValue): Nobody's going to be able to understand your code if you persist in using self in unpythonic ways. It's used as the first argument of a class method. Period. > # Problemsection1: > # Here it's getting Interesting > # We're at the HomeDaliServer, and now I want to use QuerySqlite() in the > file HomeDatastore.py So call it: firstarg = whatever * RequestType secondarg = something different + RequestValue result = HomeDatastore.QuerySqlite(firstarg, secondarg) > ### > HomeScheduler.py Where are your import statements? No module automatically sees imports that were done elsewhere. Import what you need in a module. > # Problemsection2: > # If new workerthread is started, Informations must be queried using > QuerySlite() and also update data I don't see any 'update data' function anywhere, but if you want to call QuerySqlite, you need to call it: thisresult = HomeDatastore.QuerySqlite(him, her, theother) > > ### > HomeDatastore.py > def QuerySqlite(): You presumably mean def QuerySqlite(firstparam, secondparam): since a function with no arguments is going to be stuck trying to use globals, and that's not a good habit to get into. > #doing something here.. #doing something with those parameters, and only those parameters > # returning Data > > ### > -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
?????? compile python 3.3 with bz2 support
Finally I worked it out. I write it down Here to people who meet the same problem like me. 1. Install bzip2 from source is OK 2. There is no need to add "--with-bz2" to "./configure", because it is not a valid param. python makefile will search the bz2 itself, if it find the bz2 lib, it will automatically compile this module. see setup.py line 1373. So the "./configure" outputs the warning : "configure: WARNING: unrecognized options: --with-bz2" 3. The reason why I failed before is that I did not correctly compile the bz2.so, the filename "_bz2.cpython-33m_failed.so" has indicated that fact. And the reason why I faild to compile bz2.so is strangely the RedHat "SELinux". So the only thing I then do is disable it (setenforce 0), after that, everything is OK. Thanks for everyone. -- -- ??: "Isml"<76069...@qq.com>; : 2012??12??24??(??) 11:21 ??: "Benjamin Kaplan"; "Python List"; : ?? compile python 3.3 with bz2 support Thanks for your reply.According to your advice, I tried again, but still failed. Here is how I do this time: 1. I did not find package "libbz2-dev" in my source, so I still install it from source 2. I carefully checked the output of "./confiruge" this time and find a warning : "configure: WARNING: unrecognized options: --with-bz2"?? so I used a wrong param? 3. I checked the build-in Python 2.4.3 which can successfully "import bz2"??and find a "bz2.so" in it's lib dir(/usr/lib/python2.4/lib-dynload/bz2.so)??I check the dependency of this file [root@localhost lib-dynload]# ldd /usr/lib/python2.4/lib-dynload/bz2.so linux-gate.so.1 => (0x002a) libbz2.so.1 => /usr/lib/libbz2.so.1 (0x00336000) libpthread.so.0 => /lib/libpthread.so.0 (0x00fa5000) libc.so.6 => /lib/libc.so.6 (0x00128000) /lib/ld-linux.so.2 (0x003e5000) it seems that the redhat has already installed the libbz2.so. But I failed to find such a file in my own compiled python 3.3 lib dir(/usr/local/lib/python3.3/lib-dynload/), strangely I see a file named "_bz2.cpython-33m_failed.so", the name indicated that it is not a right file. I renamed it to bz2.so and tried again, finally get a error: >>> import bz2 Traceback (most recent call last): File "", line 1, in ImportError: dynamic module does not define init function (PyInit_bz2) -- -- ??: "Benjamin Kaplan"; : 2012??12??23??(??) 0:06 ??: "Python List"; : Re: compile python 3.3 with bz2 support On Dec 21, 2012 1:31 AM, "Isml" <76069...@qq.com> wrote: > > hi, everyone: > I want to compile python 3.3 with bz2 support on RedHat 5.5 but fail to > do that. Here is how I do it: > 1. download bzip2 and compile it(make??make -f Makefile_libbz2_so??make > install) > 2.chang to python 3.3 source directory : ./configure > --with-bz2=/usr/local/include > 3. make > 4. make install > > after installation complete, I test it?? > [root@localhost Python-3.3.0]# python3 -c "import bz2" > Traceback (most recent call last): > File "", line 1, in > File "/usr/local/lib/python3.3/bz2.py", line 21, in > from _bz2 import BZ2Compressor, BZ2Decompressor > ImportError: No module named '_bz2' > By the way, RedHat 5.5 has a built-in python 2.4.3. Would it be a problem? > > > -- What is the output of configure? The last thing it does is list which modules are not going to be built. Is bz2 on the list? What does configure say when it's looking for bz2?-- http://mail.python.org/mailman/listinfo/python-list
Making a Unix daemon process (was: Forking into the background (Linux))
Hans Mulder writes: > On 24/12/12 01:50:24, Olive wrote: > > My goal is to write a script that 1) write something to stdout; then > > fork into the background, closing the stdout (and stderr, stdin) pipe. > > > > I have found this answer (forking -> setsid -> forking) > > http://stackoverflow.com/a/3356154 You're following a path that leads to the desire for a “daemon” http://stackoverflow.com/questions/473620/how-do-you-create-a-daemon-in-python/688448#688448>. > You may want to look at the python-daemon module on Pypy, which > appears to do what you need, including some features you haven't asked > for, yet. It's even better when you look at it on PyPI http://pypi.python.org/pypi/python-daemon/> (note that PyPy is a Python implementation, PyPI is an index of Python packages). The discussion forum for ‘python-daemon’ development is at http://lists.alioth.debian.org/mailman/listinfo/python-daemon-devel>. -- \ “Faith may be defined briefly as an illogical belief in the | `\ occurrence of the improbable.” —Henry L. Mencken | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list