Re: [Tutor] Socket Programming issue
aditya nauty.m...@gmail.com wrote in message news:BANLkTikS+gzm=89thczpbwksd+wufec...@mail.gmail.com... This is a small client-server program in which i am using a Vbscript program to check for connectivity of 2 machines and write the output to a text file whether it connectes or not , for example the contents of the file *output.txt* are 192.168.1.2 is connected 192.168.1.10 is not connected Now i am trying to send the contents of this file from a client through a socket to a server which is running on my main server .This is basically created to automate the checking of connectivity of the machines. The issue is that although the Vbscript writes the output to the file correctly but when the client sends the contents of the file to the server via socket , it sometimes prints all the lines of the file on the server and sometimes it doesnt , i dont know whether the issue is with the client or the server , Please Help.. CLIENT.PY import socket import os import sys os.system(C:\Python26\ping.vbs) host = localhost port= 2 size = 1024 s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host,port)) f=open('output.txt','r') while 1: data = f.readline() if data: s.send(data) else: break Use s.sendall(data) instead of send to correct the error Alan pointed out. f.close() s.close() SERVER.PY import socket host = port = 2 size = 1024 backlog=5 s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host,port)) s.listen(backlog) s.accept() should be before the while loop, then loop on recv until the client closes the connection. Since TCP is a streaming protocol, recv() could receive less than a line or more than one line at once, but with the accept inside the loop the script will pause waiting for a different client to connect, and won't continue reading the data from the original client. -Mark while 1: client, addr =s.accept() data=client.recv(size) if data: print data else: print client exit s.close() -- Regards Aditya ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] trying to translate and ebcidic file
Prinn, Craig craig.pr...@bowebellhowell.com wrote in message news:6b49a56a6e493f4eba255f6f197f070f050e4fe...@bbh-mail1.bbh.priv... I am looking for a way to translate and ebcidic file to ascii. Is there a pre-existing library for this, or do I need to do this from scratch? If from scratch and ideas on where to start? There are a couple of EBCDIC codecs (see list of codecs in http://docs.python.org/library/codecs.html). Try:open('file.txt').read().decode('ibm500').encode('ascii','replace') You'll get '?' for chars ascii doesn't support. -Mark ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python ctypes dll issue
mammar mam...@gmail.com wrote in message news:BANLkTin90dmfRkBu5O=dz-p36fp3nl_...@mail.gmail.com... Hi All, I have created a DLL with the following function exported in it int myFunction(char *id, char *name); Below is the python code to load the dll and call myFunction from ctypes import * # Load DLL into memory mydll= windll.LoadLibrary(my.dll) id = create_string_buffer(030725002) name = create_string_buffer(mammar) print mydll.myFunction(id, name) But when i run the above code i am getting error dialog box with following info Debug Assertion Failed! Program: C:\Python27\pythonw.exe file: fread.c line: 93 Expression: (buffer != NULL) Whats the problem? Any idea? windll requires the function called to be __stdcall calling convention. The default is normally __cdecl. Try cdll instead. -Mark ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] process and modify a list of strings, in place
John Martinetti s...@missinglynx.net wrote in message news:AANLkTi=8kvksqzpujsqwffj8yarjcwhuhawtzkzfv...@mail.gmail.com... Hello - I'm a novice programmer, not even amateur level and I need some help with developing an algorithm to process a list of strings. I hope this list is tolerant of n00bs, if not, please let me know and I'll take this elsewhere. Some background. I cut up a text based report from a reporting application into fields by slicing the lines up using fixed column widths to delimit the fields. This was necessary to ensure that a couple of the fields that had free-form comments with variable spacing. If there were well-defined field delimiters I could have used awk or some other text processing tool. Python worked very well for cutting up the lines from the report into fields and let me store each record into a list of strings. So - I have a list of openPOs which is a list of strings. I do this like this: # #! /usr/bin/python import sys, re txtreport=open(open_pos.txt,'r') openPOs=[] while 1: record = txtreport.readline() # - reads in a line of data from the report file vendornum = record[:6] # - breaks out each column of the report into fields vendorname = record[7:40] ordernum = record[41:47] ordersuffix = record[48:59] orderdate = record[60:70] buyer = record[71:77] partnum = record[78:100] qty = record[101:108] comment = record[109:135] # - create a record from all the fields linedata = (vendornum, vendorname, ordernum, ordersuffix, orderdate, buyer, partnum, qty, comment) # - append the record to the list of records representing the CQ report openPOs.append(linedata) # if not the end of the file, do it again if not record: break I noticed when splitting up your record line there is a character skipped between each field. A delimiter perhaps? Then you may be interested in the csv module. Assuming the delimiter is '|', the following code will produce the same result in openPOs: import csv with open('open_pos.txt','rb') as f: reader = csv.reader(f,delimiter='|') openPOs = list(reader) print openPOs Note you may have to specify some more parameters to csv.reader depending on your file dialect. See the csv.Dialect class for details. -Mark ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Looking for a tutor to review my code and provideconstructive feedback.
Glen Clark gle...@gmail.com wrote in message news:aanlktimabbj8ae35q3ao9+xzbvtnyzbz3wrudahmn...@mail.gmail.com... Hello, I have completed my first python script. This is after watching a video guide on python and is my first attempt at writing code in python. While the code is not very useful I got the idea for it when googling python projects for beginners. The idea was to create a script that asked the user to input a list of names and allow the user to change a name if he wanted before confirming the entries. I tried to incorporate what I had learnt from the videos, such as conditionals, error handling, functions etc... and write it how I would write code in future. Please if you are kind enougth to take the time to provide feedback I would appreciate that it is constructive :) The script is here: http://bpaste.net/show/10658/ Your code is very readable...more so than some experienced people ;^) A few suggestions (and assuming Python 3.X, since that's what it looks like): * list shadows a built-in type, and should not be used for variable names. names would be more appropriate. * input() return a string, so no need for str(input(...)). * range(x) is equivalent to range(0,x). * The two loops in InitiateEntries can be consolidated: for In in range(NumItems): names.append(input(Enter name {}: .format(In+1))) Or using a list comprehension: names = [input(Enter name {}: .format(In+1) for In in range(NumItems)] * Prefer for name in names: instead of using indexing, or for idx,name in enumerate(names): if indexes are needed. Example: for idx,name in enumerate(names): print({}: {}.format(idx,name) * Since 1-based indexing was used elsewhere to present names to the user, the PrintEntries display code should also use idx+1. * When returning a boolean value, you can simpify: if confirmed == 'n': return True else: return False To: return confirmed == 'n' Also see PEP8 (http://www.python.org/dev/peps/pep-0008/) for Python's suggested coding standard. -Mark ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Problem with input() and unicode string
Alan Gauld alan.ga...@btinternet.com wrote in message news:i2pqps$fp...@dough.gmane.org... Alex abc...@yahoo.co.uk wrote The first print statement works as expected, both in IDLE and when double-clicking the file for a console view. The second one works in IDLE, but just flashes by when double-clicking the file, due to an error report I can't see. So run it from a Console prompt and you will then be able to see the error. That should help you debug it. Try: import sys year = raw_input(u'Introduce el año:'.encode(sys.stdout.encoding)) Without the explicit encoding I got a UnicodeError due to using the 'ascii' codec. Interesting that 'print' uses the console encoding for Unicode strings, but input() and raw_input() don't for their prompts. You may still get a Unicode error if your console encoding doesn't support the characters you are trying to print, but it worked on my US Windows 'cp437' console. -Mark ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Help - How to end program
Jason MacFiggen jmacfig...@gmail.com wrote in message news:aanlktinevw8zje7fxktomks+tbrp=trmb7sb7pbkt...@mail.gmail.com... Python keeps looping when it gets past the int 0, how do I end the program when it the int 0 or 0. my_hp = 50 mo_hp = 50 my_dmg = random.randrange(1, 20) mo_dmg = random.randrange(1, 20) endProgram = end() while True: if mo_hp 0: print The Lich King has been slain! elif my_hp 0: print You have been slain by the Lich King! if mo_hp = 0: endProgram else my_hp = 0: endProgram else: print Menu Selections: print 1 - Attack print 2 - Defend print choice = input (Enter your selection. ) choice = float(choice) print if choice == 1: mo_hp = mo_hp - my_dmg print The Lich King is at , mo_hp, Hit Points print You did , my_dmg, damage! print my_hp = my_hp - mo_dmg print I was attacked by the lk for , mo_dmg, damage! print My Hit Points are , my_hp print elif choice == 2: mo_hp = mo_hp - my_dmg / 2 print The Lich King is at, mo_hp, Hit Points print you did , my_dmg / 2, damage! print my_hp = my_hp - mo_dmg print I was attacked by the lk for , mo_dmg, damage! print My Hit Points are , my_hp print The keyword 'break' will exit a while loop. Since you have no commands after the while loop, that will end your program. -Mark ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python 2.5.4 - error in rounding
Alan Gauld alan.ga...@btinternet.com wrote in message news:ht6v97$63...@dough.gmane.org... Neven Gorsic neven.gor...@gmail.com wrote I run into Python error in rounding and not know how to predict when it will occur in order to prevent wrong result. It depends how you define wrong. When I was at scvhool the rules f or rounding decimals said that if it ended in 5 you rounded to the nearest even digit. So 0.45 - 0.4 and 0.55 -0.6 But you seem to assume a 5 always rounds up... What can I do to assure accurate result? Just to be picky, Python is being accurate, but it is accurately reflecting the binary value... But I think you knew that! :-) %.2f % 0.465 '0.47' correct %.2f % 0.475 '0.47' not correct %.2f % 0.485 '0.48' not correct The good news is that python's round() function seems to have had the same teacher as you :-) So %.2f % round(0.475,2) '0.48' %.2f % round(0.485, 2) '0.49' Only coincidentally! .475 0.47498 # %.2f will round down to 0.47 .485 0.48499 # %.2f will round down to 0.48 round(.475,2) 0.47998 # %.2f will round up to 0.48 round(.485,2) 0.48999 # %.2f will round up to 0.49 -Mark ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Sequences of letter
Juan Jose Del Toro jdeltoro1...@gmail.com wrote in message news:s2i9b44710e1004112212zdf0b052fxe647ba6bb9671...@mail.gmail.com... Dear List; I have embarked myself into learning Python, I have no programming background other than some Shell scripts and modifying some programs in Basic and PHP, but now I want to be able to program. I have been reading Alan Gauld's Tutor which has been very useful and I've also been watching Bucky Roberts (thenewboston) videos on youtube (I get lost there quite often but have also been helpful). So I started with an exercise to do sequences of letters, I wan to write a program that could print out the suquence of letters from aaa all the way to zzz like this: aaa aab aac ... zzx zzy zzz So far this is what I have: letras = [a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,x,y,z] letra1 = 0 letra2 = 0 letra3 = 0 for i in letras: for j in letras: for k in letras: print letras[letra1]+letras[letra2]+letras[letra3] letra3=letra3+1 letra2=letra2+1 letra1=letra1+1 It goes all the way to aaz and then it gives me this error Traceback (most recent call last): File /home/administrador/programacion/python/letras2.py, line 8, in module print letras[letra1]+letras[letra2]+letras[letra3] IndexError: list index out of range Script terminated. Am I even in the right path? I guess I should look over creating a function or something like that because when I run it I can't even use my computer no memory left -- ¡Saludos! / Greetings! Juan José Del Toro M. jdeltoro1...@gmail.com Guadalajara, Jalisco MEXICO ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor It's easier than you think. Here's a hint: for i in 'abcd': ... print i ... a b c d What are the values of i,j,k in your loop? -Mark ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Searching for time in a given string
Judith Flores jur...@yahoo.com wrote in message news:27451.74230...@web113808.mail.gq1.yahoo.com... Hello, I was wondering if someone could provide me with the pattern syntax to find the time in a given string. The time usually appears as 14:28:32 (for example) within a string (Sun Jan 23 14:28:32 1965). How can I retrieve the time? The built-in datetime module can parse this type of string: (http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior) PythonWin 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on win32. Portions Copyright 1994-2008 Mark Hammond - see 'Help/About PythonWin' for further copyright information. s = Sun Jan 23 14:28:32 1965 from datetime import datetime d=datetime.strptime(s,'%a %b %d %H:%M:%S %Y') d.hour 14 d.minute 28 d.second 32 d.time() datetime.time(14, 28, 32) d.date() datetime.date(1965, 1, 23) d.ctime() 'Sat Jan 23 14:28:32 1965' It also knows that date was really a Saturday :^) -Mark ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to wrap ctype functions
Jan Jansen knack...@googlemail.com wrote in message news:f17500b71003030943w606925edie41b41d6d64ef...@mail.gmail.com... Hi there, I wonder what's the best way to wrap given function calls (in this case ctype function calls but more generally built-in functions and those kinds). I have a huge c library and almost all functions return an error code. The library also contains a function, that returns the corresponding error message to the error code. So, what I need to do for every call to one of the libraries functions looks like this: error_code = my_c_library.SOME_FUNCTION_ CALL(argument) if error_code != 0: error_message = my_c_library.GET_ERROR_TEXT(error_code) print error in function call SOME_FUNCTION_CALL print error_message my_c_library.EXIT_AND_CLEAN_UP() ctypes has a couple of methods to post process return values. 1. A callable can be assigned has the .restype attribute of the function object. In this case, the function is assumed to return an integer, and it is passed to the callable. The function could raise an exception for non-zero return values. This usage is deprecated. See 16.15.1.8. Return types in the Python docs (http://docs.python.org/library/ctypes.html). 2. Any return type can be assigned to .restype, and a callable can be assigned to the .errcheck attribute. This has more flexibility than #1 since it works for return types without int. The callable is provided the return value, original function object, and original arguments to help customize the behavior of the return value. See 16.15.2.3. Foreign functions in the docs. Also, for some function calls I would need to do some preperations like: error_code = my_c_library.LOG_IN_AS_ADMINISTRATOR(admin_user, admin_password) error_code = my_c_library.SOME_FUNCTION_CALL(argument) I like the decorator idea, but I can't figure out if it's applicable here. To be able to call the function in a manner like this would be great, e.g. @change_user(admin_user, admin_password) @error_handling my_c_library.SOME_FUNCTION_CALL(argument) Decorators don't decorate calls to functions, just function declarations. Here's a *rough* example: def prep(func): ... def prepwork(*args,**kwargs): ... print 'doing prep work...' ... func(*args,**kwargs) ... return prepwork ... @prep ... def something(a,b): ... print a,b ... something(1,2) doing prep work... 1 2 -Mark ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Encoding
Giorgio anothernetfel...@gmail.com wrote in message news:23ce85921003050915p1a084c0co73d973282d8fb...@mail.gmail.com... 2010/3/5 Dave Angel da...@ieee.org I think the problem is that i can't find any difference between 2 lines quoted above: a = uciao è ciao and a = ciao è ciao a = unicode(a) Maybe this will help: # coding: utf-8 a = ciao è ciao b = uciao è ciao.encode('latin-1') a is a UTF-8 string, due to #coding line in source. b is a latin-1 string, due to explicit encoding. a = unicode(a) b = unicode(b) Now what will happen? unicode() uses 'ascii' if not specified, because it has no idea of the encoding of a or b. Only the programmer knows. It does not use the #coding line to decide. #coding is *only* used to specify the encoding the source file is saved in, so when Python executes the script, reads the source and parses a literal Unicode string (u'...', u..., etc.) the bytes read from the file are decoded using the #coding specified. If Python parses a byte string ('...', ..., etc.) the bytes read from the file are stored directly in the string. The coding line isn't even used. The bytes will be exactly what was saved in the file between the quotes. -Mark ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python 3.0
bob gailer bgai...@gmail.com wrote in message news:4b7fea0e.6000...@gmail.com... On 2/20/2010 5:52 AM, Paul Whittaker wrote: Using the following script, the (Windows 7) PC echoes the key presses but doesn't quit (ever!) import msvcrt print('Press SPACE to stop...') while True: k = msvcrt.getch() # Strangely, this echoes to the IDLE window if k == ' ': # Not recognized break According to the docs: msvcrt.getch() - Read a keypress and return the resulting characterThis call will block if a keypress is not already available, but will not wait for Enter to be pressed. If the pressed key was a special function key, this will return '\000' or '\xe0'; the next call will return the keycode. The Control-C keypress cannot be read with this function. IOW - getch always returns 1 character. You are testing for a 0 length string. Will never happen. What keystroke do you want to break the loop? To Bob: There is a space between the quotes. To the OP: Are you running from a console window? The code works fine for me from the console, but running under both IDLE and PythonWin msvcrt.getch() returns 255 immediately. Windows applications without a console usually don't play nice with C I/O calls. -Mark ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] create an object from a class in dll with ctypes?
katrin schmid kati...@gmx.de wrote in message news:20100123021522.155...@gmx.net... hi, so how about 32 and 64 bit, do they need separat versions, too? So a pyd is an actual dll? Regrads, katrin Yes, to both questions. -Mark ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] create an object from a class in dll with ctypes?
katrin schmid kati...@gmx.de wrote in message news:0edda7dddff84d639352526b72dbf...@katissspc... hi, i am getting started with ctypes in python 2.5 and was wondering if i would be able to create an object from the class in my dll somehow. I only found examples that show how to access a function but the function i want to call is part of a cpp class in my dll... ctypes is for C DLLs. You might want to look at www.swig.org instead. -Mark ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python workspace - IDE and version control
Kent Johnson ken...@tds.net wrote in message news:1c2a2c591001190905u28db4464hc1d1461ad26e9...@mail.gmail.com... On Tue, Jan 19, 2010 at 9:12 AM, Andreas Kostyrka andr...@kostyrka.org wrote: The cool part about git that I've not yet replicated with hg is git add -p which allows you to seperate out different changes in the same file. Sounds like the record and crecord extensions come close, anyway: http://mercurial.selenic.com/wiki/RecordExtension http://mercurial.selenic.com/wiki/CrecordExtension TortoiseHg's commit GUI allows this. -Mark ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Expanding a Python script to include a zcat and awkpre-process
galaxywatc...@gmail.com wrote in message news:5dff81f3-a087-41f2-984b-914a08e2b...@gmail.com... I wrote a simple Python script to process a text file, but I had to run a shell one liner to get the text file primed for the script. I would much rather have the Python script handle the whole task without any pre-processing at all. I will show 1) a small sample of the text file, 2) my script, 3) the one liner that I want to fold into the script, and 4) the task at hand. 1) $ zcat textfile.txt.zip | head -5 134873600, 134873855, 32787 Protex Technologies, Inc. 135338240, 135338495, 40597 135338496, 135338751, 40993 201720832, 201721087, 12838 HFF Infrastructure Operations 202739456, 202739711, 1623 Beseau Regional de la Region Languedoc Roussillon 2) $ cat getranges.py #!/usr/bin/env python import string highflag = flagcount = sum = sumtotal = 0 infile = open(textfile.txt, r) # Find the range by subtracting column 1 from column 2 for line in infile: num1, num2 = string.split(line) sum = int(num2) - int(num1) if sum 1000: flag1 = flagcount += 1 if sum highflag: highflag = sum else: flag1 = print str(num2) + - + str(num1) + = + str(sum) + flag1 sumtotal = sumtotal + sum print Total ranges = , sumtotal print Total # of ranges over 10 million: , flagcount print Largest range: , highflag 3) zcat textfile.txt.zip | awk -F, '{print $1, $2}' textfile.txt 4) In my first iteration, I used string.split(num1, ,) but I ran into trouble when I encountered commas within column 3, such as 32787 Protexic Technologies, Inc.. I don't know how to handle this exception. I also don't know how to uncompress the file in Python and pass it to the rest of the script. Hence I used my zcat | awk oneliner to get the job done. So how do I uncompress zip and gzipped files in Python, and how do I force split to only evaluate the first two columns? Better yet, can I tell split to not evaluate commas in the double quoted 3rd column? Check out the csv, zipfile, and gzip modules in the Python documentation. -Mark ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Send Hex
Григор grigor.ko...@gmail.com wrote in message news:acd355e80912180634l1c7a545fo7be9d5e99138b...@mail.gmail.com... Hi Can I send date and time like Hex in to the Serial port or file. from time import * It preferable to just use import time import time def TimeMake(): '''Formating time and data (dd-mm-yy hh:mm) and change it like ASCII''' Time=list(localtime()) #get Time and Date Time[0]=str(Time[0])#Make (yy) str Time = '%02d-%02d-%s %02d:%02d' % (Time[2], Time[1], Time[0][2:], Time[4], Time[5]) #Formating (dd-mm-yy hh:mm) The previous lines have a bug (dd-mm-yy mm:ss is the result). A less error-prone version is: Time = time.strftime('%d-%m-%y %H:%M',localtime()) TimeHex = [] for i in Time: #Take ASCII TimeHex.append(ord(i)) Time =[] for i in TimeHex: #Make ASCII in hex format Time.append(hex(i)) return Time Time=TimeMake() #When I write it in the some file is a string but must to be like hex The resulting string from strftime *can* be sent directly to a serial port or file. Each character in the string is a byte of data. If you actually need to send hexadecimal characters as text, the binascii module has hexlify: import binascii import time binascii.hexlify(time.strftime('%d-%m-%y %H:%M',localtime())) '31382d31322d30392032303a3039' -Mark ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] getting python 3 to run from the command line (version2)
Forgive the top-posting, but when in Rome... Running 'chcp' at the command line will show the default code page. Judging from the OP's name it is probably an Arabic version of Windows. Since Python 2.6 works it probably is falling back to something besides cp720. Try: import sys print sys.stdout.encoding to find out what. Python 3.0 probably has a bug if it runs but doesn't work correctly as described by the OP below. Python 3.1 refuses to guess and displays an error. Since Python 3.X uses Unicode for strings it really needs to know the encoding of the terminal to decode stdin and encode to stdout. Implementing a cp720 codec would likely fix the problem. -Mark ALAN GAULD alan.ga...@btinternet.com wrote in message news:339296.66934...@web86707.mail.ird.yahoo.com... Forwarding to the tutor list with cut n paste sessions. It looks to me like the code page issue somebody else referred to is the problem but the behaviour seems a bit extreme, I'd have thought it might have chosen a default value or something... But I'm not sure what causes it to select cp720 in the first place. Where does Py_Initialize get its values? Are they set in the environment somewhere? And why is 2.6 OK? I know 3.0 did some changes around locale handling but I can't recall what they were. I assume this is a side effect of those changes? Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ - Forwarded Message From: Khalid Al-Ghamdi emailkg...@gmail.com To: ALAN GAULD alan.ga...@btinternet.com Sent: Sunday, 15 November, 2009 18:02:25 Subject: Re: [Tutor] getting python 3 to run from the command line (version 2) Hi, I'm really sorry for this hassle! Python31 (gives error): C:\Users\KEpython Fatal Python error: Py_Initialize: can't initialize sys standard streams LookupError: unknown encoding: cp720 This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information. C:\Users\KEcd c:\python31 c:\Python31python Fatal Python error: Py_Initialize: can't initialize sys standard streams LookupError: unknown encoding: cp720 This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information. Python30 (doesn't respond): c:\Python31cd c:\python30 c:\Python30python Python 3.0.1 (r301:69561, Feb 13 2009, 20:04:18) [MSC v.1500 32 bit (Intel)] on win32 Type help, copyright, credits or license for more information. 2+2 Python26(works ok): C:\Users\KEcd c:\python26 c:\Python26python Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32 Type help, copyright, credits or license for more information. 2+2 4 Thanks very much On Sun, Nov 15, 2009 at 8:16 PM, ALAN GAULD alan.ga...@btinternet.com wrote: Unfortunately the image didn't get to me. To copy/paste from a cmd window click the small icon at the left hand end of the title bar. From that select Edit-Mark Use the mouse to select the text you want to copy Use the menu again to do Edit-Copy Now paste into your mail program. You can make this easier by opening the properties dialog from the same menu, and on the Options tag tick QuickEdit. This will allow you to select with the mouse and copy by hitting return after selecting. This is very useful when sending python examples to the tutor list! :-) Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ From: Khalid Al-Ghamdi emailkg...@gmail.com To: Alan Gauld alan.ga...@btinternet.com Sent: Sunday, 15 November, 2009 7:11:06 Subject: Re: [Tutor] getting python 3 to run from the command line (version 2) Hi Alan, this is how the problem looks from my work pc (which is xp. at home i use vista). and yes i don't know how copy and paste from the cmd so here is an image: As you can see when I try to access python31 it gives me the error above. When I use python 26 it works fine. Now, I don't have python30 installed at my work PC, but what happens is when I enter c:\python30\python it initiates and gives me a blank prompt() then when i enter something (2+2 for example) it returns () as if i just pressed enter without entering any code. It just doesn't process the code for me. I hope you can be of help. thanks On Sat, Nov 14, 2009 at 9:56 PM, Alan Gauld alan.ga...@btinternet.com wrote: Khalid Al-Ghamdi emailkg...@gmail.com wrote when i try to code something it just gives me a new line without any processing of the code. (for example:2+2 returns a new line) You mean you get to the prompt? And you type 2+2 you get this: 2+2 With just a newline between your input and the next prompt? when I tried to change the path to the directory that contains python 31 and enter *python (c:\python31)*, I'm not surprised it doesn't work, that
Re: [Tutor] getting python 3 to run from the command line
Khalid Al-Ghamdi emailkg...@gmail.com wrote in message news:dfac564f0911140040y27e0bee5ub02aa2de2b02f...@mail.gmail.com... Hi, for some reason I haven't been able to get python 3 to work from the the command line. I've added it to the the path in the the system variables but still no luck. when I try to run python 2.6 it works flawlessly, though, bearing in mind that it wasn't added to the system variables! i'm running windows vista and have python 30 ,31 and 26 installed. all of this , by the way, was just to get easy install to work so i can get nose working to do some practice of unit testing! can anyone shed some light on the issue? How are you starting python? If you type 'python' and C:\Python31 is the first thing in your path, you should see Python 3.1 execute. If you type 'somefile.py' the Windows command line uses the registered program for the '.py' extension to run the script. It doesn't use the PATH. You can see the default program for an extension from the command line with the 'assoc' and 'ftype' commands: C:\assoc .py .py=Python.File C:\ftype Python.File Python.File=C:\Python26\python.exe %1 %* -Mark ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] getting python 3 to run from the command line (version 2)
Khalid Al-Ghamdi emailkg...@gmail.com wrote in message news:dfac564f0911140854v42fa4e0ehe5868517a50ef...@mail.gmail.com... hi all, I realize my question was previous question was phrased, well, vaguely, as I learn from your responses so here's version 2 of my question: i'm running windows vista and have python 30 ,31 and 26 installed.! when I try to run python form the command line by printing *python *to whichever path i have there (in my case:C:\users\KE) it runs python 30, but when i try to code something it just gives me a new line without any processing of the code. (for example:2+2 returns a new line) when I tried to change the path to the directory that contains python 31 and enter *python (c:\python31)*, it just crashes and gives me the following message: *fatal python error: Py_Initialize: can't initialize sys standard streams * *LookupError: unknown encoding: cp720* * * *This application has requested the Runtime to terminate it in an unusual way. * *Please contact teh application's support team for more Information.* * * When i change the directory to c:\python26 and then enter it works ok. so can anyone tell me why this is happening? PS: I learn from Alan Gauld's response that windows defaults to python30 when i enter python because in the system variables python30 was entered first and I confirmed that that was true, but still python 30 doesn't process my code and python 31 crashes. My version of Python and Windows doesn't understand cp720. According to http://en.wikipedia.org/wiki/Code_page_720, it is a OEM Arabic code page. The Windows-equivalent is 'cp1256'. I have Python 2.6 and it doesn't have a codec for cp720, but does for cp1256. Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] on win32 Type help, copyright, credits or license for more information. u'abc'.encode('cp720') Traceback (most recent call last): File stdin, line 1, in module LookupError: unknown encoding: cp720 u'abc'.encode('cp1256') 'abc' If you are running on an Arabic version of Windows, you might change the console code page to 1256 and see if that works. Run 'chcp 1256' before running 'python'. -Mark ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Being beaten up by a tuple that's an integer thats a tuple that may be an unknown 'thing'.
Robert Berman berma...@cfl.rr.com wrote in message news:1257261606.29483.23.ca...@bermanrl-desktop... In [69]: l1=[(0,0)] * 4 In [70]: l1 Out[70]: [(0, 0), (0, 0), (0, 0), (0, 0)] In [71]: l1[2][0] Out[71]: 0 In [72]: l1[2][0] = 3 --- TypeError Traceback (most recent call last) /home/bermanrl/ipython console in module() TypeError: 'tuple' object does not support item assignment First question, is the error referring to the assignment (3) or the index [2][0]. I think it is the index but if that is the case why does l1[2][0] produce the value assigned to that location and not the same error message. Second question, I do know that l1[2] = 3,1 will work. Does this mean I must know the value of both items in l1[2] before I change either value. I guess the correct question is how do I change or set the value of l1[0][1] when I specifically mean the second item of an element of a 2D array? I have read numerous explanations of this problem thanks to Google; but no real explanation of setting of one element of the pair without setting the second element of the pair as well. Tuples are read-only, so you can't change just one element of a tuple: x=0,0 x (0, 0) x[0]=1 Traceback (most recent call last): File interactive input, line 1, in module TypeError: 'tuple' object does not support item assignment You can, however, replace the whole thing, as you found: x=1,1 x (1, 1) To do what you want, you a list of lists, not a list of tuples, but there is a gotcha. This syntax: L=[[0,0]]*4 L [[0, 0], [0, 0], [0, 0], [0, 0]] Produces a list of the *same* list object, so modifying one modifies all: L[2][0]=1 L [[1, 0], [1, 0], [1, 0], [1, 0]] Use a list comprehension to create lists of lists, where each list is a *new* list: L = [[0,0] for i in range(4)] L [[0, 0], [0, 0], [0, 0], [0, 0]] L[2][0] = 1 L [[0, 0], [0, 0], [1, 0], [0, 0]] -Mark ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Changing text colors on WinXP py2.6.2
Tim Golden m...@timgolden.me.uk wrote in message news:4ad471e6.7050...@timgolden.me.uk... Alan Gauld wrote: Tim Golden m...@timgolden.me.uk wrote No. ANSI escapes don't work on Windows. Wouldn't the ANSI codes work if ANSI.SYS were loaded? I thought you could still load ANSI.SYS it just wasn't normally there? The help system says you should load it in config.nt with: device=c:\winnt\system32\ansi.sys But I admit I've never tried it - I didn't even like ANSI.SYS when I was using DOS! (from memory). I'm fairly sure that even that no longer works. When this question last came up I think we went round that loop and discovered that it didn't. Happy to be wrong. :) That still works, but it only ever worked for command.com (the 16-bit command interpreter that still comes with Windows XP). A 16-bit DOS program or a batch file explicitly run under command.com can still use ANSI excapes. -Mark ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to perform variable assignment and
wesley chun wes...@gmail.com wrote in message [snip] ... however, there is a tiny bug: if the $HOME environment variable is *not* set, you will get a KeyError exception. one solution is to add a default value to your get() method call so that it returns an object with a Boolean False value: No KeyError. Default on missing is to return None. help(os.environ.get) Help on method get in module os: get(self, key, failobj=None) method of os._Environ instance -Mark ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how can I append a iteration to a tow dimensional array
Rayon evosw...@hotmail.com wrote in message news:bay122ds664a5c474fbf157089866c3...@phx.gbl... how can I append a iteration to a tow dimensional array so that one value can be like a key in a dir. It's unclear what behavior you are looking for, but there are a number of errors in your code below. Describe what you are trying to achieve. I can't use a directory because some of the values repeat and the dir throws them out. def getMark(record): for x in record.split(','): return str(x).strip() The for statement above will not iterate, but will return the first comma-delimited thing in record. str(x) is redundant. x will be a string already. What do you want this function to do? array = [] for x in bigMethod(): array.append(getMark(x)) array1=[] for count in array: array1 = [[count],[x]] for v in array1: print v What do you want this to do? -Mark ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] mapping/filtering a sequence
Douglas Philips d...@mac.com wrote in message news:6a3250c7-31b6-4958-8e0a-f538989ed...@mac.com... On or about 2009 Sep 5, at 10:45 AM, Martin A. Brown indited: Have you discovered the map() builtin yet? I would imagine that others on this list will have some even more elegant and efficient solutions for you, but here's a possibility: def filt_seq( thing ): if thing == 38: thing = thing - 4 elif thing == 40: thing = thing - 1 return thing l = [ 1, 17, 12, 38, 4, 40, 17, 19 ] l = map( filt_seq, l ) Good luck, I must have missed a message or two, because I don't understand why math is being done on constants like that. Given my misunderstanding, I'd go with: my_map = { 38: 34, 40: 39 } def filter_item(item): return my_map.get(item, item) l = [ ... ] l = map(filter_item, l) As a list comp: L=range(30,41) [{38:34,40:39}.get(n,n) for n in L] [30, 31, 32, 33, 34, 35, 36, 37, 34, 39, 39] -Mark ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What kind of number is this
Emad Nawfal (عماد نوفل) emadnaw...@gmail.com wrote in message news:652641e90907250514m1566287aq75f675fd63360...@mail.gmail.com... On 7/25/09, Dave Angel da...@ieee.org wrote: Emad Nawfal (9E'/ FHAD) wrote: Hi Tutors, I have a bunch of text files that have many occurrences like the following which I believe, given the context, are numbers: #1633;#1640;#1639;#1634; #1637;#1639; #1634;#1632;#1632;#1640; etc. So, can somebody please explain what kind of numbers these are, and how I can get the original numbers back. The files are in Arabic and were downloaded from an Arabic website. I'm running python2.6 on Ubuntu 9.04 Those are standard html encodings for some Unicode characters. [snip] You might find re.sub() useful to process your text files. It will replace the HTML encodings with the actual Unicode character. import re data = u#1633;#1640;#1639;#1634;#1637;#1639;#1634;#1632;#1632;#1640; s = re.sub(r'#(\d+);',lambda m: unichr(int(m.group(1))),data) s u'\u0661\u0668\u0667\u0662\u0665\u0667\u0662\u0660\u0660\u0668' print s 1872572008 And this can be helpful for identifying Unicode characters: import unicodedata for c in s: ... print unicodedata.name(c) ... ARABIC-INDIC DIGIT ONE ARABIC-INDIC DIGIT EIGHT ARABIC-INDIC DIGIT SEVEN ARABIC-INDIC DIGIT TWO ARABIC-INDIC DIGIT FIVE ARABIC-INDIC DIGIT SEVEN ARABIC-INDIC DIGIT TWO ARABIC-INDIC DIGIT ZERO ARABIC-INDIC DIGIT ZERO ARABIC-INDIC DIGIT EIGHT -Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] UnicodeEncodeError
gpo goodpotat...@yahoo.com wrote in message news:24554280.p...@talk.nabble.com... I'm doing a simple excercise in reading a file, and printing each line. However, I'm getting this error. The file is a windows txt file, ecoded in ANSI(ascii). I don't understand why Pythin is displaying a Unicode error. Here is my script: f=open('I:\\PythonScripts\\statement.txt') for line in f: print (line) f.close() statement.txt is just a copy of the text from an article at (http://www.tgdaily.com/content/view/43296/98/) into notepad. The error I get is: Traceback (most recent call last): File I:\PythonScripts\fileloop.py, line 9, in print (line) File C:\Python31\lib\encodings\cp437.py, line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_map)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\u2014' in position 10: character maps to I've looked this up, and see that others have had a similar error; however, I don't see any thing saying what I should be encoding to/from since my input and output files are both ascii. Notepad doesn't encode in ASCII. What it calls ANSI is the default file system encoding, which on US Windows is cp1252. I see you are using Python 3.1. When not given an explicit encoding, Python 3.1 defaults to the default file system encoding. It successfully reads the file, which happens to contain non-ASCII data. cp1252 supports the Unicode character \u2014 (EM DASH). However, when you try to print the file on the console, the console's default encoding is cp437 and doesn't support this character. On Python 3.1 there is a function, ascii(), that will display the contents of a string using ascii-only. Try print(ascii(line)). Another trick is to switch to Lucida Console font and change the console's code page to 1252 with the command chcp 1252. This font and code page supports the EM DASH and will display the text properly with print(line). You can also use a shell that supports the full Unicode character set such as Idle or PythonWin instead of the console. -Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] UnicodeEncodeError
Alan Gauld alan.ga...@btinternet.com wrote in message news:h407ah$lc...@ger.gmane.org... Mark Tolonen metolone+gm...@gmail.com wrote ... I see you are using Python 3.1. ... You can also use a shell that supports the full Unicode character set such as Idle or PythonWin instead of the console. As a matter of interest - and somewhat off topic - does anyone know if there is a Python 3 (3.0 or 3.1) version of Pythonwin out yet? Too lazy to look :-) Yes. PythonWin 214 is the latest version and supports 3.0 and 3.1. -Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] window graphics
David H. Burns dhbu...@cherokeetel.net wrote in message news:4a4d65e5.3040...@cherokeetel.net... Thanks, Alan, With the Python3.0, I have installed, he entry from tkinter import * doesn't produce any error message, but tk = TK() results in NameError: 'TK' is not defined. Also for the word canvas As you suggest, I probably need to start with a 2.x version. Python is case-sensitive. Try tk = Tk() and Canvas. -Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Need help with python game program
jonathan wallis mindboggle...@gmail.com wrote in message news:57b8984c0906301738w1fb0e660m6bb2123399f27...@mail.gmail.com... My problem is simple, is their a way to make a variable equal multiple numbers? Such as X = 5 through 10, and then the program makes x equal something random 5 through 10, or something similar. Use the random module. There are various types of random number generation there, such as: x = random.randint(5,10) -Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] About the vertical bar input
hyou hyo...@hotmail.com wrote in message news:blu143-ds478a37dc2b1db050e5b96c4...@phx.gbl... Hello, I'm trying to write a script that simply execute a command line like: C:\...(path)..\Devenv solution /build Debug|Win32 However, in Python the | symbol is reserved thus I just can't make the command line above working once I added the | sign in it. How can I put the original vertical bar in a string? Without an example of the code you are using, my guess is you are using os.system to execute a command on Windows. The Windows shell (cmd.exe) uses veritical bar for the pipe command, which sends output from one program into the input of another. The caret(^) is used in the Windows to escape special characters. Example: import os os.system('echo Hello|World') 'World' is not recognized as an internal or external command, operable program or batch file. 255 os.system('echo Hello^|World') Hello|World 0 -Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Writing a csv from a dictionary
Kent Johnson ken...@tds.net wrote in message news:1c2a2c590906230415q351c7c74kebc591907ce0e...@mail.gmail.com... On Tue, Jun 23, 2009 at 1:08 AM, Mark Tolonenmetolone+gm...@gmail.com wrote: import csv dyc = { 'a50' : ['textfield', 50, 40], 'k77' : ['othertext', 60, 10] } myfile = open('csv-test.csv', 'w') mywriter = csv.writer(myfile, dialect='excel') for k,[a,b,c] in dyc.items(): mywriter.writerow([k,a,b,c]) I think I would write this as for k, v in dyc.items(): # or iteritems() mywriter.writerow([k] + v) That way it doesn't depend on the actual size of the value list. I knew there was a more straightforward way, it just wouldn't come to me at 1am. ;^) -Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Writing a csv from a dictionary
Eduardo Vieira eduardo.su...@gmail.com wrote in message news:9356b9f30906221404o7a7c5e5dt3d59e7b6d40ac...@mail.gmail.com... Hello, I have a dictionary similar to this: dyc = { 'a50' : ['textfield', 50, 40], 'k77' : ['othertext', 60, 10] } I was trying to write a csv with the csv module, by doing this: import csv myfile = open('c:/myscripts/csv-test.csv', 'wb') mywriter = csv.writer(myfile, dialect='excel') for item in dyc: mywriter.write(item) myfile.close() this gives me this result: a50,['textfield', 50, 40] k77,['othertext', 60, 10] I would like this, instead: a50,textfield, 50, 40 k77,othertext, 60, 10 It's a good idea to cut-and-paste actual code and actual output. Your above code doesn't work. writerow is the correct method and for item in dyc.items(): is needed to iterate over keys and values correctly. import csv dyc = { 'a50' : ['textfield', 50, 40], 'k77' : ['othertext', 60, 10] } myfile = open('csv-test.csv', 'w') mywriter = csv.writer(myfile, dialect='excel') for k,[a,b,c] in dyc.items(): mywriter.writerow([k,a,b,c]) myfile.close() OUTPUT: a50,textfield,50,40 k77,othertext,60,10 If you want quoted text fields use: mywriter = csv.writer(myfile, dialect='excel',quoting=csv.QUOTE_NONNUMERIC) -Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Need better understanding of **kwargs
Eduardo Vieira eduardo.su...@gmail.com wrote in message news:9356b9f30906061044i4ded250fif3b387e64a117...@mail.gmail.com... Hello, I thought I understood **kwargs until I stumbled with this function: def changeflexion(myword, mytag, **dicty): global er_verbs global ar_verbs global ir_verbs #global dicty for item in dicty: if myword in item and mytag in item[1]: if dicty[item].endswith('ar'): ending = item[0].replace(dicty[item][:-2], ) try: return dicty[item][:-2] + ar_verbs[ending] except KeyError: return item[0] elif dicty[item].endswith('er'): ending = item[0].replace(dicty[item][:-2], ) try: return dicty[item][:-2] + er_verbs[ending] except KeyError: return item[0] elif dicty[item].endswith('ir'): ending = item[0].replace(dicty[item][:-2], ) try: return dicty[item][:-2] + ir_verbs[ending] except KeyError: return item[0] else: return item[0] but when I import the module and call: a = conjugate.changeflexion('estaban', 'VLFin', conjugate.mydict) I get this error: TypeError: changeflexion() takes exactly 2 arguments (3 given) Isn't the 3rd argument supposed to be a dictionary? No, **dicty means the function takes zero or more keyword parameters: def f(a,b,**k): ... print a,b,k ... f(1,2) # no keyword parameters 1 2 {} f(1,2,c=3) # one keyword parameter 1 2 {'c': 3} f(1,2,{'c':3}) # a dictionary Traceback (most recent call last): File interactive input, line 1, in module TypeError: f() takes exactly 2 arguments (3 given) But there is a syntax to pass keyword arguments as a dictionary: f(1,2,**{'c':3}) 1 2 {'c': 3} -Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unicode, utf-8 problem again
Dinesh B Vadhia dineshbvad...@hotmail.com wrote in message news:col103-ds25bb23a18e216061c32eb1a3...@phx.gbl... Hi! I'm processing a large number of xml files that are all declared as utf-8 encoded in the header ie. ?xml version=1.0 encoding=UTF-8? My Python environment has been set for 'utf-8' through site.py. It's a bad idea to change the encoding through site.py. Your script won't work on any other system. -Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Encode problem
Kent Johnson ken...@tds.net wrote in message news:1c2a2c590905050337j1afc177ene64f800dcc3a7...@mail.gmail.com... On Tue, May 5, 2009 at 1:14 AM, Mark Tolonen metolone+gm...@gmail.com wrote: The below works. ConfigParser isn't written to support Unicode correctly. I was able to get Unicode sections to write out, but it was just luck. Unicode keys and values break as the OP discovered. So treat everything as byte strings: Thanks for the complete example. files = glob.glob('*.txt') c.add_section('files') for i,fn in enumerate(files): fn = fn.decode(sys.getfilesystemencoding()) I think if you give a Unicode string to glob.glob(), e.g. glob.glob(u'*.txt'), then the strings returned will also be unicode and this decode step will not be needed. You're right, that's why I had the comment above it :^) # The following could be glob.glob(u'.') to get a filename in # Unicode, but this is for illustration that the encoding of the # source file has no bearing on the encoding strings other than # ones hard-coded in the source file. The OP had wondered why his source file encoding doesn't use the encoding defined for the application (# -*- coding: utf-8 -*-). and I thought this would illustrate that byte strings could be in other encodings. It also shows the reason spir could said ... you shouldn't even need explicit encoding; they should pass through silently because they fit in an 8 bit latin charset.. If I'd left out the Chinese, I could've use a latin-1 encoding for everthing and not decode or encode at all (assuming the file system was latin-1). -Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] quick question to open(filename, 'r') vs. file(filename, 'r')
W W sri...@gmail.com wrote in message news:333efb450905050408m48246dd8wc90b94880898e...@mail.gmail.com... On Tue, May 5, 2009 at 5:41 AM, spir denis.s...@free.fr wrote: Le Tue, 5 May 2009 00:41:39 +0100, Alan Gauld alan.ga...@btinternet.com s'exprima ainsi: Backwards compatibility. The file type was introduced in python 2.2, before which there was open. And file has been removed again in Python v3 In fact open is now an alias for io.open and no longer simply returns a file object - in fact the file type itself is gone too! I, for one, am glad it is gone again. It took awhile to train myself not to write: file = open('filename.txt') and incorrectly shadow the built-in. It's just the most natural name for the variable :^) -Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Encode problem
spir denis.s...@free.fr wrote in message news:20090501220601.31891...@o... Le Fri, 1 May 2009 15:19:29 -0300, Pablo P. F. de Faria pablofa...@gmail.com s'exprima ainsi: self.cfg.write(codecs.open(self.properties_file,'w','utf-8')) As one can see, the character encoding is explicitly UTF-8. But ConfigParser keeps trying to save it as a 'ascii' file and gives me error for directory-names containing 128 code characters (like Á). It is just a horrible thing to me, for my app will be used mostly by brazillians. Just superficial suggestions, only because it's 1st of May and WE so that better answers won't maybe come up before monday. If all what you describe is right, then there must be something wrong with char encoding in configParser's write method. Have you had a look at it? While I hardly imagine why/how ConfigParser would limit file pathes to 7-bit ASCII... Also, for porteguese characters, you shouldn't even need explicit encoding; they should pass through silently because they fit in an 8 bit latin charset. (I never encode french path/file names.) The below works. ConfigParser isn't written to support Unicode correctly. I was able to get Unicode sections to write out, but it was just luck. Unicode keys and values break as the OP discovered. So treat everything as byte strings: # coding: utf-8 # Note coding is required because of non-ascii # in the source code. This ONLY controls the # encoding of the source file characters saved to disk. import ConfigParser import glob import sys c = ConfigParser.ConfigParser() c.add_section('马克') # this is a utf-8 encoded byte string...no u'') c.set('马克','多少','明白') # so are these # The following could be glob.glob(u'.') to get a filename in # Unicode, but this is for illustration that the encoding of the # source file has no bearing on the encoding strings other than # one's hard-coded in the source file. The 'files' list will be byte # strings in the default file system encoding. Which for Windows # is 'mbcs'...a magic value that changes depending on the # which country's version of Windows is running. files = glob.glob('*.txt') c.add_section('files') for i,fn in enumerate(files): fn = fn.decode(sys.getfilesystemencoding()) fn = fn.encode('utf-8') c.set('files','file%d'%(i+1),fn) # Don't need a codec here...everything is already UTF8. c.write(open('chinese.txt','wt')) -- Here is the content of my utf-8 file: - [files] file3 = ascii.txt file2 = chinese.txt file1 = blah.txt file5 = ÀÈÌÒÙ.txt file4 = other.txt [马克] 多少 = 明白 Hope this helps, Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Optional groups in RE's
Moos Heintzen iwasr...@gmail.com wrote in message news:7b13ba330904111546n21d90202i7572a75c55b02...@mail.gmail.com... Hello Tutors! I was trying to make some groups optional in a regular expression, but I couldn't do it. For example, I have the string: data = price42/price sdlfks d fship60/ship sdf sdf titleTitle/title [ re attempts stripped] Your data looks like XML. If it is actually well-formed XML, have you tried ElementTree? PythonWin 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32. Portions Copyright 1994-2008 Mark Hammond - see 'Help/About PythonWin' for further copyright information. from xml.etree import ElementTree as ET data = objectprice42/price sdlfks d fship60/ship sdf sdf titleTitle/title/object t=ET.fromstring(data) t.tag 'object' for e in t.getchildren(): ... print e.tag,e.text ... price 42 ship 60 title Title -Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Please use plain text.
Signature.htmlI normally reply in whatever the original poster uses, because when I convert HTML to plain text it removes all the attribution indentation, making it difficult to tell who wrote what (see below...I converted this post back to plain text). HTML is generally painful to read unless your editor completely supports editing in it (mine doesn't), so I second the motion to post only plain text. -Mark Wayne Watson sierra_mtnv...@sbcglobal.net wrote in message news:49dad279.2000...@sbcglobal.net... That's strange--tiny image below. I use SeaMonkey, and it seems to be almost identical to Tbird. I tend to use html for my signature. I'm not sure what someone did to produce the tiny print below. Ah, I see, they apparently grabbed the image, and inserted it. When I grab images with SnagIt, I have the text size set to something much more reasonable than I see here. Maybe someone has exceptionally good eyes. Occasionally, when I print, e-mail, not my own, I get tiny letters. That's solvable (Win XP) by pumping up the size in Print Preview. I still find it odd, and it seems to happen randomly. bob gailer wrote: Wayne Watson wrote: I'm curious about this request. What mail reader are you using that causes the problem? I use Thunderbird. It is not the cause of the problem. It renders emails exactly as formatted by the sender. The specific example I was reacting to was this morning 1:08 AM: Re: [Tutor] Formatting zip module arguments correctly metolone+gm...@gmail.com In hopes that you can see graphics, here is an extract: [snip] -- Bob Gailer Chapel Hill NC 919-636-4239 -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time) Less than all cannot satisfy Man. -- William Blake ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Formatting zip module arguments correctly
The error indicates your source file cannot be read. Did you have it open in an editor that locks it for exclusive use when you ran your program? Also, the command: zipfile.ZipFile(target, 'w').write(source) writes backup_list to the target zipfile, and returns None, assigning the return value to zip_command and passing that to os.system makes no sense. The command above will throw an exception if anything goes wrong (as you found), so the following code is probably what you want: try: zipfile.ZipFile(target, 'w').write(source) except IOError: print('Backup Failed') else: print('Successful backup to',target) -Mark Benjamin Serrato benjamin.serr...@gmail.com wrote in message news:dde7cc5d0904051354v1c103fb2wf28f182734970...@mail.gmail.com... Please tell me why this code fails. I am new and I don't understand why my formatting of my zip arguments is incorrect. Since I am unsure how to communicate best so I will show the code, the error message, and what I believe is happening. #!c:\python30# Filename: backup_ver5.pyimport osimport time import zipfilesource = r'C:\Documents and Settings\Benjamin Serrato\My Documents\python\backup_list'target_dir = r'C:\Documents and Settings\Benjamin Serrato\My Documents\python\backup_dir' today = target_dir + os.sep + time.strftime('%Y%m%d') now = time.strftime('%H%M%S')comment = input('Enter a comment -- ')if len(comment) == 0: target = today + os.sep + now + '.zip' else: target = today + os.sep + now + '_' + \ comment.replace(' ', '_') + '.zip'if not os.path.exists(today): os.mkdir(today) print('Successfully created directory', today) print(target)print(source)zip_command = zipfile.ZipFile(target, 'w').write(source)if os.system(zip_command) == 0: print('Successful backup to', target)else: print('Backup FAILED') I receive this error message: Enter a comment -- C:\Documents and Settings\Benjamin Serrato\My Documents\python\backup_dir\200904 05\154956.zip C:\Documents and Settings\Benjamin Serrato\My Documents\python\backup_list Traceback (most recent call last): File C:\Documents and Settings\Benjamin Serrato\My Documents\python\backup_ve r5.py, line 32, in module zip_command = zipfile.ZipFile(target, 'w').write(source) File c:\python30\lib\zipfile.py, line 1031, in write fp = io.open(filename, rb) File C:\Python30\lib\io.py, line 222, in open closefd) File C:\Python30\lib\io.py, line 615, in __init__ _fileio._FileIO.__init__(self, name, mode, closefd) IOError: [Errno 13] Permission denied: 'C:\\Documents and Settings\\Benjamin Ser rato\\My Documents\\python\\backup_list' The two print tests before zip_command is assigned tell me that the two strings are being passed to zipfile.ZipFile() correctly. The traceback tells me I am not calling zipfile.ZipFile() correctly. The error in __init__ makes me more sure of this. Last, the problem seems to be that I am causing my path string to have double backslashes. I can't follow why the IOError shows that. I used this site to figure out how to use zipfile. zipfile is a class, I import it at the start of the program then I use it and its primary method. I pass the file I would like to write to zipfile.ZipFile('file to write', 'mode') and set the program to open an object set to be writable. Then the command writes the file to the destination folder with a sub-method like so, .zipfile('files to write'). Where am I going wrong? -- ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how are unicode chars represented?
Kent Johnson ken...@tds.net wrote in message news:1c2a2c590903310357m682e16acr9d94b12b60993...@mail.gmail.com... On Tue, Mar 31, 2009 at 1:52 AM, Mark Tolonen metolone+gm...@gmail.com wrote: Unicode is simply code points. How the code points are represented internally is another matter. The below code is from a 16-bit Unicode build of Python but should look exactly the same on a 32-bit Unicode build; however, the internal representation is different. Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32 Type help, copyright, credits or license for more information. x=u'\U00012345' x.encode('utf8') '\xf0\x92\x8d\x85' However, I wonder if this should be considered a bug. I would think the length of a Unicode string should be the number of code points in the string, which for my string above should be 1. Anyone have a 32-bit Unicode build of Python handy? This exposes the implementation as UTF-16. len(x) 2 x[0] u'\ud808' x[1] u'\udf45' In standard Python the representation of unicode is 16 bits, without correct handling of surrogate pairs (which is what your string contains). I think this is called UCS-2, not UTF-16. There is a a compile switch to enable 32-bit representation of unicode. See PEP 261 and the Internal Representation section of the second link below for more details. http://www.python.org/dev/peps/pep-0261/ http://www.cmlenz.net/archives/2008/07/the-truth-about-unicode-in-python Kent My string above is UTF-16 because it *does* handle surrogate pairs. See http://en.wikipedia.org/wiki/UTF-16. UCS-2 (2-byte Universal Character Set) is an obsolete character encoding which is a predecessor to UTF-16. The UCS-2 encoding form is identical to that of UTF-16, except that it *does not* support surrogate pairs The single character \U00012345 was stored by Python as the surrogate pair \ud808\udf45 and was correctly encoded as the 4-byte UTF-8 '\xf0\x92\x8d\x85' in my example. Also, Because of the technical similarities and upwards compatibility from UCS-2 to UTF-16, the two encodings are often erroneously conflated and used as if interchangeable, so that strings encoded in UTF-16 are sometimes misidentified as being encoded in UCS-2. Python isn't strictly UCS-2 anymore, but it doesn't completely implement UTF-16 either, since string functions return incorrect results for characters outside the BMP. -Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how are unicode chars represented?
Kent Johnson ken...@tds.net wrote in message news:1c2a2c590903300352t2bd3f1a7j5f37703cf1c3...@mail.gmail.com... On Mon, Mar 30, 2009 at 3:36 AM, spir denis.s...@free.fr wrote: Everything is in the title ;-) (Is it kind of integers representing the code point?) Unicode is represented as 16-bit integers. I'm not sure, but I don't think Python has support for surrogate pairs, i.e. characters outside the BMP. Unicode is simply code points. How the code points are represented internally is another matter. The below code is from a 16-bit Unicode build of Python but should look exactly the same on a 32-bit Unicode build; however, the internal representation is different. Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32 Type help, copyright, credits or license for more information. x=u'\U00012345' x.encode('utf8') '\xf0\x92\x8d\x85' However, I wonder if this should be considered a bug. I would think the length of a Unicode string should be the number of code points in the string, which for my string above should be 1. Anyone have a 32-bit Unicode build of Python handy? This exposes the implementation as UTF-16. len(x) 2 x[0] u'\ud808' x[1] u'\udf45' -Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Opening a cmd.exe
Tim Golden m...@timgolden.me.uk wrote in message news:49c65068.2080...@timgolden.me.uk... Tim Golden wrote: Alan Gauld wrote: Sigga Sig sigridur...@ru.is wrote I am writing a code that is supoesed to act as routers and i need to open a different cmd window for each one of them with it's name and so on. I do not know how to implement in mi Python cod a sentece that opens such a cmd. I know how to open a cmd.exe bud not with specific attributes that are needed. Does this do what you want? It creates a new cmd window titled Dir, then executes some commands. If you want the window to stay open after executing the commands, use /k instead of /c. 'cmd /?' gives other switches you might want. The escaping(^) of the ampersands() is required or the commands will run in the current console not the new one. import os os.system('start cmd /c title Dir ^^ dir ^^ pause') -Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] irregular/parse/sort
su...@aol.com wrote in message news:d08.50baad3e.36f80...@aol.com... I've been using re.sub() to try and take the below pattern1 and convert it to pattern2 (which are below) below that is mycode1. Does anyone have any suggestions as to how I can figure this out? pattern1 NTR+A0001 0.01 GLU-A0003 8.21 GLU-A0008 3.619 ARG+A0010 14 [snip lots of data] pattern2 pKaRes NTR 1 A,value= 0.01 pKaRes GLU 3 A,value= 8.21 pKaRes GLU 8 A,value= 3.619 pKaRes ARG 10 A,value= 14 Since everything appears to be in a fixed column, given a single line from above, this will convert it (no re required): print 'pKaRes %s %d %s,value= %s' % (line[:3],int(line[5:9]),line[4],line[10:]) -Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] TypeError: dict objects are unhashable
qsqgeekyog...@tiscali.co.uk wrote in message news:16014207.1237036582618.javamail.r...@ps26... hi, i have a list which contains duplicate dictionaries. how do i extract the unique items out? l1 = [{'a': 'ddd'}, {'a': 'ddd'}, {'b': 'eee'}, {'c': 'ggg'}] set(l1) TypeError: dict objects are unhashable but, {'a': 'ddd'} == {'a': 'ddd'} True How about: l1 = [{'a': 'ddd'}, {'a': 'ddd'}, {'b': 'eee'}, {'c': 'ggg'}] [dict(n) for n in set(tuple(n.items()) for n in l1)] [{'c': 'ggg'}, {'b': 'eee'}, {'a': 'ddd'}] -Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] new print statement + time module
spir denis.s...@free.fr wrote in message news:20090228081629.36a24...@o... Le Sat, 28 Feb 2009 06:34:07 +0200, George Wahid geoter...@gmail.com s'exprima ainsi: I downloaded python 3.0.1 today and started experimenting with the new print statement. import time for l in 'the answer': ...print(l,end='') ...time.sleep(0.1) the code is supposed to print the answer with a 0.1 second long pause between the letters. instead, it waits for 1 second ( 0.1*len(the answer) seconds ) and then prints the answer. what am I doing wrong ? Indeed, it does the same for me with python 2.5: from time import sleep for c in 1234567890: sleep(0.25) print c, I guess python underlying outputs are managed like a queue that is flushed at certain points, eg whan a newline comes. Already noticed weird outputs messing up ordinary prints (~ sys.stdout) and exceptions messages (sys.stderr). I'd like to know more about that. both replacing print(l,end='') with print(l) or using the msvcrt module instead of the print function work fine. The same with py2.5. Without the ',', all is fine. Maybe there is a trick to force python printing ot in due time, but I have no idea, sorry. stdout is line-buffered. Here's the trick: import time import sys for l in 'the answer': print(l,end='') sys.stdout.flush() time.sleep(0.1) -Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Removing control characters
A regex isn't always the best solution: a=''.join(chr(n) for n in range(256)) a '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !#$%\'()*+,-./0123456789:;=?...@abcdefghijklmnopqrstuvwxyz[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff' b=''.join(n for n in a if ord(n) = 32 and ord(n) = 126) b ' !#$%\'()*+,-./0123456789:;=?...@abcdefghijklmnopqrstuvwxyz[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~' -Mark Dinesh B Vadhia dineshbvad...@hotmail.com wrote in message news:col103-ds55714842811febeb4a97ca3...@phx.gbl... I want a regex to remove control characters ( chr(32) and chr(126)) from strings ie. line = re.sub(r[^a-z0-9-';.], , line) # replace all chars NOT A-Z, a-z, 0-9, [-';.] with 1. What is the best way to include all the required chars rather than list them all within the r ? 2. How do you handle the inclusion of the quotation mark ? Cheers Dinesh -- ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Removing control characters
Kent Johnson ken...@tds.net wrote in message news:1c2a2c590902191500y71600feerff0b73a88fb49...@mail.gmail.com... On Thu, Feb 19, 2009 at 5:41 PM, Dinesh B Vadhia dineshbvad...@hotmail.com wrote: Okay, here is a combination of Mark's suggestions and yours: # replace unwanted chars in string s with t = .join([( if n in c else n) for n in s if n not in c]) t 'Product ConceptsHard candy with an innovative twist, Internet Archive: Wayback Machine. [online] Mar. 25, 2004. Retrieved from the Internet URL: http://www.confectionery-innovations.com.' This last bit doesn't work ie. replacing the unwanted chars with - eg. 'ConceptsHard'. What's missing? The if n not in c at the end of the list comp rejects the unwanted characters from the result immediately. What you wrote is the same as t = .join([n for n in s if n not in c]) because n in c will never be true in the first conditional. BTW if you care about performance, this is the wrong approach. At least use a set for c; better would be to use translate(). Sorry, I didn't catch the replace with space part. Kent is right, translate is what you want. The join is still nice for making the translation table: table = ''.join(' ' if n 32 or n 126 else chr(n) for n in xrange(256)) string.translate('here is\x01my\xffstring',table) 'here is my string' -Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] dict() versus {}
This: dict(one=1,two=2,three=3) {'three': 3, 'two': 2, 'one': 1} Is a shortcut for the longer: dict((('one',1),('two',2),('three',3))) {'three': 3, 'two': 2, 'one': 1} and given how this works: def function(**kwargs): ... print kwargs ... function(one=1,two=2,three=3) {'three': 3, 'two': 2, 'one': 1} One can guess how the shortcut is implemented. -Mark wormwood_3 wormwoo...@yahoo.com wrote in message news:454349.94041...@web110811.mail.gq1.yahoo.com... dict( [arg]) Return a new dictionary initialized from an optional positional argument or from a set of keyword arguments. If no arguments are given, return a new empty dictionary. If the positional argument arg is a mapping object, return a dictionary mapping the same keys to the same values as does the mapping object. But why doesn't the optional positional argument arg in this case, not being a mapping type, get evaluated?: dict(thing=1) And even if it makes sense for it not to be evaluated, wouldn't it be better for dict() to complain that it didn't get a string or an int as it expects for a keyword argument? Maybe I am missing the use case, so far it just seems strange to force the keyword to a string. -Sam -- From: bob gailer bgai...@g mail.com To: wormwood_3 wormwoo...@yahoo.com Cc: Python Tutorlist tutor@python.org Sent: Wednesday, January 21, 2009 11:25:12 PM Subject: Re: [Tutor] dict() versus {} wormwood_3 wrote: Hmm, looked through the latest docs, in the sections on dictionary types, don't see examples that point to this case well. Can you link to what you had in mind? 2.1 Built-in Functions ... dict( [mapping-or-sequence]) ... these all return a dictionary equal to {one: 2, two: 3}: ... dict(one=2, two=3) From: bob gailer bgai...@gmail.com To: wormwood_3 wormwoo...@yahoo.com Cc: Python Tutorlist tutor@python.org Sent: Wednesday, January 21, 2009 11:02:35 PM Subject: Re: [Tutor] dict() versus {} wormwood_3 wrote: When creating a list of dictionaries through a loop, I ran into a strange issue. I'll let the code talk: l = 'i am a special new list'.split() t = [] for thing in l: ... t.append({thing: 1}) ... t [{'i': 1}, {'am': 1}, {'a': 1}, {'special': 1}, {'new': 1}, {'list': 1}] This is what I expected. {} says to make a dictionary. Thing, not being quoted, is clearing a variable, which needs to be evaluated and used as the key. t = [] for thing in l: ... t.append(dict(thing=1)) ... t [{'thing': 1}, {'thing': 1}, {'thing': 1}, {'thing': 1}, {'thing': 1}, {'thing': 1}] This was what threw me. Why would the dict() function not evaluate thing? How can it take it as a literal string without quotes? I suggest you look dict up in the Python documentation. There it shows the result you got as an example. When in doubt read the manual. -- Bob Gailer Chapel Hill NC 919-636-4239 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Bob Gailer Chapel Hill NC 919-636-4239 -- ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Concerning Programming Exercise #6 of Chapter 2 of Python Programming John Zelle Textbook
Since you are updating the principal value each year, use the following to grow the principal by the interest rate each year: principal = principal * (1 + apr) -Mark bob gailer bgai...@gmail.com wrote in message news:49761fdc.5020...@gmail.com... Donna Belle Ibarra wrote: Hi! I need help with program exericse #6 entitled Futval.py which is a program that computes the value of an investment carried 10 years into the future. This is the coding I have.. yet it does not seem to spit out the correct numbers (Am I using an incorrect equation?) Take a look at http://en.wikipedia.org/wiki/Time_value_of_money#Present_value_of_a_future_sum for the various formulas. I am not sure which applies in your case. def main(): print This program calculates the future value print of a 10-year investment. principal = input(Enter the amount invested each year: ) apr = input(Enter the annual interest rate: ) years = input(Enter the number of years: ) for i in range (1, years + 1): principal = principal * (1 + apr)**i print The value in, i, years is:, principal main() The output is suppose to appear like this: This program calculates the future value of a 10-year investment. Enter the amount invested each year: 100.00 Enter the annual interst rate: 0.05 Enter the number of years: 10 The value in 1 years is 105.0 The value in 2 years is 215.25 The value in 3 years is 331.0125 The value in 4 years is 452.563125 And so on.. ^Please help me!!! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Bob Gailer Chapel Hill NC 919-636-4239 -- ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Date comparison across time zones
frenc1z 1z fren...@gmail.com wrote in message news:7b60d8a80901130845s30842deeuba55afec99285...@mail.gmail.com... Hello, I'm a novice python (python 2.6.1) user with the following problem. Never though this was going to be so difficult :-). I would like to compare some dates (date+time really). The dates all have the following RFC2822 format: Eg. is d1 d2? d1 = Tue, 13 Jan 2009 03:27:29 -0800 d2 = Tue, 13 Jan 2009 02:40:00 -0600 Check out the email.utils module, specifically the parsedate_tz and mktime_tz functions. -Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Deleting recursive folder definition
Alan Gauld alan.ga...@freenet.co.uk wrote in message news:50c11a8b9db748fa9e6e892067cce...@xp... I've managed to do something incredibly stupid on my XP box. I've created a folder that is a link to itself - at least I think that's what has happened, it was a CASE tool that I was using that actually did the damage. The symptoms are that I can infinitely navigate down to the next level. I can also delete as many folders as I like but the top level properties still report 232 folders... Also I get error messages on the defective folder saying the filename(ie path) is too long. I've tried using Cygwin rm, I've tried renaming the folder to a shorter name., I've tried using the DOS DEL command. My last resort is to try to write a program to do it, but how? Does anyone know enough about Windows filesystem (NTFS) to know which API calls etc I would need? Or is there a better solution? I'm not even sure this approach will work since it will just recurse to inifinity too I suspect! The MSDN and Knowledge Base don't seem to offer any advice either... Any ideas? It sounds as if you've created an NTFS junction point. The XP Help topic shows 3 utilities that may help: Microsoft offers three utilities for creating and manipulating NTFS junction points: Linkd.exe a.. Grafts any target folder onto a Windows 2000 version of NTFS folder b.. Displays the target of an NTFS junction point c.. Deletes NTFS junction points that are created with Linkd.exe d.. Location: Microsoft Windows 2000 Resource Kit Mountvol.exe a.. Grafts the root folder of a local volume onto a Windows 2000 version of NTFS folder (or mounts the volume) b.. Displays the target of an NTFS junction point that is used to mount a volume c.. Lists the local file system volumes that are available for use d.. Deletes the volume mount points that are created with mountvol.exe e.. Location: Windows 2000 CD-ROM in the I386 folder Delrp.exe a.. Deletes NTFS junction points b.. Also deletes other types of reparse points, which are the entities that underlie junction points c.. Aimed primarily at developers who create reparse points d.. Location: Microsoft Windows 2000 Resource Kit Linkd or Delrp sound like what you may need. If you want to fix the problem programmatically, try looking up: DeviceIoControl FSCTL_GET_REPARSE_POINT FSCTL_DELETE_REPARSE_POINT FSCTL_SET_REPARSE_POINT -Mark -Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Better way - fnmatch with list ? CORRECTION
Damon Timm damont...@gmail.com wrote in message news:262679b50901031327n23b2f754l62fe0cf98751c...@mail.gmail.com... On Fri, Jan 2, 2009 at 7:16 PM, Jervis Whitley jervi...@gmail.com wrote: for fn in files: base, ext = os.path.splitext(fn) if ext.lower() in ['.flac', '.mp3', '.mp4']: takes into account systems with case sensitive filenames. Thanks! Will throw that in there. I'm getting it ... bit by little bit. fnmatch already takes into account systems with case-sensitive filenames: help(fnmatch.fnmatch) Help on function fnmatch in module fnmatch: fnmatch(name, pat) Test whether FILENAME matches PATTERN. Patterns are Unix shell style: * matches everything ? matches any single character [seq] matches any character in seq [!seq] matches any char not in seq An initial period in FILENAME is not special. Both FILENAME and PATTERN are first case-normalized if the operating system requires it. If you don't want this, use fnmatchcase(FILENAME, PATTERN). -Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] to sort
prasad rao prasadarao...@gmail.com wrote in message news:9e3fac840812252221pe3345bam7e3e3563e050c...@mail.gmail.com... hello I am trying to sort a list(I know there is a builtin sort method). a=[21,56,35,47,94,12] b=[] for x in a: b.append (min(a)) a.remove (min(a)) a [56, 47, 94] b [12, 21, 35] It is not Compleating .Doing only 3 rounds.Why? You should not change a list while iterating over it. Instead, iterate until a is empty: a=[21,56,35,47,94,12] b=[] while a: ...b.append(min(a)) ...a.remove(min(a)) ... a [] b [12, 21, 35, 47, 56, 94] -Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Reading module to import from a string
Shrutarshi Basu technorapt...@gmail.com wrote in message news:376fbdcf0812151438w53c8f3f7rc1dc481b52428...@mail.gmail.com... Suppose I have a module that I want to import called ImMod1 that's saved in a variable like so: var = ImMod1 Is there some way to import ImMod1 by using var? Thanks, Basu mod = __import__(var) -Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Working with lists
btk...@email.unc.edu wrote in message news:20081213095244.n4clmwk3k4gkg...@webmail4.isis.unc.edu... Hi everyone, I seem to use this pattern alot when writing functions and I'm wondering if there is a more efficient method. It comes up whenever I want to work with more than one item in a list; for instance, say I want to add each consecutive number in alist and output the new list. Ideally, I'd be able to write: for num in list1: newlist.append(num+nextnum) This doesn't work, though because there's no way to access nextnum unless I implement a count variable like this: count=1 for num in list1: newlist.append(num+list1[count]) count+=1 Instead, it usually ends up easier to write: for index in range (len(list1)-1): newlist.append((list1[index]+list1[index+1])) It's not a big deal to have to write the additional code, but problems arise when I use this structure in the context of more complex functions, when I am passing multiple lists of varying length, because it is easy to get confused with the index numbers and I can't do anything to the last value of the list, since I then get an indexerror because the function tries to call list[i+1]. Is there a simpler way to do a procedure like this? From your description, do you want: L = [1,2,3,4,5,6] result = [3,5,6,9,11]? I don't see anything in itertools, but this works: def ishift(L,n): ... for i in xrange(len(L)-n+1): ... yield L[i:i+n] ... for n in shift(L,2): ... print n ... [1, 2] [2, 3] [3, 4] [4, 5] [5, 6] for a,b,c in shift(L,3): ... print a,b,c ... 1 2 3 2 3 4 3 4 5 4 5 6 [sum(n) for n in ishift(L,2)] [3, 5, 7, 9, 11] [sum(n) for n in ishift(L,3)] [6, 9, 12, 15] -Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] accessing list from a string
Bryan Fodness [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] I have a list in a text file that is in the python format., Positions = [2.5,2.8] and would like to grab the values. for line in file('list.txt'): if line == Positions: x1,x2=Positions I know this does not work. Is there a direct way to get my x1 and x2 values. line = '[2.5,2.8]' x1,x2 = eval(line) x1,x2 (2.5, 2.7998) -Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] extend my re
Ricardo Aráoz [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Hi, I've got a half working re but I can't find a way to give it the final touch. Let's say I have (it would actually be source code file) : import re MyString = Algo ... Start ... otro ... comment ... otro ... comment ... comment ... otro ... end ... MyPattern = re.compile(r'(.*?Start.*?)((comment.*?)*)(comment)(.*?end)', re.S) print MyString Algo Start otro comment otro comment comment otro end print MyPattern.sub(r'\1\2/*\4*/\5', MyString) Algo Start otro comment otro comment /*comment*/ otro end Which is basically ok. I have to find the last comment in the block and comment it. But I'd like to comment the whole line, my desired output would be : Algo Start otro comment otro comment /*comment*/ otro end And if there was something after the comment I would also like it to be commented : from: comment and something else to : /* comment and something else*/ any help? A quick attempt that works for your example: MyPattern = re.compile(r'(.*?Start.*?)((\n\s*comment.*?)*\n)(\s*comment.*?)(\n.*?end)', re.S) You might look into something like pyparsing instead of a complicated re. -Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] List of lists help
Alan Gauld [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] [snip] Something like L = [[0,0,0] *3] I think you meant: [[0,0,0]]*3 [[0, 0, 0], [0, 0, 0], [0, 0, 0]] -Mark Now L contains 3 copies of the same list so when you change any one copy it is reflected in all of the other copies. L[0][1] = 6 L [[0,6,0],[0,6,0],[0,6,0]] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] appending to a utf-16 encoded text file
Tim Golden [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Tim Brown wrote: Hi, I'm trying to create and append unicode strings to a utf-16 text file. The best I could come up with was to use codecs.open() with an encoding of 'utf-16' but when I do an append I get another UTF16 BOM put into the file which other programs do not expect to see :-( Is there some way to stop codecs from doing this or is there a better way to create and add data to a utf-16 text file? Well, there's nothing to stop you opening it raw, as it were, and just appending unicode encoded as utf16. code s = uThe cat sat on the mat f = open (utf16.txt, wb) for word in s.split (): f.write (word.encode (utf16) + ) f.close () /code TJG Result: The@揾愀琀 sat@濾渀 the@淾愀琀 word.encode('utf16') adds a BOM every time, and the space wasn't encoded. utf-16-le and utf-16-be don't add the BOM. This works: import codecs s = uThe cat sat on the mat f = codecs.open(utf16.txt,wb,utf-16-le) f.write(u'\ufeff') # if you want the BOM for word in s.split (): f.write (word + u' ') f.close() -Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Edit a Word document programmatically
These two lines connect to Word. The EnsureDispatch makes sure Word constants work later: import win32com.client word = win32com.client.gencache.EnsureDispatch('Word.Application') Then record a Word macro to do what you want (this was a find/replace all): Selection.Find.ClearFormatting Selection.Find.Replacement.ClearFormatting With Selection.Find .Text = fox .Replacement.Text = cat .Forward = True .Wrap = wdFindContinue .Format = False .MatchCase = False .MatchWholeWord = False .MatchByte = False .MatchWildcards = False .MatchSoundsLike = False .MatchAllWordForms = False End With Selection.Find.Execute Replace:=wdReplaceAll Then translate to Python: find = word.Selection.Find find.ClearFormatting() find.Replacement.ClearFormatting() find.Text = 'fox' find.Replacement.Text = 'cat' find.Forward = True find.Wrap = win32com.client.constants.wdFindContinue find.Execute(Replace=win32com.client.constants.wdReplaceAll) True -Mark URBAN LANDREMAN [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Good morning, I'm trying to write some Python code to programmatically do a Find and Replace of a string within a Microsoft Word document. Any suggestions on where I could look to find how to do such a function? Thank you. Urban Landreman -- ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Downloading Files from the net
Timo [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] What is the best/correct way to download files from a webpage? www.example.com/example.mp3 for instance. I know how to open the site (with urllib), but have no idea how to write the file to the harddisk. Quick and dirty, if example.mp3 isn't too big to fit in memory at once: import urllib fin = urllib.urlopen('http://www.example.com/example.mp3') fout = open('example.mp3','wb') fout.write(fin.read()) fin.close() fout.close() -Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python regex help
Arun Tomar [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] On Sun, 2008-09-28 at 17:26 +0100, Alan Gauld wrote: Arun Tomar [EMAIL PROTECTED] wrote I've been using shell scripting using sed pipes i've solved it, but with python, i need to practice more ;). ok, i got it. here is the code that needs to be included after code in the last mail ;) sub1 = (-.*)|(Tel:)|\(M\)|\(R\) new_reg = re.compile(sub1) for n in range(len(new_array)): mod_array.append(new_reg.sub('',new_array[n])) Given your original data, this should work: -cut data = '''\ Contact Candidate Jyoti Soni - 0 Year(s) 0 Month(s) MCA Keyskills: C , C + + , Java , JSP , Oracle , S / W Testing B.Sc Pt.Ravishanker University,Raipur MCA Pt.Ravishanker University,Raipur Currently in: Pune CTC(p.a): Not Disclosed Modified: 27 Sep 2007 Tel: 09975610476(M) Account Information Account Information Contact Candidate Minal - 0 Year(s) 0 Month(s) MCA Keyskills: c , c + + , java , ASP . NET , VB , Oracle , Dimploma in Web Designing B.Sc Shivaji University , Maharasthra MCA Shivaji University , Maharashtra Currently in: Pune CTC(p.a): INR 0 Lac(s) 5 Thousand Modified: 27 Jan 2006 Last Active: 06 Sep 2007 Tel: 9890498376(M) 011 02162 250553(R) Account Information Account Information ''' import re record = re.compile(r'(?ms)Contact Candidate\s*\n(.*?) -.*?\nTel: (\d+)') print record.findall(data) --cut Output: [('Jyoti Soni', '09975610476'), ('Minal', '9890498376')] -Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] print the hole unicode list
Yang [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Hello, I am trying to print out the hole unicode char list in window! form 0-65535. I use the winxp in simple chinese LOCAL! the ascii form 0-127 and CJK chars form 0X4E00-0X9FA4 can be print out! Other ucode chars case this error UnicodeEncodeError: 'gbk' codec can't encode character u'\u9fa6' in position 0 my code is here: for i in range(0,65536 ): uchar=unicode(\u%04X%i,unicode-escape) print %x :%i,uchar how can I achive a hole unicode list? Or can it be done? Your console encoding is 'gbk', which can't display all the Unicode characters. The following code can be used to generate all the characters into a file using an encoding that supports all Unicode characters, and then that file can be viewed in a program that supports the encoding (like Notepad for this example). Still, what characters you see will depend on the font used. Fonts generally do not support display of every Unicode character. import codecs f=codecs.open('unicode.txt','wt',encoding='utf-8') for i in xrange(32,0x1): # skip control chars if i 0xD800 or i 0xDFFF: # skip surrogate pair chars f.write(u'%04X: %s\t' % (i,unichr(i))) f.close() -Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Raw string
Neven Gorsic [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] On Mon, Jul 21, 2008 at 9:44 AM, Monika Jisswel [EMAIL PROTECTED] wrote: instead of s='e:\mm tests\1. exp files\5.MOC-1012.exp' try to use : s = r'e:\mm tests\1. exp files\5.MOC-1012.exp'.replace( '\\', '') for me here is what it gives: s = r'e:\mm tests\1. exp files\5.MOC-1012.exp'.replace('\\', '') print s e:\\mm tests\\1. exp files\\5.MOC-1012.exp s.split('') ['e:', 'mm tests', '1. exp files', '5.MOC-1012.exp'] why \\ i you only have one \ ? : you need to escape it because its a special character to the python interpreter. the r character is important in the expression s = r'e:\mm tests\1. exp files\5.MOC-1012.exp'.replace('\\', '') because it tells the interpreter to take the string as RAW and thus leave it unchanged even if it contains special characters that should actually be treated special. now to use the r or not to use it ? when to use it ? how to use it ? I always use it ! always had the result I expected, so I would suggest you use it always too specialy with the re module, ofcourse unless the result is not satisaying you, so this code (using r this time works too) : s = r'e:\mm tests\1. exp files\5.MOC-1012.exp'.replace(r'\\', r'') print s e:\\mm tests\\1. exp files\\5.MOC-1012.exp s.split('') ['e:', 'mm tests', '1. exp files', '5.MOC-1012.exp'] Thanks, I am aware of goodies that raw string offers, but my question was how to use it with variable that already contains string. :) What it seems you don't understand is that raw strings just a method to create a string. If you already have a string read from a file, it is already created. Maybe you are confused between the representation of a string and the value of the string. s = 'c:\\abc\\123.txt' t = r'c:\abc\123.txt' s==t True Two ways to *create* the *same* string. Note there are two ways to *display* a string as well. print displays the actual value. If you don't use print, you get a representation of the string in a way that can be used to create the string in code. print s c:\abc\123.txt print t c:\abc\123.txt s 'c:\\abc\\123.txt' t 'c:\\abc\\123.txt' Note what happens if you use single backslashes without a raw to create the string: s = 'c:\abc\123.txt' s 'c:\x07bcS.txt' print s c:bcS.txt Because it wasn't a 'raw' string, the \a was interpreted as the non-printable BEL control character. \123 was interpreted as an octal constant, which turned out to be capital-S. The representation of the string contained a \x07 for the BEL control character. Since it is unprintable, the representation displayed it as a hexadecimal escape code. When you read a string from a file, the actual characters in the file end up in the string. No backslash interpretation is performed. So in your example, just read in the file and perform your operations: sample.txt contains: c:\abc\123.txt Code: import os pathname = open('sample.txt').read() pathname 'c:\\abc\\123.txt' print pathname c:\abc\123.txt print os.path.dirname(pathname) c:\abc print os.path.basename(pathname) 123.txt os.path.dirname(pathname) 'c:\\abc' os.path.basename(pathname) '123.txt' Does that clear up the confusion? --Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Unittest
OK, your console is set to 'ascii' ('cp437' was my example and is the Windows console encoding). 'ascii' won't be able to display Russian. It shouldn't have displayed the Ð˜Ð·Ð²ÐµÐ½Ð¸Ñ characters either. Are you still running on the same terminal that display those characters? Can you change your terminals encoding preference via an environment variable? -- Mark Oleg Oltar [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] And in case: # coding: utf-8 import traceback try: raise Exception(u'Зрегиться') except Exception,e: print traceback.format_exc().decode('utf-8').encode('cp437', 'replace') Getting beryl:~ oleg$ python ./wish/newaccount/reg.py Traceback (most recent call last): File ./wish/newaccount/reg.py, line 5, in module raise Exception(u'?') Exception: unprintable Exception object My console settings: In [1]: import sys In [2]: sys.getdefaultencoding() Out[2]: 'ascii' In [3]: sys.stdout.encoding Out[3]: 'US-ASCII' On Thu, Jul 17, 2008 at 9:30 AM, Oleg Oltar [EMAIL PROTECTED] wrote: OK the output: # coding: utf-8 import traceback try: raise Exception(u'Зрегиться') except Exception,e: print traceback.format_exc().decode('utf-8') Traceback (most recent call last): File /var/folders/PC/PCtFE4gQGiqpQymiAScfnk+++TM/-Tmp-/py46506ECT, line 7, in module print traceback.format_exc().decode('utf-8') UnicodeEncodeError: 'ascii' codec can't encode characters in position 148-156: ordinal not in range(128) On Thu, Jul 17, 2008 at 8:13 AM, Mark Tolonen [EMAIL PROTECTED] wrote: The Exception is output in the encoding of the source file. If the terminal you are displaying the exception on is in a different encoding, it will be garbled. I'm not familiar with OS X's terminal. Try running python and printing sys.stdout.encoding. Alternatively, wrap your code in a try/except handler and translate the exception yourself. # coding: utf-8 import traceback try: raise Exception(u'Зарегистрироваться') except Exception,e: print traceback.format_exc().decode('utf-8') The last line translates the utf-8 traceback into Unicode. Printing Unicode will encode the output with the terminal's decoding. If there are characters it can't display, you'll still get an error, though. You can be more explicit however: print traceback.format_exc().decode('utf-8').encode('cp437','replace') In this case you'll get ? whenever a character can't be represented in the selected encoding. cp437, for example, can't display any russian characters, so for me (on Windows) I just get all ???. When I tried it with a character string that could be displayed in cp437, it worked fine: Traceback (most recent call last): File stdin, line 1, in module File t4.py, line 4, in module raise Exception('MàΓ£ΦΘΩδ') Exception: MàΓ£ΦΘΩδ Another option is to redirect the output to a file and read the file with an editor that can display utf-8 (such as Notepad on Windows). python testfile.py 2error.txt # this redirects stderr to a file. Hope that helps, Mark Oleg Oltar [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] The code # -*- coding: utf-8 -*- #!/usr/bin/python This test case check how system works in the situation, when user tries to use already used username (domain) We are creating two accounts with such parameters: 1. Sex = Femle 2. Name1=Name2 = foobar%S 3. Pass1 = Name 4. Pass2 = Name 5. Email address1 = Email address2 = [EMAIL PROTECTED] In the test we use verification point - warning message about incorrect input of domain name and the sugestion message from selenium import selenium import unittest, time, re import HTMLTestRunner import config import Creating_account_basic class Same_domain_name(unittest.TestCase): def setUp(self): self.name = foobar self.email = self.name + @meta.ua self.verificationErrors = [] self.selenium = selenium(localhost, ,config.browser, config.link) self.selenium.start() def test_create_account_to_check(self): Creating sample account for next test sel = self.selenium sel.open(/) sel.click(ulink=Регистрация) sel.wait_for_page_to_load(7) sel.click(id_gender_1) sel.type(id_first_name, self.name) sel.type(id_last_name, self.name
Re: [Tutor] Unittest
You get the D characters when decoding Russian encoded in UTF-8 using Latin-1 instead. # coding: utf-8 x=u'Зарегистрироваться' print x.encode('utf-8').decode('latin-1') ÐаÑегиÑÑÑиÑоваÑÑÑÑ Check that your html encoding is declared correctly. -- Mark Oleg Oltar [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Ok, seems it's my console setting. Tried console with koi8-r (from http://vak.ru/doku.php/macosx-russian), and it looks ok there. Mean the satndard output, but still getting D chars instead of russian when trying to convert it to html via HTMLTestRunner (see http://tungwaiyip.info/software/HTMLTestRunner.html) On Thu, Jul 17, 2008 at 9:33 AM, Oleg Oltar [EMAIL PROTECTED] wrote: And in case: # coding: utf-8 import traceback try: raise Exception(u'Зрегиться') except Exception,e: print traceback.format_exc().decode('utf-8').encode('cp437', 'replace') Getting beryl:~ oleg$ python ./wish/newaccount/reg.py Traceback (most recent call last): File ./wish/newaccount/reg.py, line 5, in module raise Exception(u'?') Exception: unprintable Exception object My console settings: In [1]: import sys In [2]: sys.getdefaultencoding() Out[2]: 'ascii' In [3]: sys.stdout.encoding Out[3]: 'US-ASCII' On Thu, Jul 17, 2008 at 9:30 AM, Oleg Oltar [EMAIL PROTECTED] wrote: OK the output: # coding: utf-8 import traceback try: raise Exception(u'Зрегиться') except Exception,e: print traceback.format_exc().decode('utf-8') Traceback (most recent call last): File /var/folders/PC/PCtFE4gQGiqpQymiAScfnk+++TM/-Tmp-/py46506ECT, line 7, in module print traceback.format_exc().decode('utf-8') UnicodeEncodeError: 'ascii' codec can't encode characters in position 148-156: ordinal not in range(128) On Thu, Jul 17, 2008 at 8:13 AM, Mark Tolonen [EMAIL PROTECTED] wrote: The Exception is output in the encoding of the source file. If the terminal you are displaying the exception on is in a different encoding, it will be garbled. I'm not familiar with OS X's terminal. Try running python and printing sys.stdout.encoding. Alternatively, wrap your code in a try/except handler and translate the exception yourself. # coding: utf-8 import traceback try: raise Exception(u'Зарегистрироваться') except Exception,e: print traceback.format_exc().decode('utf-8') The last line translates the utf-8 traceback into Unicode. Printing Unicode will encode the output with the terminal's decoding. If there are characters it can't display, you'll still get an error, though. You can be more explicit however: print traceback.format_exc().decode('utf-8').encode('cp437','replace') In this case you'll get ? whenever a character can't be represented in the selected encoding. cp437, for example, can't display any russian characters, so for me (on Windows) I just get all ???. When I tried it with a character string that could be displayed in cp437, it worked fine: Traceback (most recent call last): File stdin, line 1, in module File t4.py, line 4, in module raise Exception('MàΓ£ΦΘΩδ') Exception: MàΓ£ΦΘΩδ Another option is to redirect the output to a file and read the file with an editor that can display utf-8 (such as Notepad on Windows). python testfile.py 2error.txt # this redirects stderr to a file. Hope that helps, Mark Oleg Oltar [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] The code # -*- coding: utf-8 -*- #!/usr/bin/python This test case check how system works in the situation, when user tries to use already used username (domain) We are creating two accounts with such parameters: 1. Sex = Femle 2. Name1=Name2 = foobar%S 3. Pass1 = Name 4. Pass2 = Name 5. Email address1 = Email address2 = [EMAIL PROTECTED] In the test we use verification point - warning message about incorrect input of domain name and the sugestion message from selenium import selenium import unittest, time, re import HTMLTestRunner import config import Creating_account_basic class Same_domain_name(unittest.TestCase): def setUp(self): self.name = foobar self.email = self.name + @meta.ua self.verificationErrors = [] self.selenium = selenium(localhost, ,config.browser
Re: [Tutor] Unittest
The Exception is output in the encoding of the source file. If the terminal you are displaying the exception on is in a different encoding, it will be garbled. I'm not familiar with OS X's terminal. Try running python and printing sys.stdout.encoding. Alternatively, wrap your code in a try/except handler and translate the exception yourself. # coding: utf-8 import traceback try: raise Exception(u'Зарегистрироваться') except Exception,e: print traceback.format_exc().decode('utf-8') The last line translates the utf-8 traceback into Unicode. Printing Unicode will encode the output with the terminal's decoding. If there are characters it can't display, you'll still get an error, though. You can be more explicit however: print traceback.format_exc().decode('utf-8').encode('cp437','replace') In this case you'll get ? whenever a character can't be represented in the selected encoding. cp437, for example, can't display any russian characters, so for me (on Windows) I just get all ???. When I tried it with a character string that could be displayed in cp437, it worked fine: Traceback (most recent call last): File stdin, line 1, in module File t4.py, line 4, in module raise Exception('MàΓ£ΦΘΩδ') Exception: MàΓ£ΦΘΩδ Another option is to redirect the output to a file and read the file with an editor that can display utf-8 (such as Notepad on Windows). python testfile.py 2error.txt # this redirects stderr to a file. Hope that helps, Mark Oleg Oltar [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] The code # -*- coding: utf-8 -*- #!/usr/bin/python This test case check how system works in the situation, when user tries to use already used username (domain) We are creating two accounts with such parameters: 1. Sex = Femle 2. Name1=Name2 = foobar%S 3. Pass1 = Name 4. Pass2 = Name 5. Email address1 = Email address2 = [EMAIL PROTECTED] In the test we use verification point - warning message about incorrect input of domain name and the sugestion message from selenium import selenium import unittest, time, re import HTMLTestRunner import config import Creating_account_basic class Same_domain_name(unittest.TestCase): def setUp(self): self.name = foobar self.email = self.name + @meta.ua self.verificationErrors = [] self.selenium = selenium(localhost, ,config.browser, config.link) self.selenium.start() def test_create_account_to_check(self): Creating sample account for next test sel = self.selenium sel.open(/) sel.click(ulink=Регистрация) sel.wait_for_page_to_load(7) sel.click(id_gender_1) sel.type(id_first_name, self.name) sel.type(id_last_name, self.name) sel.type(id_email, self.email) sel.type(id_username, self.name) #sel.wait_for_condition(sel.is_element_present(check_username_block), 7) time.sleep(10) print !!!, sel.is_element_present(check_username_block) sel.type(id_password, self.name) print sel.get_text(check_username_block).decode('cp-1252') sel.type(id_password2, self.name) sel.click(u//[EMAIL PROTECTED]'Зарегистрироваться']) sel.wait_for_page_to_load(7) if config.debugMode is True: time.sleep(5) def tearDown(self): self.selenium.stop() print self.verificationErrors self.assertEqual([], self.verificationErrors) if __name__ == __main__: unittest.main() #HTMLTestRunner.main() On Thu, Jul 17, 2008 at 6:47 AM, Oleg Oltar [EMAIL PROTECTED] wrote: In [1]: import sys In [2]: sys.getdefaultencoding() Out[2]: 'ascii' In [3]: sys.stdout.encoding Out[3]: 'US-ASCII' On Thu, Jul 17, 2008 at 6:29 AM, Oleg Oltar [EMAIL PROTECTED] wrote: Seems need help there. Start getting Traceback (most recent call last): File ./newaccount/Same_domain_name.py, line 56, in test_create_account_to_check print sel.get_text(check_username_block) UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128) when trying to get the text of one of the elements. How to solve it? On Thu, Jul 17, 2008 at 5:11 AM, Oleg Oltar [EMAIL PROTECTED] wrote: OK, I just run the program from terminal. OS: OS X, IDLE = Emacs:). Yep used the string # -*- coding: utf-8 -*- to setup encoding On Thu, Jul 17, 2008 at 4:14 AM, Kent Johnson [EMAIL PROTECTED] wrote: Another possibility - do you have a coding declaration in your source file, something like # -*- coding: encoding name -*- If so, does the coding
Re: [Tutor] manipulating a string
Bryan Fodness [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] I have a string (column names) that I need to split. D_H = 'D 5 10 15 20 25 30 35 40 D Upper D Lower' I cannot do a simple list(D_H).split because the last two strings have a space between them (D Upper and D Lower are two, not four labels). Any suggestions? How was the string built? Is it possible to delimit the columns with something besides a space, since a space is a valid character in a column name. Baring that, adding a little knowledge of the string is needed: import re D_H = 'D 5 10 15 20 25 30 35 40 D Upper D Lower' print re.split(r'\s(?![UL])',D_H) # split on spaces not followed by U or L. ['D', '5', '10', '15', '20', '25', '30', '35', '40', 'D Upper', 'D Lower'] -- Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Fibonacci series(perhaps slightly off topic)
You can actually remove the try/except, because if the calculation key-len(self.fibsseq)+1 = 0 the for loop won't execute. The for loop will make sure self.fibsseq is long enough to satisify the return self.febsseq[key] access: class Fibs(object): def __init__(self): self.fibsseq = [0, 1] def __getitem__(self, key): for i in xrange(key - len(self.fibsseq) + 1): self.fibsseq.append(self.fibsseq[-1] + self.fibsseq[-2]) return self.fibsseq[key] -Mark Emil [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Hey John thank you for your reply. I came up with this code, it is not elegant( yet) but i would say that it is more efficient :) class Fibs(object): def __init__(self): self.fibsseq = [0,1] def __getitem__(self, key): try: return self.fibsseq[key] except IndexError: for i in xrange(key-len(self.fibsseq)+1): self.fibsseq.append(self.fibsseq[-1] + self.fibsseq[-2]) return self.fibsseq[key] Date: Thu, 3 Jul 2008 12:59:39 +1200 From: [EMAIL PROTECTED] To: [EMAIL PROTECTED] Subject: Re: [Tutor] Fibonacci series(perhaps slightly off topic) CC: tutor@python.org On 03/07/2008, Emil wrote: I have created a class called Fibs which allow you to access a specific number in the Fibonacci series(http://en.wikipedia.org/wiki/Fibonacci_number) But it seems to me that it is a bit inefficient, any suggestions on how to make it more efficient? Does this behaviour seem correct to you? -- class Fibs(object): ...def __init__(self): ...self.fibsseq = [0, 1] ...def __getitem__(self, key): ...for i in xrange(key): ...self.fibsseq.append(self.fibsseq[-1] + self.fibsseq[-2]) ...return self.fibsseq[key] ... f = Fibs() f[1] 1 f[1] 1 f[1] 1 f.fibsseq [0, 1, 1, 2, 3] Maybe if I examine the first Fibonacci number a few hundred times: ones = [f[1] for i in xrange(500)] len(f.fibsseq) 505 Hmm, that's a lot of numbers to calculate when we're only looking at the first element in the sequence.. (by the way: you might want to replace 'print' with 'return' in your definition of __getitem__) (by the way 2: if you follow the above code, and then display f.fibsseq, you may see some nice curves caused by the between each number. Aren't fibonacci numbers wonderful :-) ) -- John. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Deleting specified files using a python program...help withcode?
Saad Javed [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] I transfer files a lot between my windows and linux partitions...these folders sometimes contain *.db and *.ini files which are not recognized or used by linux. So i tried to write a program to crawl through my home dir and remove these files... I'm *very* new to programming and python so please be gentle. Here is the code: import os list = ['*.ini', '*.db'] for root, dirs, files in os.walk('/home/saad'): for list in files: os.remove(os.path.join('root', 'list')) print 'done' Unfortunately its a bit too efficient and nearly wiped my home dir before i manually killed it. Again...treat me like a super noob. It's a good idea to use print instead of a destructive command like os.remove until print displays the correct filenames :^) Also, list and file are Python built-ins, so avoid using those names in code. import os,fnmatch patterns = '*.ini *.db'.split() for root,dirs,files in os.walk('/home/saad'): for pattern in patterns: for file_ in fnmatch.filter(files,pattern): print os.path.join(root,file_) -Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] need help with a regular expression
Kelie [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Hello, I'm trying to write a regular expression to filter strings that meet the following criteria: 1. Starts with 0-3 underscores; 2. Followed by one letter; 3. Then followed by 0 or more letters or digits or hyphens('-'), 4. Ends with one letter or digit; and 5. There should not be more than one continuous hyphens. This is what I have so far. I think it meets all the criteria except for the last one. Haven't figured out the answer yet. re.compile(r'_{0,3}[A-Z][A-Z0-9\-]*[A-Z0-9]') In rule 4, does the string end with an *additional* letter or digit? The string 'A' would seem to fit the rules, but the example provided would fail. re.compile(r'^_{0,3}[A-Z](?:[A-Z0-9]|-(?!-))*[A-Z0-9]$') # if rule 4 is an additional letter or digit re.compile(r'^_{0,3}[A-Z](?:[A-Z0-9]|-(?!-))*(?!-)$') # if single-letter strings are allowed -Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] arrays in python
Kirk Z Bailey [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Just wondering, if I can find a way to do a 2 dimensional array in python. 1 dimension would be a list it would seem; for 2, I could use a list of lists? Strange how I can't think of ever needing one since I discovered snake charming, but so many languages do foo dimensional arrays, it would seem like there ought to be a way to do it in python. Yes, use lists of lists, but be careful constructing them: L=[[0]*5]*5 L [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] L[0][0]=1 L [[1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0]] Oops, five references to the same list. Changing one changes all. L=[[0]*5 for _ in range(5)] L [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] L[0][0]=1 L [[1, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] Use a list comprehension to construct five different lists. --Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] For Loop question
Lie Ryan [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] On Thu, Jun 26, 2008 at 3:18 AM, Dick Moores [EMAIL PROTECTED] wrote: Hi I'm learning FOR loop now, very easy too learn. But I get confused to understand this code : myList = [1,2,3,4] for index in range(len(myList)): myList[index] += 1 print myList And the response is: [2, 3, 4, 5] Can you explain me as a newbie, how that code works ?? Ahhh... don't write it like that. It is not a pythonic way to use loop. For-loop in python can loop over sequence (list, tuple, dictionary, iterable, etc) directly (in Visual Basic, like For...Each loop), you very rarely would need to use range/xrange for the iterator, and you should never use len() to pass to range. The loop would be much more simpler, and understandable this way: myList = [1, 2, 3, 4] outList = [] for x in myList: outList.append(x + 1) print outList or in a more elegant way, using list comprehension: myList = [1, 2, 3, 4] print [(x + 1) for x in myList] The above solutions create new lists. If a functional requirement is to modify the list in place, then the original is fine (on Python 2.6 and later) or should use xrange instead of range (on Python 2.5 or earlier, especially for large lists). Another option is: myList = [1,2,3,4] for index,value in enumerate(myList): myList[index] = value + 1 -Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Newbie: Sorting lists of lists
Kent Johnson [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] On Wed, Jun 18, 2008 at 8:30 PM, Keith Troell [EMAIL PROTECTED] wrote: Let's say I have a list of lists l == [[1, 2, 3], [2, 3, 1], [3, 2, 1], [1, 3, 2]] If I do a l.sort(), it sorts on the first element of each listed list: l.sort() l [[1, 2, 3], [1, 3, 2], [2, 3, 1], [3, 2, 1]] How can I sort on the second or third elements of the listed lists? Use the key= parameter of sort to specify the sort key. operator.itemgetter is convenient for the actual key: In [3]: from operator import itemgetter In [4]: l.sort(key=itemgetter(1)) In [5]: l Out[5]: [[1, 2, 3], [3, 2, 1], [2, 3, 1], [1, 3, 2]] A longer explanation is here: http://personalpages.tds.net/~kent37/kk/7.html Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor You can use a lambda that builds the key you want to sort on from the original element: L=[[1,2,3],[2,3,1],[3,2,1],[1,3,2]] Sort on 2nd value: sorted(L,key=lambda x: x[1]) [[1, 2, 3], [3, 2, 1], [2, 3, 1], [1, 3, 2]] Sort on 2nd, then by 3rd value sorted(L,key=lambda x: (x[1],x[2])) [[3, 2, 1], [1, 2, 3], [2, 3, 1], [1, 3, 2]] -Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to make a python binding for a c library?
tuyun [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Hi I have a library written in C, I want to make a python binding for it. But I dont know how to get started. Is there any guide or document? Is Python/C API Reference Manual the right doc I need to study first? Check out the ctypes library. It comes with Python 2.5, but can be installed for older versions. Here's an example that calls the Win32 function Beep() from kernel32.dll: import ctypes ctypes.windll.kernel32.Beep(440,1000) This is a simplistic example that works for simple DLL functions that take integers and return integers. If your APIs deal with pointers and read/write buffers it is somewhat more complicated, but still easier to write your bindings in Python than using the Python C APIs. -Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tutorial indicating different output
Eric Morey [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Hello everyone, I have no prior experience with programing. I've just started with the Python tutorial at http://www.dickbaldwin.com/tocpyth.htm. On the section that describes decimal division on this page: http://www.dickbaldwin.com/python/Pyth0004.htm Figure 10 shows: 2.0/5 # get decimal quotient 0.4 2/5.0 # do it again 0.4 http://www.dickbaldwin.com/python/Pyth0004-fig10.htm Howerver, using the python shell in my terminal, I get: 2.0/5 # get decimal quotient 0.40002 2/5.0 # do it again 0.40002 I didn't worry too much about it and continued to move on. But I'm curious as to why there was a difference. Anyone know why? http://www.python.org/doc/faq/general/#why-are-floating-point-calculations-so-inaccurate -Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] seeking help to a problem w/ sockets
James Duffy [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] [snip] def close( this ): #close all connections and sockets this.conn.close() this.sock.close() def process( this ): #this is the loop of the thread, it listens, receives, closes then repeats until entire program is closed while 1: this.bindsock() this.acceptsock() this.transfer() this.close() There is no need to close the server socket after each connection. Try: def close( this ): #close all connections and sockets this.conn.close() def process( this ): this.bindsock() while 1: this.acceptsock() this.transfer() this.close() Also, take a look at the SocketServer libary. It handles multiple simultaneous connections and the details of setting up and tearing down connections: import threading import SocketServer class MyHandler(SocketServer.StreamRequestHandler): def handle(self): print 'Starting media transfer ' openfile=XMLrecieved+str(self.server.filenumber)+.xml f = open(openfile,wb) while 1: data = self.request.recv(1024) if not data: break f.write(data) f.close() print Got XML file: + openfile print 'Closing media transfer' self.server.filenumber += 1 class MyServer(SocketServer.ThreadingTCPServer): filenumber = 1 class MyThread(threading.Thread): def run(self): listen= server = MyServer(('',listen),MyHandler) server.serve_forever() t=MyThread() t.setDaemon(True) t.start() --Mark ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor