Re: [Tutor] crontab or python mistake
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 Daniel McQuay wrote, On 05/25/2006 09:24 PM: > Traceback (most recent call last): > File "/root/scripts/boxster_school_smtp.py", line 19, in ? >mssg = open('mssg.txt', 'r').read() > IOError: [Errno 2] No such file or directory: ' emmssg.txt' > Right, but I don't think the CWD for cron is in /root. Try giving it an absolute path. - -- Yi Qiang ([EMAIL PROTECTED]) Web: http://www.yiqiang.net Tel: (206) 661-8469 PGP: 0xB515564B -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.2.2 (GNU/Linux) iD8DBQFEdofJtXlIMrUVVksRAhZOAJ9Gr8RPjS37u7IEaLdZMJjawvxMDgCghTCm ub7rd1v+rrEAt2vTIpnwk4A= =xhDj -END PGP SIGNATURE- ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] crontab or python mistake
hello list,i am having a problem getting crontab to execute a python script. the script works because i can execute it by using: python boxster_school_smtp.py from a command line. i put a line in crontab that look like this: i know this is not a linux mailing list but any help would be appreciated.*/5 * * * * root /usr/local/bin/python /root/scripts/boxster_school_smtp.py now like i said the python script works by using: python my_script.py from the command line but when i use it in crontab i get some error. here is the error that cron gives: Traceback (most recent call last): File "/root/scripts/boxster_school_smtp.py", line 19, in ? mssg = open('mssg.txt', 'r').read()IOError: [Errno 2] No such file or directory: ' emmssg.txt'the emmssg.txt file is in the /root/script directory so i don't know why it cant find it.thanks again,-- Daniel McQuay [EMAIL PROTECTED]boxster.homelinux.org 814.825.0847 import smtplib import os emmssg = "/root/scripts/emmssg.txt" smtpserver = 'mail.erieit.edu' AUTHREQUIRED = 1 smtpuser = 'dmcquay' smtppass = '**' #For testing purposes only! RECIPIENTS = ['[EMAIL PROTECTED]'] #This will be used after testing #RECIPIENTS = ['[EMAIL PROTECTED]','[EMAIL PROTECTED]','[EMAIL PROTECTED]', # '[EMAIL PROTECTED]','[EMAIL PROTECTED]', # '[EMAIL PROTECTED]'] SENDER = '[EMAIL PROTECTED]' emmssg = open('emmssg.txt').read() session = smtplib.SMTP(smtpserver) if AUTHREQUIRED: session.login(smtpuser, smtppass) smtpresult = session.sendmail(SENDER, RECIPIENTS, emmssg) if smtpresult: errstr = "" for recip in smtpresult.keys(): errstr = """Could not delivery mail to: %s Server said: %s %s %s""" % (recip, smtpresult[recip][0], smtpresult[recip][1], errstr) raise smtplib.SMTPException, errstr ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] partial string matching in list comprehension?
doug shawhan wrote: > I have a series of lists to compare with a list of exclusionary terms. > > junkList =["interchange", "ifferen", "thru"] > > The comparison lists have one or more elements, which may or may not > contain the junkList elements somewhere within: > > l = ["My skull hurts", "Drive the thruway", "Interchangability is not my > forte"] > > ... output would be > > ["My skull hurts"] > > I have used list comprehension to match complete elements, how can I do > a partial match? One way is to use a helper function to do the test: In [1]: junkList =["interchange", "ifferen", "thru"] In [2]: lst = ["My skull hurts", "Drive the thruway", "Interchangability is not my forte"] In [3]: def hasJunk(s): ...: for junk in junkList: ...: if junk in s: ...: return True ...: return False ...: In [4]: [ s for s in lst if not hasJunk(s) ] Out[4]: ['My skull hurts', 'Interchangability is not my forte'] Hmm, I guess spelling counts :-) also you might want to make this case-insensitive by taking s.lower() in hasJunk(). Another way is to make a regular expression that matches all the junk: In [7]: import re Escape the junk in case it has any re-special chars: In [9]: allJunk = '|'.join(re.escape(junk) for junk in junkList) In [10]: allJunk Out[10]: 'interchange|ifferen|thru' You could compile with re.IGNORECASE to make case-insensitive matches. Spelling still counts though ;) In [11]: junkRe = re.compile(allJunk) In [13]: [ s for s in lst if not junkRe.search(s) ] Out[13]: ['My skull hurts', 'Interchangability is not my forte'] My guess is the re version will be faster, at least if you don't count the compile, but only testing will tell for sure: In [14]: import timeit In [18]: timeit.Timer(setup='from __main__ import hasJunk,lst', stmt='[ s for s in lst if not hasJunk(s) ]').timeit() Out[18]: 11.921303685244915 In [19]: timeit.Timer(setup='from __main__ import junkRe,lst', stmt='[ s for s in lst if not junkRe.search(s) ]').timeit() Out[19]: 8.3083201915327223 So for this data using re is a little faster. Test with real data to be sure! Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] partial string matching in list comprehension?
doug shawhan wrote: > I have a series of lists to compare with a list of exclusionary terms. > > > > junkList =["interchange", "ifferen", "thru"] > > The comparison lists have one or more elements, which may or may not > contain the junkList elements somewhere within: > > l = ["My skull hurts", "Drive the thruway", "Interchangability is not > my forte"] > > ... output would be > > ["My skull hurts"] > > I have used list comprehension to match complete elements, how can I > do a partial match? > > def removeJunk(reply, junkList): > return [x for x in reply if x not in junkList] > > It would be so much prettier than searching through each list element > for each term - I tend to get lost in a maze of twisty corridors, all > alike. Just say the magic word PLUGH! Be sure to pick up the batteries while you're in there. How about re? import re Build the search pattern: pattern = "|".join(junkList) Compile it: junkListPattern = re.compile(pattern) def removeJunk(reply, junkListPattern): return [x for x in reply if not junkListPattern.search(x)] *just with your hands* -- Bob Gailer 510-978-4454 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Q on path information
> And "whereis python" returns > python: /usr/bin/python /usr/bin/python2.4 /usr/lib/python2.4 > /usr/include/python /usr/include/python2.4 > /usr/share/man/man1/python.1.gz > > Does this mean I am using the python executable in > "/usr/bin/python/" but it then looks for built-in modules in > "/usr/lib64/python2.4/"? I'm no Suse expert but its common in Unix to have a standard name for a program which is a link to the latest version. Thus I guess that /usr/bin/python is a link to whatever the current version is, in this case /usr/bin/python2.4. When you upgrade the installer simply replaces the link to point to the new version, so you only have to type python to find it. > (2) A clarification question: PYTHONPATH is not needed as long > as one just imports built-in modules (such as re or sys) or > own modules from the same directory as the importing script, > right? For example, running "python foo.py" on the command > line, where foo.py imports a module "foo2.py" from the same > directory, the current directory is inferred automatically, right? I think sio, it seems to be how windoze does it... But I usually have PYTHONPATH set up so I can't be quite sure. Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question on regular expressions
> for line in open(r'e:\pycode\out_test.txt','rb') : >output.write( re.sub(r'([^\w\s])', lambda s: chr(int(s.group(), > 16))) % ord(s.group()), line)) > > This generated the traceback: > > File "E:\pycode\sample_decode_file_specials_from_hex.py", line 8 >output.write( re.sub(r'([^\w\s])', lambda s: chr(int(s.group(), > 16))) % ord(s.group()), line)) > > ^ > SyntaxError: invalid syntax > > > By any chance, do you see where the syntax issue is? Andrew, This is a good place to use the Python interactive prompt. Try the various bits in the interpreter to find out what causes the error. To be honest I'd break that single line into at least 2 if not 3 lines anyway purely from a debug and maintenance point of view. You are in real danger of turning Python into perl here! :-) As to your error: output.write( re.sub( r'([^\w\s])', lambda s: chr(int(s.group(),16)) ) % ord(s.group()), line)) the parens dont seem to match up... Or am I miscounting? Alan G ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question on regular expressions
On Thu, 25 May 2006, Kent Johnson wrote: > Yes, this is a feature of print, it always inserts a newline. Well, you can get rid of the newline by ending with a comma, but it still will insert spaces: >>> for ch in "abc": ... print ch ... a b c >>> for ch in "abc": ... print ch, ... a b c >>> I recall a way to get around that, too, but don't remember what it was. Your suggestion: > To avoid this, use sys.stdout.write() instead of print: Is the cleanest way to go, rather than arm-wrestling with "print". ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question on regular expressions (fwd)
On Thu, 25 May 2006, Alan Gauld wrote: > In general I prefer to use string formatting to convert into hex > format. I'm a big fan of hexlify: >>> from binascii import hexlify >>> s="abc-123" >>> hexlify(s) '6162632d313233' ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] partial string matching in list comprehension?
I have a series of lists to compare with a list of exclusionary terms. junkList =["interchange", "ifferen", "thru"] The comparison lists have one or more elements, which may or may not contain the junkList elements somewhere within: l = ["My skull hurts", "Drive the thruway", "Interchangability is not my forte"] ... output would be ["My skull hurts"] I have used list comprehension to match complete elements, how can I do a partial match? def removeJunk(reply, junkList): return [x for x in reply if x not in junkList] It would be so much prettier than searching through each list element for each term - I tend to get lost in a maze of twisty corridors, all alike. Thanks! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Unable to import xxx.pyd
I'm debugging a program where I'm trying to import a file named xxx.pyd. I test the logic interactively with IDLE and see that it makes a difference on which directory the file xxx.pyd is located. That is, I can get it to work when xxx.pyd is on the path. However, when I run the program in batch #!/usr/local/bin/python import cgitb; cgitb.enable() print "Content-type: text/html" print print "" import sys print sys.path import xxx I get the error message: No module named xxx, even though I know that the file xxx.pyd is on the path. If I put a file xxx.py in the same folder, the system finds that file. The file xxx.pyd has security numeric value 755, so the system should be able to find it. I'm baffled. Any suggestions of what my be causing the system to not find xxx.pyd? Thanks. Urban Landreman ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question on regular expressions
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 Hi Everyone, Thanks for all of your patience on this. I finally got it to work. Here is the completed test code showing what is going on. Not cleaned up yet but it works for proof-of-concept purposes. #!/usr/bin/python import re,base64 # Evaluate captured character as hex def ret_hex(value): return '%'+base64.b16encode(value) # Evaluate the value of whatever was matched def enc_hex_match(match): return ret_hex(match.group(0)) def ret_ascii(value): return base64.b16decode(value) # Evaluate the value of whatever was matched def enc_ascii_match(match): arg=match.group() #remove the artifically inserted % sign arg=arg[1:] # decode the result return ret_ascii(arg) def file_encoder(): # Read each line, pass any matches on line to function for # line in file.readlines(): output=open(r'e:\pycode\sigh.new','wb') for line in open(r'e:\pycode\sigh.txt','rb'): output.write( (re.sub('[^\w\s]',enc_hex_match, line)) ) output.close() def file_decoder(): # Read each line, pass any matches on line to function for # line in file.readlines(): output=open(r'e:\pycode\sigh.new2','wb') for line in open(r'e:\pycode\sigh.new','rb'): output.write(re.sub('%[0-9A-F][0-9A-F]',enc_ascii_match, line)) output.close() file_encoder() file_decoder() -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.3 (MingW32) iD8DBQFEdfQQDvn/4H0LjDwRAnbIAJ0cD9fdtIqtpfksP07n02Er9YMPiwCfTSsC pCVDgnQ8pbZS40BuA8gNNBQ= =mPoG -END PGP SIGNATURE- ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Q on path information
I have 2 questions I'm curious about (BTW, I use the default python installation as delivered with Linux SuSe 10.0) (1) How can I print the path to the python I'm using and where it imports built-in modules? python.sys returns (i probably want 64bit, so this seems ok): /usr/lib/python24.zip /usr/lib64/python2.4 /usr/lib64/python2.4/plat-linux2 /usr/lib64/python2.4/lib-tk /usr/lib64/python2.4/lib-dynload /usr/lib64/python2.4/site-packages /usr/lib64/python2.4/site-packages/Numeric /usr/lib64/python2.4/site-packages/PIL But, "which python" in the shell returns /usr/bin/python And "whereis python" returns python: /usr/bin/python /usr/bin/python2.4 /usr/lib/python2.4 /usr/include/python /usr/include/python2.4 /usr/share/man/man1/python.1.gz Does this mean I am using the python executable in "/usr/bin/python/" but it then looks for built-in modules in "/usr/lib64/python2.4/"? (2) A clarification question: PYTHONPATH is not needed as long as one just imports built-in modules (such as re or sys) or own modules from the same directory as the importing script, right? For example, running "python foo.py" on the command line, where foo.py imports a module "foo2.py" from the same directory, the current directory is inferred automatically, right? Thanks! E. Cecilia Ovesdotter Alm Graduate student/Dept. of Linguistics, UIUC http://www.linguistics.uiuc.edu/ebbaalm/ Office: 2013 Beckman Phone: (217) 721-7387 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question on regular expressions
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 Hi Kent, Sorry for causing so much trouble. I am not married to either a single or multi-line solution one way or another. Just a solution that works. Based on something by Danny Yoo provided, I had started with something like: import re,base64 # Evaluate captured character as hex def ret_hex(value): return base64.b16encode(value) def ret_ascii(value): return base64.b16decode(value) # Evaluate the value of whatever was matched def eval_match(match): return ret_ascii(match.group(0)) out=open(r'e:\pycode\sigh.new2','wb') # Read each line, pass any matches on line to function for # line in file.readlines(): for line in open(r'e:\pycode\sigh.new','rb'): print (re.sub('[^\w\s]',eval_match, line)) The char to hex pass works but omits the leading x. The hex to char pass does not appear to work at all. No error is generated. It just appears to be ignored. Kent Johnson wrote: > Andrew Robert wrote: > > You have an argument in the wrong place. Stop trying to do everything in > one line! Put the lambda in a def'd function. Put the re.sub on it's own > line. You are tripping over unnecessary complexity. I'm not going to fix > it any more. > > Kent > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > - -- Thank you, Andrew Robert Systems Architect Information Technologies MFS Investment Management Phone: 617-954-5882 E-mail: [EMAIL PROTECTED] Linux User Number: #201204 -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.3 (MingW32) iD8DBQFEddHSDvn/4H0LjDwRAibnAJ4/6/IiPtz7k+jIa01kRe1X25UNkACfaq24 bbqKqyOZyLpCRBEHbrO7H7A= =8+rq -END PGP SIGNATURE- ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question on regular expressions
Andrew Robert wrote: > -BEGIN PGP SIGNED MESSAGE- > Hash: SHA1 > > When I alter the code to: > > import re,sys > > output = open(r'e:\pycode\new_test.txt','wb') > > for line in open(r'e:\pycode\out_test.txt','rb') : >output.write( re.sub(r'([^\w\s])', lambda s: chr(int(s.group(), 16))) > , line) > > output.close() > > I get the trace: > > Traceback (most recent call last): > File "E:\pycode\sample_decode_file_specials_from_hex.py", line 8, in ? > output.write( re.sub(r'([^\w\s])', lambda s: chr(int(s.group(), > 16))) , line) > TypeError: sub() takes at least 3 arguments (2 given) > > It appears that the code is not recognizing the line. > > I checked the parentheses and they appear to be properly enclosed. > > Any ideas? You have an argument in the wrong place. Stop trying to do everything in one line! Put the lambda in a def'd function. Put the re.sub on it's own line. You are tripping over unnecessary complexity. I'm not going to fix it any more. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question on regular expressions
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 lol.. Glutton for punishment I guess. I tried removing the last parentheses but I then get an error that two arguments are passed when three are expected. Danny Yoo wrote: > > >> for line in open(r'e:\pycode\out_test.txt','rb') : >>output.write( re.sub(r'([^\w\s])', lambda s: chr(int(s.group(), >> 16))) % ord(s.group()), line)) > > > Let's add some whitespace. > > output.write(re.sub(r'([^\w\s])', >lambda s: chr( > int(s.group(), 16) > ) > ) % ord(s.group()), line)) > > I do see at least one too many parens here, so that's something you > should look at. > > But I'd also recommend writing a helper function here. Just because you > can do this in one line doesn't mean you have to. *grin* It might be > useful to change the lambda back to a helper function. > - -- Thank you, Andrew Robert Systems Architect Information Technologies MFS Investment Management Phone: 617-954-5882 E-mail: [EMAIL PROTECTED] Linux User Number: #201204 -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.3 (MingW32) iD8DBQFEdbtlDvn/4H0LjDwRAqg+AJ0SZY/T3kCpG+3qWX3F3yRSt73P7ACdFsZQ LnBhWh95EfuHA+eMkz6gkF4= =C0oN -END PGP SIGNATURE- ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question on regular expressions
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 When I alter the code to: import re,sys output = open(r'e:\pycode\new_test.txt','wb') for line in open(r'e:\pycode\out_test.txt','rb') : output.write( re.sub(r'([^\w\s])', lambda s: chr(int(s.group(), 16))) , line) output.close() I get the trace: Traceback (most recent call last): File "E:\pycode\sample_decode_file_specials_from_hex.py", line 8, in ? output.write( re.sub(r'([^\w\s])', lambda s: chr(int(s.group(), 16))) , line) TypeError: sub() takes at least 3 arguments (2 given) It appears that the code is not recognizing the line. I checked the parentheses and they appear to be properly enclosed. Any ideas? Kent Johnson wrote: > Take out " % ord(s.group())" - the result of chr() is the actual string > you want, not a format string. > > The syntax error is caused by mismatched parentheses. > > Kent > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > - -- Thank you, Andrew Robert Systems Architect Information Technologies MFS Investment Management Phone: 617-954-5882 E-mail: [EMAIL PROTECTED] Linux User Number: #201204 -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.3 (MingW32) iD8DBQFEdbpWDvn/4H0LjDwRAhEmAJ9WSfKitH1VgsTD5kTLI4cWP5YZRwCgs0mz Y9jl5l6Q/VZe6NmUaibZGa4= =nezG -END PGP SIGNATURE- ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question on regular expressions
> for line in open(r'e:\pycode\out_test.txt','rb') : >output.write( re.sub(r'([^\w\s])', lambda s: chr(int(s.group(), > 16))) % ord(s.group()), line)) Let's add some whitespace. output.write(re.sub(r'([^\w\s])', lambda s: chr( int(s.group(), 16) ) ) % ord(s.group()), line)) I do see at least one too many parens here, so that's something you should look at. But I'd also recommend writing a helper function here. Just because you can do this in one line doesn't mean you have to. *grin* It might be useful to change the lambda back to a helper function. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question on regular expressions
Andrew Robert wrote: > -BEGIN PGP SIGNED MESSAGE- > Hash: SHA1 > > Hi all, > > I tried: > > > output = open(r'e:\pycode\new_test.txt','wb') > > for line in open(r'e:\pycode\out_test.txt','rb') : > output.write( re.sub(r'([^\w\s])', lambda s: chr(int(s.group(), > 16))) % ord(s.group()), line)) > > > This generated the traceback: > > File "E:\pycode\sample_decode_file_specials_from_hex.py", line 8 > output.write( re.sub(r'([^\w\s])', lambda s: chr(int(s.group(), > 16))) % ord(s.group()), line)) > > ^ > SyntaxError: invalid syntax > > > By any chance, do you see where the syntax issue is? Take out " % ord(s.group())" - the result of chr() is the actual string you want, not a format string. The syntax error is caused by mismatched parentheses. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question on regular expressions
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 Hi all, I tried: output = open(r'e:\pycode\new_test.txt','wb') for line in open(r'e:\pycode\out_test.txt','rb') : output.write( re.sub(r'([^\w\s])', lambda s: chr(int(s.group(), 16))) % ord(s.group()), line)) This generated the traceback: File "E:\pycode\sample_decode_file_specials_from_hex.py", line 8 output.write( re.sub(r'([^\w\s])', lambda s: chr(int(s.group(), 16))) % ord(s.group()), line)) ^ SyntaxError: invalid syntax By any chance, do you see where the syntax issue is? Kent Johnson wrote: > Andrew Robert wrote: > Use int(s, 16) to convert a base 16 string to an integer, and chr() to > convert the int to a string. So something like this: > lambda s: chr(int(s.group(), 16))) > > Kent > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > - -- Thank you, Andrew Robert Systems Architect Information Technologies MFS Investment Management Phone: 617-954-5882 E-mail: [EMAIL PROTECTED] Linux User Number: #201204 -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.3 (MingW32) iD8DBQFEdbMrDvn/4H0LjDwRAi09AKC1I6XIcXiqYmpk4hpcbnkwux1NawCgt/zp xySHXPrh5JncZphAcVRtbtI= =xtr9 -END PGP SIGNATURE- ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help requested: port not free, under Windows XP
Andre Roberge schreef: > Thank you Rick (and Alan) for your suggestions which I forwarded to > Catherine, would-be-user of Crunchy Frog. Apparently Catherine was > using port 8080 as a proxy server; changing it made everything work. > This also tells me that I should use a different number as a default. You might want to avoid any of the numbers in http://www.iana.org/assignments/port-numbers or http://www.freebsd.org/cgi/cvsweb.cgi/src/etc/services?rev=1.102.8.1&content-type=text/x-cvsweb-markup, as they are already registered for other uses. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question on regular expressions
Andrew Robert wrote: > Taking this a little further along, I wrote the converted file to a new > file using: > > > import re,sys > > output = open(r'e:\pycode\out_test.txt','wb') > > for line in open(r'e:\pycode\sigh.txt','rb') : > output.write( re.sub(r'([^\w\s])', lambda s: '%%%2X' % > ord(s.group()), line)) > > output.close() > > > Not elegant but its strictly for test :) > > > Last part and we can call it a day. > > How would you modify the lambda statement to covert a the hex value back > to its original value? Use int(s, 16) to convert a base 16 string to an integer, and chr() to convert the int to a string. So something like this: lambda s: chr(int(s.group(), 16))) Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Pexpect logging out from a remote terminal
Hey I have a script that logs into a remote terminal over ssh and executes a script i.e. 1. Script logs into remote terminal over ssh 2. Executes another script that resides on the remote terminal, with the command 'child.sendline(cmdString)', where cmdString is a reference to the local script being run. So I would like run the command 'child.sendline(cmdString)' in the background, grab the output from the local script being run on the remote terminal, redirect it into a logfile and I will have another function that monitors when this is complete and then proceeds. I have looked over numerous examples in my python cookbook but cannot see anything that I could adapt to this. Any suggestions on what I could do or where I could find some helpful info. Thanks K -- "Behind every great man, there is a great woman. Behind that woman is Mr.T." ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question on regular expressions
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 Great! Taking this a little further along, I wrote the converted file to a new file using: import re,sys output = open(r'e:\pycode\out_test.txt','wb') for line in open(r'e:\pycode\sigh.txt','rb') : output.write( re.sub(r'([^\w\s])', lambda s: '%%%2X' % ord(s.group()), line)) output.close() Not elegant but its strictly for test :) Last part and we can call it a day. How would you modify the lambda statement to covert a the hex value back to its original value? Do I need to incorporate base64.16basedecode somehow? The original perl code to covert back to normal is: `perl -ple 's/(?:%([0-9A-F]{2}))/chr hex $1/eg' somefiletxt Kent Johnson wrote: > Yes, this is a feature of print, it always inserts a newline. To avoid > this, use sys.stdout.write() instead of print: > for line i open(r'e:\pycode\sigh.txt','rb'): > line = re.sub(r'([^\w\s])', lambda s: '%%%2X' % ord(s.group()), line) > sys.stdout.write(line) > > Kent > - -- Thank you, Andrew Robert Systems Architect Information Technologies MFS Investment Management Phone: 617-954-5882 E-mail: [EMAIL PROTECTED] Linux User Number: #201204 -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.3 (MingW32) iD8DBQFEdacCDvn/4H0LjDwRAkTWAJ4/KS6WnAgUraPZLmyPCQ45izq5tQCgl7sR nkZbIauRcdlavA89ZhnDSuM= =YZPS -END PGP SIGNATURE- ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help requested: port not free, under Windows XP
On 5/25/06, Richard Harding <[EMAIL PROTECTED]> wrote: Andre Roberge wrote:> ===Now the question===> Someone on edu-sig tried to get it working on her computer running> Windows XP home edition (just like mine, where it works fine!).> However, she gets an error message about > " port 8080 not free on local host." This is after she made sure> nothing else internet-related was working. [This kind of message can> happen if another instance of Crunchy Frog is already running, which > she made sure wasn't.]>> smart and friendly people here that I could find an answer ;-)Ideas:1) Built in XP firewall, what SP is she at vs what you might have?2) 8080 is a common port for proxy servers and alternate web configs so my first suggestion would be to change the app to not use a port that isso commonly used for something else.3) In the end I would just try to port scan the machine and see if it islistening on port 8080 and then you're stuck trying to find out why. There are several ports scanners for windows you can download a trialof. I personally just use nmap.Thank you Rick (and Alan) for your suggestions which I forwarded to Catherine, would-be-user of Crunchy Frog. Apparently Catherine was using port 8080 as a proxy server; changing it made everything work. This also tells me that I should use a different number as a default. I'll now go back to just being a reader of this list, with some rare attempts at answering questions. AndréRick ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question on regular expressions
Andrew Robert wrote: > The python method inserts extra blank lines after each hex value line. > Does anyone know why this might be? > > Is the print statement inserting a artificial new line character? Yes, this is a feature of print, it always inserts a newline. To avoid this, use sys.stdout.write() instead of print: for line i open(r'e:\pycode\sigh.txt','rb'): line = re.sub(r'([^\w\s])', lambda s: '%%%2X' % ord(s.group()), line) sys.stdout.write(line) Kent > > If so, how cam I remove that? > > > The python code I am using is: > > > > import re,sys > > for line i open(r'e:\pycode\sigh.txt','rb'): > print re.sub(r'([^\w\s])', lambda s: '%%%2X' % ord(s.group()), line) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question on regular expressions
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 Hi Everyone I did a comparison of the output between the perl and python methodology. They do basically the same thing but the perl form seems to be more "true" The python method inserts extra blank lines after each hex value line. For example: Original text: def handler(signal, frame): """ Trap signal interrupts if they occur """ Converted In Perl: def handler%28signal%2C frame%29%3A %22%22%22 Trap signal interrupts if they occur %22%22%22 Converted In Python: def handler%28signal%2C frame%29%3A %22%22%22 Trap signal interrupts if they occur %22%22%22 Does anyone know why this might be? Is the print statement inserting a artificial new line character? If so, how cam I remove that? The python code I am using is: import re,sys for line i open(r'e:\pycode\sigh.txt','rb'): print re.sub(r'([^\w\s])', lambda s: '%%%2X' % ord(s.group()), line) The file is being opened in rb mode because eventually binary files would be opened via this method as well. Alan Gauld wrote: >> a = open(r'e:\pycode\csums.txt','rb').readlines() >> >> for line in a: >>print re.sub(r'([^\w\s])', lambda s: '%%%2X' % ord(s.group()), line) > > Or just > > for line in open(r'e:\pycode\csums.txt','rb'): > print. > >> Breaking down the command, you appear to be calling an un-named function >> to act against any characters trapped by the regular expression. >> >> Not familiar with lamda :). > > You ae absolutely right. > It creates an un-named(or anonymous function). :-) > >> The un-named function does in-place transformation of the character to >> the established hex value. > > Its actually the call to re.sub() that makes in in place. > >> How would you reverse the process from a python point of view? > > Just write a reverse function for the lamda... > > Alan G. > > - -- Thank you, Andrew Robert Systems Architect Information Technologies MFS Investment Management Phone: 617-954-5882 E-mail: [EMAIL PROTECTED] Linux User Number: #201204 -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.3 (MingW32) iD8DBQFEdZ9oDvn/4H0LjDwRAo89AJwJ64+wpfOnboxw4/+w8PhmZBzgwACfYH7C VPW5VPyqSWhAUgkoOBorjJM= =bOj0 -END PGP SIGNATURE- ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] _next
Christopher Spears schreef: > How does this script work? > > #!/usr/bin/python > > class IteratorExample: > def __init__(self, s): > self.s = s > self.next = self._next().next > self.exhausted = 0 > def _next(self): > if not self.exhausted: > flag = 0 > for x in self.s: > if flag: > flag = 0 > yield x > else: > flag = 1 > self.exhausted = 1 > def __iter__(self): > return self._next() > > def main(): > a = IteratorExample('edcba') > for x in a: > print x Maybe I should try to explain what's happening instead of only offering an alternative. It's somewhat complicated by the fact that this is a very convoluted example IMO. To be able to use an object in a for loop like that, it needs an __iter__() method. That method is called behind the scenes when the for loop is started, and it should return an iterator object. An iterator object is an object with a next() method that returns the next element each time it's called, and raises StopIteration if there are no more elements. Useless but simple example: class Count: def __init__(self): self.max = 10 self.index = 0 def __iter__(self): return self def next(self): self.index += 1 if self.index > self.max: raise StopIteration return self.index Objects instantiated from this class can be iterated over because of the __iter__() method. In this case, that method returns the object itself; therefore the object itself serves as the iterator object. It does this with its next() method, which simply returns the numbers 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 and then raises StopIteration. A special kind of iterator object can be made with a generator function. That looks like a normal function, but uses yield instead of return. Each time its next element is requested, it runs until it encounters a yield statement. At that point, it passes the value specified in the yield statement to its caller and then freezes. When the next element is requested, it resumes operation directly after the yield statement where it was frozen until it encounters the next yield statement. And so on, until the function ends or executes the return statement or raises StopIteration. Again, a simple example: def backwards(s): for x in s[::-1]: yield x for x in backwards('edcba'): print x a b c d e Now, in your example the two are mixed. To make matters somewhat less complicated, I commented some lines that are totally useless; you should ignore them: class IteratorExample: def __init__(self, s): self.s = s #self.next = self._next().next #self.exhausted = 0 def _next(self): #if not self.exhausted: flag = 0 for x in self.s: if flag: flag = 0 yield x else: flag = 1 #self.exhausted = 1 def __iter__(self): return self._next() The _next() method is a generator function as I described above, which creates an iterator object when called. The __iter__() method just calls that generator function and returns the result to its caller. HTH -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] _next
Christopher Spears schreef: > How does this script work? > > #!/usr/bin/python > > class IteratorExample: > def __init__(self, s): > self.s = s > self.next = self._next().next > self.exhausted = 0 > def _next(self): > if not self.exhausted: > flag = 0 > for x in self.s: > if flag: > flag = 0 > yield x > else: > flag = 1 > self.exhausted = 1 > def __iter__(self): > return self._next() I always use generator functions like this to achieve the same effect: def IteratorExample(): flag = 0 for x in s: if flag: flag = 0 yield x else: flag = 1 Much less boilerplate and behind-the-scenes bookkeeping, so it's easier to type and understand. Result is the same: >>> a = IteratorExample('edcba') >>> for x in a: print x d b >>> a = IteratorExample('edcba') >>> print a.next() d >>> print a.next() b >>> print a.next() Traceback (most recent call last): File "", line 1, in -toplevel- print a.next() StopIteration -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor