Re: What's the difference between built-in func getattr() and normal call of a func of a class
Diez B. Roggisch wrote: > No, it will only return _always_ a value if you provide a default one. > If not, they have the exact same semantics. > > What you've got here is something usually called "syntactic sugaring" - > a specialized syntax that performs certain instructions that _could_ be > done by hand - but the concise syntax is (supposedly, and certainly in > this case) easier to read/write/understand. > > There are others - e.g. list comprehensions or a < b < c. > > Regards, > > Diez Cool~ Thanks for showing me the "syntactic sugaring":) -- http://mail.python.org/mailman/listinfo/python-list
What's the difference between built-in func getattr() and normal call of a func of a class
Hi, I wonder what is the difference between the built-in function getattr() and the normal call of a function of a class. Here is the details: getattr( object, name[, default]) Return the value of the named attributed of object. name must be a string. If the string is the name of one of the object's attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised. Is that to say the only difference between the two is that no matter the specific function exists or not the built-in func will always return a value, but "class.function" will not? -- http://mail.python.org/mailman/listinfo/python-list
Default location while open an Excel file
Hi, As you know, I can use this to open an Excel file: """ import win32com.client doc = win32com.client.Dispatch("Excel.Application") doc.Workbooks.Open(excelFile, ReadOnly=True) """ But the problem is when I only pass the filename to the Open() method, and of course the file is in the current directory, it will throw an exception that the specified file can't be found. When I use os.path.abspath(excelFile) instead, it works. But I do know that somebody can only pass a filename, and no exception is raised. Now I wonder is that because the "somebody" happen to put the file on the default location of the Open() method? If so, does any one know the default location? Thanks for your consideration. Regards, Johnny -- http://mail.python.org/mailman/listinfo/python-list
Re: Default location while open an Excel file
On Oct 20, 11:24 am, Gabriel Genellina <[EMAIL PROTECTED]> wrote: > At Friday 20/10/2006 00:08, Johnny wrote: > > >doc.Workbooks.Open(excelFile, ReadOnly=True) > > >But the problem is when I only pass the filename to the Open() > >method, and of course the file is in the current directory, it will > >throw an exception that the specified file can't be found. When I use > >os.path.abspath(excelFile) instead, it works. But I do know that > >somebody can only pass a filename, and no exception is raised. Now I > >wonder is that because the "somebody" happen to put the file on the > >default location of the Open() method? If so, does any one know the > >default location?Why don't you want to use an absolute path? It's safe, will > >always > work... What if Excel, for whatever reason, decides to start the Open > dialog pointing to another location? What if your script does not > have permission to write on such location? Yes, I agree and willing to use abstract path. I only wonder what's happending inside this method so that I can get more understanding of the problem caused by passing an relative path in. :) Regards, Johnny -- http://mail.python.org/mailman/listinfo/python-list
Multiple FTP download using Muliti thread
I have taken a look at the code that dose one download at time, in multi threaded manner: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/465531 What I wanted to do is, make it download multiple files at the same time. I am new to python and have gone over "Dive In To Python" yesterday. Can some give a idea what I need to do. Once I understand the big picture, then I can piece together. -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiple FTP download using Muliti thread
Where or What folder does the ftp files get downloaded to? Justin Ezequiel wrote: > import ftplib, posixpath, threading > from TaskQueue import TaskQueue > > def worker(tq): > while True: > host, e = tq.get() > > c = ftplib.FTP(host) > c.connect() > try: > c.login() > p = posixpath.basename(e) > fp = open(p, 'wb') > try: c.retrbinary('RETR %s' % e, fp.write) > finally: fp.close() > finally: c.close() > > tq.task_done() > > if __name__ == '__main__': > q = TaskQueue() > host = 'ftp.microsoft.com' > > c = ftplib.FTP(host) > c.connect() > try: > c.login() > folder = '/deskapps/kids/' > for n in c.nlst(folder): > if n.lower().endswith('.exe'): > q.put((host, n)) > finally: c.close() > > numworkers = 4 > for i in range(numworkers): > t = threading.Thread(target=worker, args=(q,)) > t.setDaemon(True) > t.start() > > q.join() > print 'Done.' -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiple FTP download using Muliti thread
When I run the following script, with host and password and username changed, I get the following errors: raise error_temp, resp error_temp: 421 Unable to set up secure anonymous FTP Dose the host should allow 4 simultaneous login at a time? Justin Ezequiel wrote: > import ftplib, posixpath, threading > from TaskQueue import TaskQueue > > def worker(tq): > while True: > host, e = tq.get() > > c = ftplib.FTP(host) > c.connect() > try: > c.login() > p = posixpath.basename(e) > fp = open(p, 'wb') > try: c.retrbinary('RETR %s' % e, fp.write) > finally: fp.close() > finally: c.close() > > tq.task_done() > > if __name__ == '__main__': > q = TaskQueue() > host = 'ftp.microsoft.com' > > c = ftplib.FTP(host) > c.connect() > try: > c.login() > folder = '/deskapps/kids/' > for n in c.nlst(folder): > if n.lower().endswith('.exe'): > q.put((host, n)) > finally: c.close() > > numworkers = 4 > for i in range(numworkers): > t = threading.Thread(target=worker, args=(q,)) > t.setDaemon(True) > t.start() > > q.join() > print 'Done.' -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiple FTP download using Muliti thread
It works using ftp.microsoft.com. But where does it put the downloaded files? can I specify a download folder location? Justin Ezequiel wrote: > johnny wrote: > > When I run the following script, with host and password and username > > changed, I get the following errors: > > raise error_temp, resp > > error_temp: 421 Unable to set up secure anonymous FTP > > > > Dose the host should allow 4 simultaneous login at a time? > > > > does it work using ftp.microsoft.com? > > post your code -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiple FTP download using Muliti thread
It places the ftp downloaded contents on the same folder as the this ftp python script. How do I set a diffrent download folder location? johnny wrote: > It works using ftp.microsoft.com. But where does it put the downloaded > files? can I specify a download folder location? > > Justin Ezequiel wrote: > > johnny wrote: > > > When I run the following script, with host and password and username > > > changed, I get the following errors: > > > raise error_temp, resp > > > error_temp: 421 Unable to set up secure anonymous FTP > > > > > > Dose the host should allow 4 simultaneous login at a time? > > > > > > > does it work using ftp.microsoft.com? > > > > post your code -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiple FTP download using Muliti thread
I am getting the following error: raise error_temp, resp error_temp: 421 Unable to set up secure anonymous FTP Here is the code: import ftplib, posixpath, threading from TaskQueue import TaskQueue def worker(tq): while True: host, e = tq.get() c = ftplib.FTP(host) c.connect() try: c.login() p = posixpath.basename(e) fp = open('H:/eclipse/workspace/src/ftp_download/' + p, 'wb') try: c.retrbinary('RETR %s' % e, fp.write) finally: fp.close() finally: c.close() tq.task_done() if __name__ == '__main__': q = TaskQueue() #host = 'ftp.microsoft.com' host = 'mysite.com' c = ftplib.FTP(host) c.connect() try: #c.login() c.login("[EMAIL PROTECTED]","temppass" ) #folder = '/deskapps/kids/' folder = '' for n in c.nlst(folder): #if n.lower().endswith('.exe'): #q.put((host, n)) if n.lower().endswith('.jpg'): q.put((host, n)) elif n.lower().endswith('.jpeg'): q.put((host, n)) finally: c.close() numworkers = 4 for i in range(numworkers): t = threading.Thread(target=worker, args=(q,)) t.setDaemon(True) t.start() q.join() print 'Done.' Justin Ezequiel wrote: > johnny wrote: > > When I run the following script, with host and password and username > > changed, I get the following errors: > > raise error_temp, resp > > error_temp: 421 Unable to set up secure anonymous FTP > > > > Dose the host should allow 4 simultaneous login at a time? > > > > does it work using ftp.microsoft.com? > > post your code -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiple FTP download using Muliti thread
Ok I fixed it. Needed to put in username, and password in the c.login inside while True loop. while True: host, e = tq.get() c = ftplib.FTP(host) c.connect() try: c.login() p = posixpath.basename(e) fp = open('H:/eclipse/workspace/src/ftp_download/' + p, 'wb') johnny wrote: > I am getting the following error: > > raise error_temp, resp > error_temp: 421 Unable to set up secure anonymous FTP > > Here is the code: > > import ftplib, posixpath, threading > from TaskQueue import TaskQueue > > def worker(tq): > while True: > host, e = tq.get() > > c = ftplib.FTP(host) > c.connect() > try: > c.login() > p = posixpath.basename(e) > fp = open('H:/eclipse/workspace/src/ftp_download/' + p, > 'wb') > try: c.retrbinary('RETR %s' % e, fp.write) > finally: fp.close() > finally: c.close() > > tq.task_done() > > if __name__ == '__main__': > q = TaskQueue() > #host = 'ftp.microsoft.com' > host = 'mysite.com' > c = ftplib.FTP(host) > c.connect() > try: > #c.login() > c.login("[EMAIL PROTECTED]","temppass" ) > > #folder = '/deskapps/kids/' > folder = '' > for n in c.nlst(folder): > #if n.lower().endswith('.exe'): > #q.put((host, n)) > if n.lower().endswith('.jpg'): > q.put((host, n)) > elif n.lower().endswith('.jpeg'): > q.put((host, n)) > > finally: c.close() > > numworkers = 4 > for i in range(numworkers): > t = threading.Thread(target=worker, args=(q,)) > t.setDaemon(True) > t.start() > > q.join() > print 'Done.' > > > Justin Ezequiel wrote: > > johnny wrote: > > > When I run the following script, with host and password and username > > > changed, I get the following errors: > > > raise error_temp, resp > > > error_temp: 421 Unable to set up secure anonymous FTP > > > > > > Dose the host should allow 4 simultaneous login at a time? > > > > > > > does it work using ftp.microsoft.com? > > > > post your code -- http://mail.python.org/mailman/listinfo/python-list
newb: Join two string variables
How do I join two string variables? I want to do: download_dir + filename. download_dir=r'c:/download/' filename =r'log.txt' I want to get something like this: c:/download/log.txt -- http://mail.python.org/mailman/listinfo/python-list
Re: newb: Join two string variables
In my code, I have the following: p = posixpath.basename(e).strip filename = download_dir+p I am getting the following error: filename = download_dir+p TypeError: cannot concatenate 'str' and 'builtin_function_or_method' objects Cameron Walsh wrote: > johnny wrote: > > How do I join two string variables? > > I want to do: download_dir + filename. > > download_dir=r'c:/download/' > > filename =r'log.txt' > > > > I want to get something like this: > > c:/download/log.txt > > > > Hi Johnny, > > This is actually two questions: > > 1.) How do I concatenate strings > 2.) How do I concatenate pathnames? > > Answers: > > 1.) > > >>> download_dir="C:/download/" > >>> filename="log.txt" > >>> path_to_file=download_dir+filename > >>> path_to_file > 'C:/download/log.txt' > > 2.) > > >>> import os > >>> filename='log.txt' > >>> path_to_file = os.path.join("C:/download",filename) > >>> path_to_file > 'C:/download/log.txt' > > > Help on function join in module posixpath: > > join(a, *p) > Join two or more pathname components, inserting '/' as needed > > > > Hope it helps, > > Cameron. -- http://mail.python.org/mailman/listinfo/python-list
PHP calls python: process vs threads
What I want to do is the following: Web user uploads a word doc, and I need it to move the uploaded word doc, on to another machine and conver it to pdf. Then update the database and allow immediate pdf download. I am thinking of using ftp from machine 1 -> machine 2, then convert doc to pdf on machine 2, using process or thread. What is the best way to go about doing this, process or threads or pyro? Pdf is created by calling commands on the command line, through python script. Thank you in advance. John -- http://mail.python.org/mailman/listinfo/python-list
newb: Can I use PYRO
What I want to do is the following: Web user uploads a word doc (web app written in php), and I need it to move the uploaded word doc, on to another machine and conver it to pdf. Then update the database and allow immediate pdf download. I am thinking of using ftp from machine 1 -> machine 2, then convert doc to pdf on machine 2, using process or thread. What is the best way to go about doing this, process or threads or pyro? Pdf is created by calling commands on the command line, through python script. Thank you in advance. John -- http://mail.python.org/mailman/listinfo/python-list
newb: How to call one modue from other
I have a module called ftp and I have another module called processKick. What I need is to have processKick, create fork and execute ftp like below. Relevant processKick code as follows: def do_child_stuff(): ftp def fork_test(): pid = os.fork() if pid == 0: # child do_child_stuff() os._exit(0) # parent - wait for child to finish os.waitpid(pid, os.P_WAIT) Can someone also tell me what is the purpose of if __name__ == "__main__": Do I have to call, main of ftp module within processKick? Thank you in advance -- http://mail.python.org/mailman/listinfo/python-list
Re: newb: How to call one modue from other
johnny wrote: > I have a module called ftp and I have another module called > processKick. What I need is to have processKick, create fork and > execute ftp like below. > > Relevant processKick code as follows: > > def do_child_stuff(): > ftp > > def fork_test(): > pid = os.fork() > if pid == 0: > # child > do_child_stuff() > os._exit(0) > # parent - wait for child to finish > os.waitpid(pid, os.P_WAIT) > Here is my ftp module: import ftplib, posixpath, threading from TaskQueue import TaskQueue def worker(tq): while True: host, e = tq.get() c = ftplib.FTP(host) c.connect() try: c.login() p = posixpath.basename(e) fp = open('H:/ftp_download/' + p, 'wb') try: c.retrbinary('RETR %s' % e, fp.write) finally: fp.close() finally: c.close() tq.task_done() if __name__ == '__main__': q = TaskQueue() #host = 'ftp.microsoft.com' host = 'mysite.com' c = ftplib.FTP(host) c.connect() try: #c.login() c.login() #folder = '/deskapps/kids/' folder = '' for n in c.nlst(folder): if n.lower().endswith('.doc'): q.put((host, n)) finally: c.close() numworkers = 4 for i in range(numworkers): t = threading.Thread(target=worker, args=(q,)) t.setDaemon(True) t.start() q.join() print 'Done.' Can someone also tell me what is the purpose of if __name__ == "__main__": Do I have to call, main of ftp module within processKick? Thank you in advance -- http://mail.python.org/mailman/listinfo/python-list
newb: What is the purpose of if __name__ == "__main__":
What is the purpose of if __name__ == "__main__": If you have a module, does it get called automatically? -- http://mail.python.org/mailman/listinfo/python-list
Re: newb: How to call one modue from other
Gabriel Genellina wrote: > Reading the Python Tutorial helps a lot. > I did read "Dive Into Python", one week ago. It's a good book, but it didn't cover this kind of situation. -- http://mail.python.org/mailman/listinfo/python-list
Multithreaded python script calls the COMMAND LINE
I have python script does ftp download in a multi threaded way. Each thread downloads a file, close the file, calls the comman line to convert the .doc to pdf. Command line should go ahead and convert the file. My question is, when each thread calls the command line, does one command line process all the request, or each thread creates a one command line process for themselves and executes the command? For some reason I am getting "File '1' is alread exists, Do you want to overwrite [y/n]?" I have to manually enter 'y' or 'n' for the python script to complete. -- http://mail.python.org/mailman/listinfo/python-list
Re: Multithreaded python script calls the COMMAND LINE
[EMAIL PROTECTED] wrote: > > That depends on how you invoke it: os.system creates a new shell which > in turn creates a new process; the spawn* functions do that directly. I am using os.system. Here is my code import ftplib, posixpath, threading from TaskQueue import TaskQueue def worker(tq): while True: host, e = tq.get() c = ftplib.FTP(host) c.connect() try: c.login() p = posixpath.basename(e) ps_dir = r'H:/ftp_download/' filename = download_dir+p fp = open(filename, 'wb') try: c.retrbinary('RETR %s' % e, fp.write) finally: fp.close() finally: c.close() if (p.lower().endswith('.ps') ): partFileName = p.split('.', 1) movedFile = download_dir + p #movedFile = p finalFile = ps_dir + partFileName[0]+'.pdf' encode_cmd = r'ps2pdf '+ movedFile + ' '+ finalFile os.system(encode_cmd) tq.task_done() if __name__ == '__main__': main() def main(): q = TaskQueue() #host = 'ftp.microsoft.com' host = 'mysite.com' c = ftplib.FTP(host) c.connect() try: #c.login() c.login() #folder = '/deskapps/kids/' folder = '' for n in c.nlst(folder): if n.lower().endswith('.ps'): q.put((host, n)) finally: c.close() numworkers = 4 for i in range(numworkers): t = threading.Thread(target=worker, args=(q,)) t.setDaemon(True) t.start() q.join() print 'Done.' > Anyway, if you have many conversion processes running, you should pass > them unique file names to avoid conflicts. > Where does the '1' name come from? If it's you, don't use a fixed name > - the tempfile module may be useful. I am giving unique name to the converted file with .pdf. I think something up with the thread. I am new to python, I am not sure what's wrong. -- http://mail.python.org/mailman/listinfo/python-list
mySql and multiple connection for threads
How do you create multiple connection in the treads. Lets say I will have at most 5 threads and I want to create at most 5 connections. If I create a connection in the "worker method", does it create connection for each threads. def worker(tq): while True: host, e = tq.get() c = ftplib.FTP(host) c.connect() try: c.login() p = os.path.basename(e) download_dir = r'H:/ftp_download/' ps_dir = r'H:/ftp_download/' filename = download_dir+p fp = open(filename, 'wb') try: c.retrbinary('RETR %s' % e, fp.write) finally: fp.close() finally: c.close() if (p.lower().endswith('.ps') ): partFileName = p.split('.', 1) movedFile = download_dir + p #movedFile = p finalFile = ps_dir + partFileName[0]+'.pdf' encode_cmd = r'ps2pdf '+ movedFile + ' '+ finalFile os.system(encode_cmd) conn = adodb.NewADOConnection('mysql') conn.Connect('localhost', 'temp', 'temp', 'temp') sql = r"update file where file_path='"+p+"' set pdf_file_path='" +finalFile+"'" cursor = conn.Execute(sql) rows = cursor.Affected_Rows() tq.task_done() -- http://mail.python.org/mailman/listinfo/python-list
ERROR CLOSING CONNECTION: mysql connection close
I am getting following connection error from my python script: conn.close() AttributeError: adodb_mysql instance has no attribute 'close' Here is my relevant code below: def worker(tq): while True: host, e = tq.get() c = ftplib.FTP(host) c.connect() try: c.login() p = os.path.basename(e) download_dir = r'H:/ftp_download/' ps_dir = r'H:/ftp_download/' filename = download_dir+p fp = open(filename, 'wb') try: c.retrbinary('RETR %s' % e, fp.write) finally: fp.close() finally: c.close() if (p.lower().endswith('.ps') ): partFileName = p.split('.', 1) movedFile = download_dir + p #movedFile = p finalFile = ps_dir + partFileName[0]+'.pdf' encode_cmd = r'ps2pdf '+ movedFile + ' '+ finalFile os.system(encode_cmd) conn = adodb.NewADOConnection('mysql') conn.Connect('localhost', 'temp', 'temp', 'temp') sql = r"update video set pdf_file_path='" +finalFile+r"' where file_path='"+p+r"'" cursor = conn.Execute(sql) rows = cursor.Affected_Rows() cursor = conn.Execute(sql) rows = cursor.Affected_Rows() cursor.close() conn.close() tq.task_done() -- http://mail.python.org/mailman/listinfo/python-list
ATTRIBUTE ERROR: 'module' object has no attribute 'ssl'
I am getting the following errors: File "H:\xampp\xampp\xampp\python\lib\httplib.py", line 679, in _send_output self.send(msg) File "H:\xampp\xampp\xampp\python\lib\httplib.py", line 646, in send self.connect() File "H:\xampp\xampp\xampp\python\lib\httplib.py", line 1073, in connect ssl = socket.ssl(sock, self.key_file, self.cert_file) AttributeError: 'module' object has no attribute 'ssl' Thank You in Advance -- http://mail.python.org/mailman/listinfo/python-list
newb: logging.getLogger('') and logging.getLogger("something")
For getLogger, can you pass anything in there and it will return a object? Would that returned object, be your root logger? Thanks, -- http://mail.python.org/mailman/listinfo/python-list
newb: SENDING os.system(encode_cmd) output to a logging file
How do I pipe the output, generated from os.system(some_command), to the logging file? -- http://mail.python.org/mailman/listinfo/python-list
newb: Creating Exception
I want to print individual exception for database connection, sql execution, database closing, closing the cursor. Can I do it with one try..catch or I need a nested try...catch? conn = adodb.NewADOConnection('mysql') conn.Connect('localhost', 'temp', 'temp', 'temp') sql = r"update file set pdf_file_path='" +finalFile+r"' where file_path='"+p+r"'" cursor = conn.Execute(sql) rows = cursor.Affected_Rows() cursor.close() conn.close() Thank you for your FOUNTAIN OF WISDOM... -- http://mail.python.org/mailman/listinfo/python-list
AttributeError: Logger instance has no attribute 'setFormatter'
I am getting a log error. I am running ActiveState Python 2.4.3. Any help greatly appreciated. Here is my code: file.py - def main() setupLogging() blah def setupLogging(): global log log = logging.getLogger("ftp") formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s') log.setFormatter(formatter) log.setLevel(logging.DEBUG) fhnd = logging.FileHandler('py_mybase.log') fhnd.setLevel(logging.DEBUG) log.addHandler(fhnd) My Error: log.setFormatter(formatter) AttributeError: Logger instance has no attribute 'setFormatter' -- http://mail.python.org/mailman/listinfo/python-list
Re: newb: SENDING os.system(encode_cmd) output to a logging file
I am doing the os.system(encode_cmd) within a thread. So you are saying, have each thread create a subprocess module. Did you mean, "Popen" (os.popen)? Like os.popen(encode_cmd) , not os.system(encode_cmd)? Gabriel Genellina wrote: > At Monday 11/12/2006 20:47, johnny wrote: > > >How do I pipe the output, generated from os.system(some_command), to > >the logging file? > > Use the subprocess module to run the command instead. > > > -- > Gabriel Genellina > Softlab SRL > > __ > Correo Yahoo! > Espacio para todos tus mensajes, antivirus y antispam ¡gratis! > ¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar -- http://mail.python.org/mailman/listinfo/python-list
Re: newb: Creating Exception
Thank you Dennis, So when line 2, gets executed, its exception goes to do_some1_error. And when line 3, gets executed, its exception goes to do_some2_error and so on. line 1: try line 2:do_some1 line 3:do_some2 line 4:do_some3 line 5: except do_some1_error: line 6:whatever1 line 7: except do_some2_error: line 8:whatever2 line 9: except do_some3_error: line 10:whatever3 Documentation is not written for newbs, it's written by guys with 6yrs of experience FOR guys with 6yrs of experience. Dennis Lee Bieber wrote: > On 11 Dec 2006 16:02:02 -0800, "johnny" <[EMAIL PROTECTED]> declaimed > the following in gmane.comp.python.general: > > > I want to print individual exception for database connection, sql > > execution, database closing, closing the cursor. Can I do it with one > > try..catch or I need a nested try...catch? > > Python does not have a "catch" instruction. > > You could do: > > try: > make connection #though that should, in my mind, be done > #as part of the > initialization of the thread > #and not as part of any > processing loop > make cursor > execute sql > fetch results if any > close cursor > commit transaction > close connection#which I'd make part of the termination > #of the thread > except Exception1, msg: > do something > except Exception2, msg: > do something2 > ... > > IF each step raises a different exception type -- if all the database > returns is "DatabaseError", then there is nothing to separate them by. > Also note that if an exception happens in the "execute sql" stage, your > handler may need to do a rollback, and the closes. > > -- > WulfraedDennis Lee Bieber KD6MOG > [EMAIL PROTECTED] [EMAIL PROTECTED] > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: [EMAIL PROTECTED]) > HTTP://www.bestiaria.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: newb: Creating Exception
I checked out couple of books from Library, one that I like called "Foundation of Python Network Programming", this is what I needed, code with understandable explantion. ;) Thread pooling and many others. Thanks all of you for the help. Dustan wrote: > Dennis Lee Bieber wrote: > > On 13 Dec 2006 03:52:49 -0800, "Dustan" <[EMAIL PROTECTED]> > > declaimed the following in gmane.comp.python.general: > > > > > > > > I didn't complete my thought. If you run into a situation like this, > > > then you might want to look to the python documentation on the web for > > > help; think of the web documentation as a reference manual rather than > > > a tutorial, even though it does provide a tutorial. > > > > I believe it was stated that the installation was using the > > ActiveState build. The documentation is supplied in Windows CHM format, > > which is likely much faster to search/read locally than loading a chain > > of web pages. > > I couldn't think of a better word to describe the 'official' > documentation. > > > Including, last time I checked, an electronic copy of "Dive into > > Python" -- http://mail.python.org/mailman/listinfo/python-list
WHAT is [0] in subprocess.Popen(blah).communicate()[0]
Can someone tell me what is the reason "[0]" appears after ".communicate()" For example: last_line=subprocess.Popen([r"tail","-n 1", "x.txt"], stdout=subprocess.PIPE).communicate()[0] Thank you. -- http://mail.python.org/mailman/listinfo/python-list
newb: Scope Question
Scope of ids: When I print "ids", it's always empty string '', as I have intialized before. That's not what I want. I want the ids to have str(r['id']).join(',') if res: ids = '' for r in res['key']: ids = str(r['id']).join(',') print("ids: %s" %(ids)) -- http://mail.python.org/mailman/listinfo/python-list
How to Machine A python script execute Machine B python script?
Anyone know how I can make Machine A python script execute a python script on Machine B ? -- http://mail.python.org/mailman/listinfo/python-list
Any Good tools to create CSV Files?
Any Good tools to create CSV Files? ReportLab only creates pdf files. I need something to create CSV files. Thank you. -- http://mail.python.org/mailman/listinfo/python-list
How to make Python poll a PYTHON METHOD
Is there a way to call a function on a specified interval(seconds, milliseconds) every time, like polling user defined method? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
newb: Python Module and Class Scope
Can a class inside a module, access a method, outside of class, but inside of the module? Eg. Can instance of class a access main, if so how? What is the scope of "def main()" interms of class A? myModule: class A: main() def main(): thnx. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to make Python poll a PYTHON METHOD
Is it possible to call threads inside another thread (nested threads)? The example above creates a thread to call a function "eat" every time based on a specified interval. Now for example, if I make the called function "eat" to spawn threads to do the work in a queue and when all jobs are done, spawned threads join. When the next interval is up this process repeat itself. Thanks. On May 7, 11:19 pm, Nick Vatamaniuc <[EMAIL PROTECTED]> wrote: > On May 7, 10:42 pm, Nick Vatamaniuc <[EMAIL PROTECTED]> wrote: > > > > > On May 7, 10:07 pm, johnny <[EMAIL PROTECTED]> wrote: > > > > Is there a way to call a function on a specified interval(seconds, > > > milliseconds) every time, like polling user defined method? > > > > Thanks. > > > Sure, > > > >>> def baz(): > > >...: print "Baz!" > >...: > > > >>> from threading import Timer > > >>> timer=Timer(5.0,baz) > > >>> timer.start() > > >>> Baz! > > > Cheers, > > -Nick Vatamaniuc > > By the way, here is another way to do it. This way it will repeat, the > other one executed once. Of course, if it executed once, you can make > it do it again, but there is some trickery involved. Here is a way to > do it using threads. > > Hope it helps, > -Nick Vatamaniuc > > from threading import Thread > from time import sleep > > class Repeater(Thread): > def __init__(self,interval,fun,*args,**kw): > Thread.__init__(self) > self.interval=interval > self.fun=fun > self.args=args > self.kw=kw > self.keep_going=True > > def run(self): >while(self.keep_going): > sleep(self.interval) > self.fun(*self.args,**self.kw) > > def stop_repeating(self): > self.keep_going=False > > def eat(*a): > print "eating: " , ','.join([stuff for stuff in a]) > > r=Repeater(1.0, eat, 'eggs','spam','kelp') > r.start() > sleep(6.0) > r.stop_repeating() -- http://mail.python.org/mailman/listinfo/python-list
Simple Python REGEX Question
I need to get the content inside the bracket. eg. some characters before bracket (3.12345). I need to get whatever inside the (), in this case 3.12345. How do you do this with python regular expression? -- http://mail.python.org/mailman/listinfo/python-list
Any python module for Traversing HTML files
Any python module for navigating and selecting, parsing HTML files? -- http://mail.python.org/mailman/listinfo/python-list
noob: reloading modified python file within Python Shell
from people.models import * Now I make changes to the models.py. How do I reload this module in Python Shell? -- http://mail.python.org/mailman/listinfo/python-list
newb: Python Floating Point
When I do the following, rounding to 2 decimal places doesn't seem to work. I should get 0.99 : >>> a =0.99 >>> a 0.98999 >>> round(a,2) 0.98999 >>> thank you. -- http://mail.python.org/mailman/listinfo/python-list
newb: lxml objectify
Breakfast at Tiffany's Movie Classic Borat Movie Comedy How do you represent DVD id=1 and it's elements, and DVD id=2 and it's elements as child of root "Library"? Like this:? from lxml import etree from lxml import objectify root = objectify.Element("Library") child[1] = objectify.Element("DVD", id="1") root.new_child = child[1] Thank you -- http://mail.python.org/mailman/listinfo/python-list
Any python based "Live Web Chat Support"
Is there any open source "live web chat support" program or script out there? Any you can recommend? -- http://mail.python.org/mailman/listinfo/python-list
Python **kwargs ?
What is **kwargs mean in python? When you put double **, does it mean passing by reference? For example: def redirect_to(request, url, **kwargs): -- http://mail.python.org/mailman/listinfo/python-list
best open source sample
Hi, I'm new to Python and am looking for a really good/complete open source project to learn from. I'd like it to take input from the browser and query mysql. Suggestions? -- http://mail.python.org/mailman/listinfo/python-list
Re: best open source sample
On Nov 13, 9:14 am, [EMAIL PROTECTED] wrote: > On Nov 13, 9:20 am, Johnny <[EMAIL PROTECTED]> wrote: > > > Hi, I'm new to Python and am looking for a really good/complete open > > source project to learn from. I'd like it to take input from the > > browser and query mysql. Suggestions? > > Zope / Plone, Django, or Turbogears are all web frameworks that are > Python based. You could check those out. Dabo is created on top of > wxPython and is made for accessing databases. > > You might also find these links helpful: > > http://wiki.python.org/moin/SummerOfCodehttp://freshmeat.net/articles/view/334/www.python.org > > Mike Thanks Mike - that should get me going. -- http://mail.python.org/mailman/listinfo/python-list
any function to fill zeros to the right?? zfill??
if I want to fill zeros to the right, what function can help?? ex: '1.23'=>'1.2300' but '1.23'.zfill(6)=>'001.23' -- http://mail.python.org/mailman/listinfo/python-list
Fwd: Sockets: Receiving C Struct
I was not sure if this message was sent before my membership was accepted. Please disregard if it's a duplicate. Thanks Begin forwarded message: > From: Johnny Venter > Date: August 5, 2011 8:15:53 AM EDT > To: python-list@python.org > Subject: Sockets: Receiving C Struct > > New to python and would like to test network/sockets with it. > > I am having a problem where I have setup the following: > > import socket, sys, struct > > HOST = '1.1.1.1' > PORT = 153 > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > s.connect((HOST, PORT)) > > data = struct.unpack('!I',s.recv(4))[0] > > s.close() > > print data > > > What I would like to do is take the input from the server, and store it in an > array. The type of data is int. > > Can someone help? > > > Thanks, Johnny > PGP.sig Description: This is a digitally signed message part -- http://mail.python.org/mailman/listinfo/python-list
Sockets: Receiving C Struct
New to python and would like to test network/sockets with it. I am having a problem where I have setup the following: import socket, sys, struct HOST = '1.1.1.1' PORT = 153 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) data = struct.unpack('!I',s.recv(4))[0] s.close() print data What I would like to do is take the input from the server, and store it in an array. The type of data is int. Can someone help? Thanks, Johnny PGP.sig Description: This is a digitally signed message part -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Windows Extensions for Mac
Thank you all for the replies. I would like to query various Windows' objects and resources from Mac and/or Linux such as Active Directory users, network shares, group members, etc... What module or methods can I use with python to accomplish this? I found dcerpc might be the way to go. On Aug 20, 2011, at 1:39 PM, Kevin Walzer wrote: > On 8/19/11 4:02 PM, johnny.venter wrote: >> >> Hello, I am looking for the Python Windows Extensions to see if they can be >> installed on a Mac.THanks. >> > > You can certainly try to install them via easy_install, I supposed, but it's > doubtful they would do anything, as the Mac does not support win32 API calls > any more than Windows supports Cocoa/Objective-C calls. > > -- > Kevin Walzer > Code by Kevin > http://www.codebykevin.com > -- > http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Windows Extensions for Mac
Yes, I want to make my queries from a remote non-Windows computer. Here is the scenario: >From my mac, I want to use python to access and read objects from a remote >Windows computer joined to a Windows 2003 functional level domain. Given this, >what is the best way to accomplish this? On Aug 20, 2011, at 7:57 PM, Chris Angelico wrote: > On Sun, Aug 21, 2011 at 12:51 AM, Johnny Venter > wrote: >> Thank you all for the replies. I would like to query various Windows' >> objects and resources from Mac and/or Linux such as Active Directory users, >> network shares, group members, etc... What module or methods can I use with >> python to accomplish this? >> > > The concept doesn't have meaning on a non-Windows computer, so I am > going to take the liberty of assuming that you really want to query > them from a different computer - some kind of network query. If that's > not the case, can you clarify exactly what your setup is? > > Chris Angelico > -- > http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Learning Python
http://greenteapress.com/thinkpython/ On Aug 23, 2011, at 10:46 PM, User wrote: > Hello all, > Does anyone have any good resources for learning Python? I know basic Java > and basic Python (loops, data types, if-then statements, etc), but I want to > delve into Python further. If anyone knows of any good books, video > tutorials, etc it would be greatly appreciated. > Thanks, > User > -- > http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Help on regular expression match
Hi, I've met a problem in match a regular expression in python. Hope any of you could help me. Here are the details: I have many tags like this: xxxhttp://xxx.xxx.xxx"; xxx>xxx xx xxxhttp://xxx.xxx.xxx"; xxx>xxx . And I want to find all the "http://xxx.xxx.xxx"; out, so I do it like this: httpPat = re.compile("(http://.*)(\")") result = httpPat.findall(data) I use this to observe my output: for i in result: print i[2] Surprisingly I will get some output like this: http://xxx.xxx.xxx";>xx In fact it's filtered from this kind of source: http://xxx.xxx.xxx";>xx" But some result are right, I wonder how can I get the all the answers clean like "http://xxx.xxx.xxx";? Thanks for your help. Regards, Johnny -- http://mail.python.org/mailman/listinfo/python-list
Re: Help on regular expression match
Fredrik Lundh wrote: > ".*" gives the longest possible match (you can think of it as searching back- > wards from the right end). if you want to search for "everything until a > given > character", searching for "[^x]*x" is often a better choice than ".*x". > > in this case, I suggest using something like > > print re.findall("href=\"([^\"]+)\"", text) > > or, if you're going to parse HTML pages from many different sources, a > real parser: > > from HTMLParser import HTMLParser > > class MyHTMLParser(HTMLParser): > > def handle_starttag(self, tag, attrs): > if tag == "a": > for key, value in attrs: > if key == "href": > print value > > p = MyHTMLParser() > p.feed(text) > p.close() > > see: > > http://docs.python.org/lib/module-HTMLParser.html > http://docs.python.org/lib/htmlparser-example.html > http://www.rexx.com/~dkuhlman/quixote_htmlscraping.html > > Thanks for your help. I found another solution by just simply adding a '?' after ".*" which makes the it searching for the minimal length to match the regular expression. To the HTMLParser, there is another problem (take my code for example): import urllib import formatter parser = htmllib.HTMLParser(formatter.NullFormatter()) parser.feed(urllib.urlopen(baseUrl).read()) parser.close() for url in parser.anchorlist: if url[0:7] == "http://": print url when the baseUrl="http://www.nba.com";, there will raise an HTMLParseError because of a line of code "". I found that this line of code is inside
A problem while using anygui
Hi, I've met a problem while using anygui to create a GUI. Here is a brief example from Dave: ### def guidialog(): def ok(**kw): win.destroy() app.remove(win) # anygui.link(btn_ok, ok) # app.run() return n #qtgui will NEVER get here ### As you can see, the program will never get the sentence "return n". I googled for the problem but didn't find much help. So any one here could give me a hand? thanks regards, Johnny -- http://mail.python.org/mailman/listinfo/python-list
A problem while using urllib
Hi, I was using urllib to grab urls from web. here is the work flow of my program: 1. Get base url and max number of urls from user 2. Call filter to validate the base url 3. Read the source of the base url and grab all the urls from "href" property of "a" tag 4. Call filter to validate every url grabbed 5. Continue 3-4 until the number of url grabbed gets the limit In filter there is a method like this: -- # check whether the url can be connected def filteredByConnection(self, url): assert url try: webPage = urllib2.urlopen(url) except urllib2.URLError: self.logGenerator.log("Error: " + url + " ") return False except urllib2.HTTPError: self.logGenerator.log("Error: " + url + " not found") return False self.logGenerator.log("Connecting " + url + " successed") webPage.close() return True But every time when I ran to the 70 to 75 urls (that means 70-75 urls have been tested via this way), the program will crash and all the urls left will raise urllib2.URLError until the program exits. I tried many ways to work it out, using urllib, set a sleep(1) in the filter (I thought it was the massive urls crashed the program). But none works. BTW, if I set the url from which the program crashed to base url, the program will still crashed at the 70-75 url. How can I solve this problem? thanks for your help Regards, Johnny -- http://mail.python.org/mailman/listinfo/python-list
Re: A problem while using urllib
Alex Martelli wrote: > Johnny Lee <[EMAIL PROTECTED]> wrote: >... > >try: > > webPage = urllib2.urlopen(url) > >except urllib2.URLError: >... > >webPage.close() > >return True > > > > > >But every time when I ran to the 70 to 75 urls (that means 70-75 > > urls have been tested via this way), the program will crash and all the > > urls left will raise urllib2.URLError until the program exits. I tried > > many ways to work it out, using urllib, set a sleep(1) in the filter (I > > thought it was the massive urls crashed the program). But none works. > > BTW, if I set the url from which the program crashed to base url, the > > program will still crashed at the 70-75 url. How can I solve this > > problem? thanks for your help > > Sure looks like a resource leak somewhere (probably leaving a file open > until your program hits some wall of maximum simultaneously open files), > but I can't reproduce it here (MacOSX, tried both Python 2.3.5 and > 2.4.1). What version of Python are you using, and on what platform? > Maybe a simple Python upgrade might fix your problem... > > > Alex Thanks for the info you provided. I'm using 2.4.1 on cygwin of WinXP. If you want to reproduce the problem, I can send the source to you. This morning I found that this is caused by urllib2. When I use urllib instead of urllib2, it won't crash any more. But the matters is that I want to catch the HTTP 404 Error which is handled by FancyURLopener in urllib.open(). So I can't catch it. Regards, Johnny -- http://mail.python.org/mailman/listinfo/python-list
Re: A problem while using urllib
Steve Holden wrote: > Johnny Lee wrote: > > Alex Martelli wrote: > > > >>Johnny Lee <[EMAIL PROTECTED]> wrote: > >> ... > >> > >>> try: > >>> webPage = urllib2.urlopen(url) > >>> except urllib2.URLError: > >> > >> ... > >> > >>> webPage.close() > >>> return True > >>> > >>> > >>> But every time when I ran to the 70 to 75 urls (that means 70-75 > >>>urls have been tested via this way), the program will crash and all the > >>>urls left will raise urllib2.URLError until the program exits. I tried > >>>many ways to work it out, using urllib, set a sleep(1) in the filter (I > >>>thought it was the massive urls crashed the program). But none works. > >>>BTW, if I set the url from which the program crashed to base url, the > >>>program will still crashed at the 70-75 url. How can I solve this > >>>problem? thanks for your help > >> > >>Sure looks like a resource leak somewhere (probably leaving a file open > >>until your program hits some wall of maximum simultaneously open files), > >>but I can't reproduce it here (MacOSX, tried both Python 2.3.5 and > >>2.4.1). What version of Python are you using, and on what platform? > >>Maybe a simple Python upgrade might fix your problem... > >> > >> > >>Alex > > > > > > Thanks for the info you provided. I'm using 2.4.1 on cygwin of WinXP. > > If you want to reproduce the problem, I can send the source to you. > > > > This morning I found that this is caused by urllib2. When I use urllib > > instead of urllib2, it won't crash any more. But the matters is that I > > want to catch the HTTP 404 Error which is handled by FancyURLopener in > > urllib.open(). So I can't catch it. > > > > I'm using exactly that configuration, so if you let me have that source > I could take a look at it for you. > > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC www.holdenweb.com > PyCon TX 2006 www.python.org/pycon/ I've sent the source, thanks for your help. Regrads, Johnny -- http://mail.python.org/mailman/listinfo/python-list
Re: A problem while using urllib
Steve Holden wrote: > Steve Holden wrote: > > Johnny Lee wrote: > > [...] > > > >>I've sent the source, thanks for your help. > >> > > > > [...] > > Preliminary result, in case this rings bells with people who use urllib2 > > quite a lot. I modified the error case to report the actual message > > returned with the exception and I'm seeing things like: > > > > http://www.holdenweb.com/./Python/webframeworks.html > > Message: > > Start process > > http://www.amazon.com/exec/obidos/ASIN/0596001886/steveholden-20 > > Error: IOError while parsing > > http://www.amazon.com/exec/obidos/ASIN/0596001886/steveholden-20 > > Message: > > . > > . > > . > > > > So at least we know now what the error is, and it looks like some sort > > of resource limit (though why only on Cygwin betas me) ... anyone, > > before I start some serious debugging? > > > I realized after this post that WingIDE doesn't run under Cygwin, so I > modified the code further to raise an error and give us a proper > traceback. I also tested the program under the standard Windows 2.4.1 > release, where it didn't fail, so I conclude you have unearthed a Cygwin > socket bug. Here's the traceback: > > End process http://www.holdenweb.com/contact.html > Start process http://freshmeat.net/releases/192449 > Error: IOError while parsing http://freshmeat.net/releases/192449 > Message: > Traceback (most recent call last): >File "Spider_bug.py", line 225, in ? > spider.run() >File "Spider_bug.py", line 143, in run > self.grabUrl(tempUrl) >File "Spider_bug.py", line 166, in grabUrl > webPage = urllib2.urlopen(url).read() >File "/usr/lib/python2.4/urllib2.py", line 130, in urlopen > return _opener.open(url, data) >File "/usr/lib/python2.4/urllib2.py", line 358, in open > response = self._open(req, data) >File "/usr/lib/python2.4/urllib2.py", line 376, in _open > '_open', req) >File "/usr/lib/python2.4/urllib2.py", line 337, in _call_chain > result = func(*args) >File "/usr/lib/python2.4/urllib2.py", line 1021, in http_open > return self.do_open(httplib.HTTPConnection, req) >File "/usr/lib/python2.4/urllib2.py", line 996, in do_open > raise URLError(err) > urllib2.URLError: > > Looking at that part of the course of urrllib2 we see: > > headers["Connection"] = "close" > try: > h.request(req.get_method(), req.get_selector(), req.data, > headers) > r = h.getresponse() > except socket.error, err: # XXX what error? > raise URLError(err) > > So my conclusion is that there's something in the Cygwin socket module > that causes problems not seen under other platforms. > > I couldn't find any obviously-related error in the Python bug tracker, > and I have copied this message to the Cygwin list in case someone there > knows what the problem is. > > Before making any kind of bug submission you should really see if you > can build a program shorter that the existing 220+ lines to demonstrate > the bug, but it does look to me like your program should work (as indeed > it does on other platforms). > > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC www.holdenweb.com > PyCon TX 2006 www.python.org/pycon/ But if you change urllib2 to urllib, it works under cygwin. Are they using different mechanism to connect to the page? -- http://mail.python.org/mailman/listinfo/python-list
Re: A problem while using urllib
Steve Holden 写道: > Good catch, John, I suspect this is a possibility so I've added the > following note: > > """The Windows 2.4.1 build doesn't show this error, but the Cygwin 2.4.1 > build does still have uncollectable objects after a urllib2.urlopen(), > so there may be a platform dependency here. No 2.4.2 on Cygwin yet, so > nothing conclusive as lsof isn't available.""" > > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC www.holdenweb.com > PyCon TX 2006 www.python.org/pycon/ Maybe it's really a problem of platform dependency. Take a look at this brief example, (not using urllib, but just want to show the platform dependency of python): Here is the snapshot from dos: --- D:\>python ActivePython 2.4.1 Build 247 (ActiveState Corp.) based on Python 2.4.1 (#65, Jun 20 2005, 17:01:55) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> f = open("t", "r") >>> f.tell() 0L >>> f.readline() 'http://cn.realestate.yahoo.com\n' >>> f.tell() 28L -- Here is the a snapshot from cygwin: --- Johnny [EMAIL PROTECTED] /cygdrive/d $ python Python 2.4.1 (#1, May 27 2005, 18:02:40) [GCC 3.3.3 (cygwin special)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> f = open("t", "r") >>> f.tell() 0L >>> f.readline() 'http://cn.realestate.yahoo.com\n' >>> f.tell() 31L -- http://mail.python.org/mailman/listinfo/python-list
Question on class member in python
Class A: def __init__(self): self.member = 1 def getMember(self): return self.member a = A() So, is there any difference between a.member and a.getMember? thanks for your help. :) Regards, Johnny -- http://mail.python.org/mailman/listinfo/python-list
Re: Question on class member in python
Peter Otten 写道: > Johnny Lee wrote: > > > Class A: > >def __init__(self): > > self.member = 1 > > > >def getMember(self): > > return self.member > > > > a = A() > > > > So, is there any difference between a.member and a.getMember? thanks > > for your help. :) > > Yes. accessor methods for simple attributes are a Javaism that should be > avoided in Python. You can always turn an attribute into a property if the > need arises to do some calculations behind the scene > > >>> class A(object): > ... def getMember(self): > ... return self.a * self.b > ... member = property(getMember) > ... def __init__(self): > ... self.a = self.b = 42 > ... > >>> A().member > 1764 > > I. e. you are not trapped once you expose a simple attribute. > > Peter Thanks for your help, maybe I should learn how to turn an attibute into a property first. -- http://mail.python.org/mailman/listinfo/python-list
Re: Question on class member in python
But I still wonder what's the difference between the A().getMember and A().member besides the style -- http://mail.python.org/mailman/listinfo/python-list
Re: Question on class member in python
Alex Martelli 写道: > Johnny Lee <[EMAIL PROTECTED]> wrote: > > > But I still wonder what's the difference between the A().getMember and > > A().member besides the style > > Without parentheses after it, getMember is a method. The difference > between a method object and an integer object (which is what member > itself is in your example) are many indeed, so your question is very > strange. You cannot call an integer, you cannot divide methods, etc. > > > Alex Sorry, I didn't express myself clear to you. I mean: b = A().getMember() c = A().member what's the difference between b and c? If they are the same, what's the difference in the two way to get the value besides the style. -- http://mail.python.org/mailman/listinfo/python-list
Re: Question on class member in python
It looks like there isn't a last word of the differrences -- http://mail.python.org/mailman/listinfo/python-list
How to translate python into C
Hi, First, I want to know whether the python interpreter translate the code directly into machine code, or translate it into C then into machine code? Second, if the codes are translated directly into machine codes, how can I translate the codes into C COMPLETELY the same? if the codes are translated first into C, where can I get the C source? Thanks for your help. Regards, Johnny -- http://mail.python.org/mailman/listinfo/python-list
Re: How to translate python into C
Szabolcs Nagy wrote: > python creates bytecode (like java classes) > > > you cannot translate python directly to c or machine code, but there > are some projects you probably want to look into > > > Pypy is a python implemetation in python and it can be used to > translate a python scrip to c or llvm code. (large project, work in > progress) > http://codespeak.net/pypy/dist/pypy/doc/news.html > > > Shedskin translates python code to c++ (not all language features > supported) > http://shed-skin.blogspot.com/ > > > Pyrex is a nice language where you can use python and c like code and > it translates into c code. (it is useful for creating fast python > extension modules or a python wrapper around an existing c library) > http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ Thanks, Szabolcs. In fact, I want to reproduce a crush on cygwin. I used a session of python code to produce the crush, and want to translate it into C and reproduce it. Is the tools provided by you help with these issues? Of coz, I'll try them first. :) Regards, Johnny -- http://mail.python.org/mailman/listinfo/python-list
Re: How to translate python into C
Thanks for your tips Niemann:) Regards, Johnny -- http://mail.python.org/mailman/listinfo/python-list
Re: How to translate python into C
Thanks Szabolcs and Laurence, it's not the crash of python but the crash of cygwin. We can locate the line number but when we submit the crash to cygwin's mail list, they told us they don't speak python. So I'm just trying to re-produce the crash in C. Regards, Johnny -- http://mail.python.org/mailman/listinfo/python-list
Why the nonsense number appears?
Hi, Pls take a look at this code: -- >>> t1 = "1130748744" >>> t2 = "461" >>> t3 = "1130748744" >>> t4 = "500" >>> time1 = t1+"."+t2 >>> time2 = t3+"."+t4 >>> print time1, time2 1130748744.461 1130748744.500 >>> float(time2) - float(time1) 0.03934332275391 >>> Why are there so many nonsense tails? thanks for your help. Regards, Johnny -- http://mail.python.org/mailman/listinfo/python-list
Unbinding multiple variables
Hi! Is there a way to automate the unbinding of multiple variables? Say I have a list of the names of all variables in the current scope via dir(). Is there a command using del or something like that that will iterate the list and unbind each of the variables? Thanks much! (If anyone posts an answer, if you could also cc your reply to my email [EMAIL PROTECTED], would be much obliged. Thanks again!) Best, -Johnny www.johnny-lin.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Unbinding multiple variables
thanks everyone for the replies! John Hunter, yep, this is Johnny Lin in geosci :). re using return: the problem i have is somewhere in my code there's a memory leak. i realize return is supposed to unbind all the local variables, but since the memory leak is happening despite return, i thought it might help me track down the leak if i unbound everything explicitly that i had defined in local scope before i returned. or if anyone has recomm. on plugging leaks, would be thankful for any pointers there too. my understanding about locals() from the nutshell book was that i should treat that dictionary as read-only. is it safe to use it to delete entries? thanks again! -- http://mail.python.org/mailman/listinfo/python-list
Re: Unbinding multiple variables
thanks again for all the help! especially the advice on ideas of tracking down the memory leak :). (sorry for not mentioning it earlier...i had thought deleting everything might be a quick and dirty way short-term fix. :P) best, -Johnny -- http://mail.python.org/mailman/listinfo/python-list
What's the matter with this code section?
Here is the source: #! /bin/python [EMAIL PROTECTED] This is a xunit test framework for python, see TDD for more details class TestCase: def setUp(self): print "setUp in TestCase" pass def __init__(self, name): print "__init__ in TestCase" self.name = name def run(self): print "run in TestCase" self.setUp() method = getattr(self, self.name) method() class WasRun(TestCase): def __init__(self, name): print "__init__ in WasRun" self.wasRun = None TestCase.__init__(self, name) def testMethod(self): print "testMethod in WasRun" self.wasRun = 1 def run(self): print "run in WasRun" method = getattr(self, self.name) method() def setUp(self): print "in setUp of WasRun" self.wasSetUp = 1 class TestCaseTest(TestCase): def testRunning(self): print "testRunning in TestCaseTest" test = WasRun("testMethod") assert(not test.wasRun) test.run() assert(test.wasRun) def testSetUp(self): print "testSetUp in TestCaseTest" test = WasRun("testMethod") test.run() assert(test.wasSetUp) # the program starts here print "starts TestCaseTest(\"testRunning\").run()" TestCaseTest("testRunning").run() print "starts TestCaseTest(\"testSetUp\").run()" TestCaseTest("testSetUp").run() And here is the result running under cygwin: $ ./xunit.py starts TestCaseTest("testRunning").run() __init__ in TestCase run in TestCase setUp in TestCase testRunning in TestCaseTest __init__ in WasRun __init__ in TestCase run in WasRun testMethod in WasRun starts TestCaseTest("testSetUp").run() __init__ in TestCase run in TestCase setUp in TestCase testSetUp in TestCaseTest __init__ in WasRun __init__ in TestCase run in WasRun testMethod in WasRun Traceback (most recent call last): File "./xunit.py", line 51, in ? TestCaseTest("testSetUp").run() File "./xunit.py", line 16, in run method() File "./xunit.py", line 45, in testSetUp assert(test.wasSetUp) AttributeError: WasRun instance has no attribute 'wasSetUp' -- http://mail.python.org/mailman/listinfo/python-list
What's the difference between VAR and _VAR_?
Hi, I'm new in python and I was wondering what's the difference between the two code section below: (I) class TestResult: _pass_ = "pass" _fail_ = "fail" _exception_ = "exception" (II) class TestResult: pass = "pass" fail = "fail" exception = "exception" Thanks for your help. -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the difference between VAR and _VAR_?
As what you said, the following two code section is totally the same? (I) class TestResult: _passxxx_ = "pass" (II) class TestResult: passxxx = "pass" -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the difference between VAR and _VAR_?
Erik Max Francis wrote: > > No, of course not. One defines a class varaible named `_passxxx_', the > other defines one named `passsxxx'. > I mean besides the difference of name... -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the difference between VAR and _VAR_?
Erik Max Francis wrote: > > You're going to have to be more clear; I don't understand your question. > What's the difference between > > a = 1 > > and > > b = 1 > > besides the difference of name? > I thought there must be something special when you named a VAR with '_' the first character. Maybe it's just a programming style and I had thought too much... -- http://mail.python.org/mailman/listinfo/python-list
Would you pls tell me a tool to step debug python program?
Hi, I've met a problem to understand the code at hand. And I wonder whether there is any useful tools to provide me a way of step debug? Just like the F10 in VC... Thanks for your help. Regards, Johnny -- http://mail.python.org/mailman/listinfo/python-list
An interesting python problem
Hi, Look at the follow command in python command line, See what's interesting?:) >>> class A: i = 0 >>> a = A() >>> b = A() >>> a.i = 1 >>> print a.i, b.i 1 0 --- >>> class A: arr = [] >>> a = A() >>> b = A() >>> a <__main__.A instance at 0x00C96698> >>> b <__main__.A instance at 0x00CA0760> >>> A >>> a.arr.append("haha") >>> print a.arr , b.arr ['haha'] ['haha'] >>> a.arr = ["xixi"] >>> print a.arr , b.arr ['xixi'] ['haha'] >>> A.arr ['haha'] >>> A.arr.append("xx") >>> A.arr ['haha', 'xx'] >>> a.arr ['xixi'] >>> b.arr ['haha', 'xx'] >>> b.arr.pop() 'xx' >>> b.arr ['haha'] >>> A.arr ['haha'] - >>> class X: def __init__(self): self.arr = [] >>> m = X() >>> n = X() >>> m.arr.append("haha") >>> print m.arr, n.arr ['haha'] [] -- http://mail.python.org/mailman/listinfo/python-list
Re: An interesting python problem
bruno modulix wrote: > > I dont see anything interesting nor problematic here. If you understand > the difference between class attributes and instance attributes, the > difference between mutating an object and rebinding a name, and the > attribute lookup rules in Python, you'll find that all this is the > normal and expected behavior. > > Or did I miss something ? > No, you didn't miss anything as I can see. Thanks for your help:) -- http://mail.python.org/mailman/listinfo/python-list
Re: No newline using printf
Roy Smith wrote: > > For closer control over output, use the write() function. You want > something like: > > import sys > for i in range(3): >sys.stdout.write (str(i)) here is the output of my machine: >>> import sys >>> for i in range(3): ... sys.stdout.write(str(i)) ... 012>>> Why the prompt followed after the output? Maybe it's not as expected. -- http://mail.python.org/mailman/listinfo/python-list
Re: Programming Language for Systems Administrator
Kanthi Kiran Narisetti wrote: > Hi All, > > I am Windows Systems Administrator(planning to migrate to Linux > administration in near future), I have occassionally written few batch > files and Vbscripts to automate my tasks. > > Now I have strong interest to learn a programming language that would > help me to write Scripts or Application ( In Systems Administrative > point of view) . > > I have read on net that Python is the best way to start of for beginers > , Please let me your suggestions and help me out to chose to the right > programming language to write scripts ranging from simple automation > scripts to appliations for my workflow. > > I am confused to chose between C++,Python,Perl. > > Thanks in Advance > > Kk -- http://mail.python.org/mailman/listinfo/python-list
Re: Good morning or good evening depending upon your location. I want to ask you the most important question of your life. Your joy or sorrow for all eternity depends upon your answer. The question is: Are you saved? It is not a question of how good you are, nor if you are a church member, but are you saved? Are you sure you will go to Heaven when you die? GOOGLE·NEWSGROUP·POST·146
You seem to have a lot of questions for someone who talks to God every three minutes. What do you guys do, discuss the Yankees or something? -- http://mail.python.org/mailman/listinfo/python-list
Spamming nut won't go away
There is no God. OK, Ron, discuss. Ron wrote: > Reports to [EMAIL PROTECTED], [EMAIL PROTECTED], [EMAIL PROTECTED], > [EMAIL PROTECTED], [EMAIL PROTECTED] > > And do not feed the troll! -- http://mail.python.org/mailman/listinfo/python-list
Re: Ron Grossi: God is not a man
C'mon. Everyone knows God plays a Martin. -- http://mail.python.org/mailman/listinfo/python-list
Re: Ron Grossi: God is not a man
Can we stop crossposting this shit to the Beatles NG, please? Donald L McDaniel wrote: > Matt Hayden wrote: > > Johnny Gentile wrote: > >> C'mon. Everyone knows God plays a Martin. > > > > I dunno. I think God has a honkin' big collection so he won't offend > > ANY luthiers when they come to visit. SOMEONE has to set up his > > guitars... > > > > mh > > 1) God is a Being Who lives in Eternity and Infinity. > > 2) God is not a man. However, His Son, Christ Jesus, left the loftiness of > Eternity and became a Man without losing His God-Substance which He > receives from His Father. This means He is not just a man, but the God-Man. > > 3)He lived a pure, sinless life, and died on the Cross in our place, as the > Sacrifice for our sins. However, He did not remain in the Tomb HE was > placed in after He was taken down from the cross by those who loved Him. > Within three days, HE was raised from the dead by His Father, still the > God-Man. After 40 days on the earth, He was returned to the Father in His > Body of flesh, tho now It was glorified (made eternal by the Father). There > He is to this very day, interceeding for those who have received Him as the > Anointed One of God. > > 4) One day, hopefully, soon, He will return in Power and Glory to judge the > thoughts of all men, and transfer His servants from their bodies of flesh to > glorified bodies, like His. > > Do not try to reason this out, since the Incarnation of Christ is not a > thing of logic and reason, but a Holy Mystery, only comprehended by faith in > those who have put their hope and trust in Him and His Sacrifice on the > Cross. Faith can easily be understood by a man with an open mind: Let us > say that there is a Sargent in the Army; his commanding officer, a General, > whose desk is a thousand miles away, and whom he has never seen, gives him a > letter containing an order. The Sargent's act of obedience to the order can > be explained as "faith", since he never saw the General, and obeys him > simply because he is his commanding officer. While we have never seen the > Father, we obey Him, because He sent a Man with orders from Him for His > servants. > > Not only that, but this simple faith is testified to by the Holy Spirit > after we obey, and our steps of faith are rewarded with experiential > knowledge of God, as we learn to recognise His Hand in our lives. We obey > God simply because His Son and servants tell us to. Through time and > experience, we have learned to trust His Words, because they come to pass, > in His Time, and in His Way. > > 4) I doubt seriously whether God plays a guitar, since guitars are made by > men, for men. His Son could theoretically play a guitar. Perhaps He does. > Perhaps He doesn't. Only the Father and His Holy Angels know. > > -- > Donald L McDaniel > Please reply to the original thread, > so that the thread may be kept intact. > == -- http://mail.python.org/mailman/listinfo/python-list
Re: Ron Grossi: God is not a man
Donald - go away. Far away. Now. And, for the last time (hopefully), stop crossposting to rec.music.beatles. Go sell crazy somewhere else. We're all stocked up. Donald L McDaniel wrote: > AKA wrote: > > "Donald L McDaniel" <[EMAIL PROTECTED]> wrote in message > > news:[EMAIL PROTECTED] > >> MC05 wrote: > >>> "sheltech" <[EMAIL PROTECTED]> wrote in message > >>> news:[EMAIL PROTECTED] > > "MC05" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] > > > > "Donald L McDaniel" <[EMAIL PROTECTED]> wrote in message > > news:[EMAIL PROTECTED] > >> > >> 4) I doubt seriously whether God plays a guitar, since guitars > >> are made by men, for men. His Son could theoretically play a > >> guitar. Perhaps He does. Perhaps He doesn't. Only the Father > >> and His Holy Angels know. > > > > So then Lucifer was a wicked bass player whose sex and drugs and > > rock n roll alientated the rest of the band and was fired? > > > > > > > > "Fired" good one > >>> > >>> Heh. Can't take credit for an accident. Your eye is better than > >>> mine. :) > >> > >> The Devil has been fired...by God Himself. Read the Book of > >> Revelation in the New Testament: Satan's end is clearly outlined by > >> the Angel Jesus sent to St. John. This end is very clear: he will > >> be cast alive into the Lake which burns with fire and brimstone, > >> where he will be tormented day and night forever. > >> > >> Not only Satan and his angels will be cast into the Lake, but all > >> those who follow him and his servants. I assure you, Satan won't be > >> ruling anyone in the Fire. He will be in just as much torment as > >> his followers. Neither will he have any sort of job. > >> > >> I strongly advise you to stop making fun of things you have no > >> understanding of. Your eternal destiny depends on the way you treat > >> others. > >> > >> -- > >> Donald L McDaniel > >> Please reply to the original thread, > >> so that the thread may be kept intact. > >> == > >> > > Just imagine if you actually had a coherent thought. > > My Bible tells me that the Truth sounds like foolishness to a perishing man. > Are you perishing? God threw out a life-raft for you. Jesus is more than > willing to rescue a drowning man. Go to the nearest church(Roman Catholic, > Eastern Orthodox), and ask how you can be saved from your sin. > > -- > Donald L McDaniel > Please reply to the original thread, > so that the thread may be kept intact. > == -- http://mail.python.org/mailman/listinfo/python-list
Re: Ron Grossi: God is not a man
>From the Book of Armaments: "And Saint Attila raised the hand grenade up on high, saying, 'Oh, Lord, bless this thy hand grenade that with it thou mayest blow thy enemies to tiny bits, in thy mercy.' And the Lord did grin, and people did feast upon the lambs, and sloths, and carp, and anchovies, and orangutans, and breakfast cereals, and fruit bats..." "And the Lord spake, saying, 'First shalt thou take out the Holy Pin. Then, shalt thou count to three, no more, no less. Three shalt be the number thou shalt count, and the number of the counting shalt be three. Four shalt thou not count, nor either count thou two, excepting that thou then proceed to three. Five is right out. Once the number three, being the third number, be reached, then lobbest thou thy Holy Hand Grenade of Antioch towards thou foe, who being naughty in my sight, shall snuff it.'" -- http://mail.python.org/mailman/listinfo/python-list
space saving retitle of thread
aa. -- http://mail.python.org/mailman/listinfo/python-list
stop
Enough salvation for one day. -- http://mail.python.org/mailman/listinfo/python-list
thread title's getting shorter...
. -- http://mail.python.org/mailman/listinfo/python-list
Re: space saving retitle of thread
And this is OK w/ Google? -- http://mail.python.org/mailman/listinfo/python-list
another title shortener
. [EMAIL PROTECTED] wrote: > Best Viewed at << 1024x768 >> > http://groups-beta.google.com/group/alt.religion.christian/browse_thread/thread/73352e0ed6923d23/1ea6c7a1ea6923ab?hl=en#1ea6c7a1ea6923ab > > *** > *** > *** > *** > > > THE MOST IMPORTANT QUESTION OF YOUR LIFE > > > > This is the most important question of your life. > > The question is: Are you saved? > > It is not a question of how good you are, nor if you > are a church member, but are you saved? > > Are you sure you will go to Heaven when you die? > > The reason some people don't know for sure if they are > going to Heaven when they die is because they just > don't know. > > The good news is that you can know for sure that you > are going to Heaven. > > The Holy Bible describes Heaven as a beautiful place > with no death, sorrow, sickness or pain. > > God tells us in the Holy Bible how simple it is to be > saved so that we can live forever with Him in Heaven. > > "For if you confess with your mouth Jesus is Lord and > believe in your heart that God raised Him from the > dead, you will be saved." (Romans 10:9) > > Over 2000 years ago God came from Heaven to earth in > the person of Jesus Christ to shed His blood and die > on a cross to pay our sin debt in full. > > Jesus Christ was born in Israel supernaturally to a > virgin Jewish woman named Mary and lived a sinless > life for thirty-three years. > > At the age of thirty-three Jesus was scourged and > had a crown of thorns pressed onto His head then > Jesus was crucified. > > Three days after Jesus died on a cross and was placed > in a grave Jesus rose from the dead as Jesus said > would happen before Jesus died. > > If someone tells you that they are going to die > and then three days later come back to life and it > actually happens then this person must be the real deal. > > Jesus Christ is the only person that ever lived a > perfect sinless life. > > This is why Jesus is able to cover our sins(misdeeds) > with His own blood because Jesus is sinless. > > The Holy Bible says, "In Him(Jesus) we have redemption > through His blood, the forgiveness of sins..." > (Ephesians 1:7) > > If you would like God to forgive you of your past, > present and future sins just ask Jesus Christ to be > your Lord and Saviour. > > It doesn't matter how old you are or how many bad things > that you have done in your life including lying and > stealing all the way up to murder. > > Just pray the prayer below with your mouth and mean it > from your heart and God will hear you and save you. > > Dear Jesus Christ, I want to be saved so that I can have > a home in Heaven with You when I die. I agree with You > that I am a sinner. I believe that You love me and want > to save me. I believe that You bled and died on the cross > to pay the penalty for my sins and that You rose from the > dead. Please forgive my sins and come into my heart and > be my Lord and Saviour. Thanks Lord Jesus Christ for > forgiving me and saving me through Your merciful grace. > Amen. > > Welcome to the family of God if you just allowed God > to save you. > > Now you are a real Christian and you can know for sure > that you will live in Heaven forever when this life > comes to an end. > > As a child of God we are to avoid sin(wrongdoing), but > if you do sin the Holy Bible says, "My dear children, > I write this to you so that you will not sin. But if > anybody does sin, we have one who speaks to the Father > in our defense Jesus Christ, the Righteous One." > > Those of you that have not yet decided to place your > trust in the Lord Jesus Christ may never get another > chance to do so because you do not know when you will die. > > Jesus said, "I am the way, the truth and the life: no one > can come to the Father(God)(in Heaven), but by me." > (John 14:6) > > This means that if you die without trusting in Jesus Christ > as your Lord and Saviour you will die in your sins and be > forever separated from the love of God in a place called Hell. > > The Holy Bible descibes Hell as a place of eternal > torment, suffering, pain and agony for all those who > have rejected Jesus Christ. > > The good news is that you can avoid Hell by allowing > Jesus Christ to save you today. Only then will you > have true peace in your life knowing that no matter > what happens you are on your way to Heaven. > > > > > Praise the Lord! > Servant of the Lord Jesus Christ > Ronald L. Grossi > > > * Show this to your family and friends so they can also be saved. > > * This message may get deleted so you may want to print a copy. > > * Just press the [Ctrl][P] keys on your keyboard to print this page. > > > > _
Re: rewrite for achieving speedup
thanks steve h., works like this just perfectly! steve b.: for the next time if i cannot figure it out i will just do it like this! thanks a lot guys, Frank -- http://mail.python.org/mailman/listinfo/python-list
rewrite for achieving speedup
Hello Group! I really tried hard for two hours to rewrite the following expression (python 2.4): -- teilnehmer = [] for r in Reisen.select(AND(Reisen.q.RESVON <= datum, Reisen.q.RESBIS >= datum)): for g in r.BUCHUNGEN: for t in g.aktiveTeilnehmer: teilnehmer.append(t) -- to something like -- teilnehmer = [x for x in ] -- Reisen is a SQLObject class, Reisen.select(...), aktiveTeilnehmer and BUCHUNGEN all are of the type SelectResults. unfortunately i just can´t figure it out to make it work. i hope someone maybe can help me? I hope to gain performance by rewriting it... Thanks a lot for your help! Regards, Frank -- http://mail.python.org/mailman/listinfo/python-list
New Pythin user looking foe some good examples to study
I have just discovered Python and am familiarizing myself with the syntax but I have always found that code examples where the best way for me to learn. Can anyone point me to a site with some good open source functioning python applications? I would appreciate any help. Also, does anyone know of any good Linux or python user groups in the orange county, California area? -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I call a python method from the XML-RPC client in Java?
[EMAIL PROTECTED] wrote: > Hi all, > I have created a XML-RPC model (with server and client) written in > Java. > I want to call the methods in another XML-RPC model written in > Python. > I know that in Java, I can use like > "xmlrpc_client.excute("handler_name.method", param)" to call the > methods in my xml-rpc server written in java. >But how can I call the methods in Python? I cannot creat a handler > in my Python XML-RPC server. > Not sure what you mean by 'creating a handler in your Python RPC server', but if you just want to use the Python XMLRPC library to make a call to an XMLRPC server, there's an example in the documentation: http://docs.python.org/lib/xmlrpc-client-example.html Hope that helps. Cheers, Guido -- http://mail.python.org/mailman/listinfo/python-list
Re: py.test munging strings in asserts?
Timothy Grant wrote: > > granted the left side of that equality could be messed up due to > create_output() NOT doing the right thing. But the right side is > simply the contents of the variable "text" so WHY is the first part of > the path being substituted with "..."? > Some grepping on '...' revealed that there's some string munging going on in py/code/safe_repr.py, In py/test/terminal/terminal.py, in TerminalSession, there's a method 'repr_locals' that uses it, I guess you have to override that or something if you want to change this behaviour... Cheers, Guido Wesdorp -- http://mail.python.org/mailman/listinfo/python-list