Re: [Tutor] Two Newbile Questions: porting drawmap.c, & Python as a lifetime language

2006-07-04 Thread Dustin J. Mitchell
[EMAIL PROTECTED] wrote:
> 1. What's involved in a port of a C program into Python?  (drawmap is  
> offered in a number of linux distributions btw.)

It really (really) depends on the C program -- C's so flexible that you
can write in a "Pythonish" style (specifically, avoiding pointer tricks,
keeping OS-specific stuff to a minimum, and using good functional / data
abstractions) or in a style that's so obfuscated as to make any sort of
translation impossible.  The flip side of that is that Python is
flexible enough to accommodate many programming styles.  It sounds like
this program basically parses an input file and produces an output file,
 so I would bet that you can find some existing code that will read the
input file, and some other existing code that will write the output
file.  Then you just have to write the middle part.

> 2. Seeing Python hailed as a good language for learning programming,  
> how do you
> rate it as a lifetime language? (I can imagine that many people have
> settled into one language for doing the remainder of their life's work. If
> I am pressed, I will choose Perl at this point.)

Eep, Perl!  Once a polyglot, always a polyglot.  My choice of language
depends on the context.  For quick web stuff, PHP (O! How I hate thee!).
 For quick manipulation of files and/or using lots of external programs,
shell.  For just about everything else, Python.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] time(duration) formats & basic time math query

2006-07-05 Thread Dustin J. Mitchell
kevin parks wrote:
> I have been handed a huge number of documents which have hundreds of  
> pages of times and durations, all calculated and notated by several  
> different people over the course of many years. Sadly, no made any  
> guidelines at all about how this work would proceed and all the  
> documenters had their own ideas about how times/durations would be  
> specified so the doc are a mess. Furthermore the person i work for  
> changes her mind every 15 minutes so i have no idea what she will  
> want at any given moment. This sounds to me like a job for Python  
> 
> 
> Essentially, I am trying to do 2 things:
> 
> move fluidly between different duration formats (take any, specify  
> and display any). Such as:
> 
> pure miliseconds
> seconds. msec
> mm:ss.msec
> hh:mm:ss.msec
> 
> So the input doc would be grepped for times and i could just  
> uncomment the line i need and get he format my boss wants at this  
> particular moment.
> So a recording that is 71 minutes and 33 seconds could be printed as:
> 4293 seconds
> 71:33.
> 01:11.33.  or whatever
> 
> also i need to be able to adjust start times, durations, and end  
> times which means doing a little time math.
> Like if a recording is 71 minute and 33 seconds.. but there are  
> several sonic events in that recording and i
> need to specify the duration, or start time etc of those individual  
> events... then i need to subtract... Additionally i
> know that i will need to subtract pure minutes from an hh:mm format
> 
> I having a real hard time getting my head round the labyrinthian  
> datetime module in the docs (i am guessing
> that this is what i should use). I wonder if anyone could give me a  
> hand and point me in the right direction.

datetime may do the trick for you, but I would use it only for its
conversional abilities -- it sounds like this is a good time for you to
implement your own "Duration" class, with some kind of flexible system
for parsing (possibly even recognizing) different time formats, and
producing different time formats, e.g.,

class Duration:
  def __init__(self, duration_string, format='guess'):
if format == 'guess': format = self.guess_format(duration_string)
self.format = format

parse, output = self.format_fns[self.format]
self.seconds = parse(self, duration_string)

  def output(self, format='original'):
if format == 'original': format = self.format
parse, output = self.format_fns[format]
return output(self)

  def parse_milliseconds(self, duration_string): ...
  def output_milliseconds(self): ...
  def parse_fracseconds(self, duration_string): ...
  def output_fracseconds(self): ...

  format_fns = {
'milliseconds' : (parse_milliseconds, output_milliseconds),
'fracseconds' : (parse_fracseconds, ouput_fracseconds),
  }

Then you can just parse the thing up like this:

  durations = [ Duration(line.strip()) for line in f.xreadlines() ]

and print it out like this:

  for dur in durations:
print dur.output('milliseconds')

Dustin
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How can I copy files recursively?

2006-07-10 Thread Dustin J. Mitchell
Richard Querin wrote:
> I know this is probably a dumb question:
> 
> I've got mp3 files that are downloaded (by ipodder) into individual
> subfolders. I'd like to write a quick script to move (not copy) all the
> mp3 files in those folders into a single destination folder. I was
> thinking I could do it easily from the linux command line (cp -r copies
> the subfolders out as well) but I can't figure out how to do it. Is
> there an easy way to achieve this using Python? I am assuming this would
> be something Python was designed to make easy..

Python's not always the best with complex manipulations like that.  You
could use os.path.walk, but here's the same thing in bash:

 find $IPODDER_DIR -type f -exec mv \{} $DEST_DIR \;

Dustin
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] question about headers and smtplib

2006-07-31 Thread Dustin J. Mitchell
shawn bright wrote:
> the only difference in one from the other is that in the headers of the
> other app (not my python script)
> there exist the following lines:
> 
> MIME-Version: 1.0
> X-Mailer: OstroSoft SMTP Control (4.0.20)
> Content-Type: text/plain; charset="us-ascii"
> Content-Transfer-Encoding: 7-bit
> 
> i do not understand how to make mine work and include (or configure to)
> the above example.
> 
> anyone point me in a right direction ?


It's hard to tell what the problem is without seeing the error messages
-- do you get a "bounce"?  Is there anything in your logfile?  Have you
tried set_debuglevel and looking at the output?  If you have information
there, but don't know how to interpret it, post it here and we'll take a
look.

You could try adding the Content-Type header to your own messages.
People configure mailservers in a lot of weird ways, and it's possible
that some mailservers reject emails without a Content-Type header..

Dustin
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python for basic web-testing

2006-08-06 Thread Dustin J. Mitchell
Hans Dushanthakumar wrote:
> Hi,
>How do I use python for basic web-tasks like inputting data or
> clicking buttons on web-pages. For eg, how do I enter my username and
> password and click on the "OK" button on the yahoo mail page?
> I had a look at the webbrowser module documentation
> (http://www.python.org/doc/current/lib/module-webbrowser.html), but it
> doesnt seem to support clicking buttons or sending data.

All the stuff you need is right here:

http://wwwsearch.sourceforge.net/

Specifically, the clicking buttons part is in ClientForm.

Dustin
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Syntax Error? Variable Scope?

2006-11-02 Thread Dustin J. Mitchell
Chuck Coker wrote:
> from net.grinder.script import Test
> from net.grinder.script.Grinder import grinder
> from net.grinder.plugin.http import HTTPPluginControl, HTTPRequest
> from HTTPClient import NVPair
> connectionDefaults = HTTPPluginControl.getConnectionDefaults()
> httpUtilities = HTTPPluginControl.getHTTPUtilities()
> 
> [... snip ...]
> 
> fileNewUserInfo = 'new-user-info.csv'
> fileNewUserInfoIsOpen = 0
> 
> [... snip ...]
> 
> class TestRunner:
>   """A TestRunner instance is created for each worker thread."""
> 
>   # The instance initialization method.
>   def __init__(self):
> print 'We are in TestRunner.__init__()'
> global infile
> global fileNewUserInfoIsOpen
> if (fileNewUserInfoIsOpen == 0):
>   infile = open(fileNewUserInfo, "r")
>   fileNewUserInfoIsOpen += 1;
>   print 'We are inside the open if statement'
> #global infile
> self._userTokenCtx = ''
> self._userTokenRi = ''
> self._userInfo = []
> 
> for line in infile.readlines():
>   self._userInfo.append(string.split((line),','))
>   print line
> 
> print self._userInfo
> 
>   def nextMethod(self):
> 
> [... snip ...]
> --
> 
> The script blows up at this line inside the for loop:
> 
>   self._userInfo.append(string.split((line),','))
> 
> with this error message in my error log:
> 
> 11/2/06 7:12:20 PM (thread 0): Aborting thread due to Jython exception
> "NameError: string" whilst creating per-thread test runner object
> 
> NameError: string
> File "new-user-registration.py", line 356, in __init__
> 
> I've tried using "import string" and it doesn't like that. I'm sure
> I'm missing something very basic here due to my newness with Python.
> Can anyone offer any insights?

Python's scoping is a little weird, but you're actually using it right.
Adding 'import string' to the top of your module should have fixed this
problem, but that's old (like Py 2.1, I think) behavior.  Nowadays, you can
write e.g., self._userInfo.append(",".split(line)).

Also, there's a CSV module that will take care of reading and splitting CSV
files for you.  Personally, I would write this all out a little differently,
taking advantage of the fact that performing operations in the global context
is allowed:

...
import csv
...

userInfo = csv.reader(file('new-user-info.csv', 'rb'))

class TestRunner:
def __init__(self):
for row in userInfo:
# row is a tuple of cells
print row

hopefully that helps.

Dustin
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Two Questions...(i) Checking for None (ii) Making commandline arguments mutually exclusive

2006-11-04 Thread Dustin J. Mitchell
> if x == None
> 
> As simple as that.

In fact, I think the following is even a little more readable:

  if x is None

and in fact that syntax has some advantages in various corner cases.  It's
largely a matter of preference.

Dustin
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] A question abt exception handling

2006-11-04 Thread Dustin J. Mitchell
import traceback

try:
something_funny()
except:
traceback.print_exc()

should do the trick for you.

Dustin
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help me to debug this script .. I tried but ....

2006-11-05 Thread Dustin J. Mitchell
Asrarahmed Kadri wrote:
> "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py",
> line 310, in RunScript
> exec codeObject in __main__.__dict__
>   File "C:\project stuff-programs\Scriptdate.py", line 18, in ?
> t1 = my_version_datecheck.dateCheck(dt1,0)
>   File "my_version_datecheck.py", line 38, in dateCheck
> import traceback
> NameError: global name 'traceback' is not defined

This tells you everything you need to know right here.

What version of Python are you using?  I know traceback existed at least in
2.3.  Might be time to consider an upgrade.

Dustin
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Encoding and XML troubles

2006-11-05 Thread Dustin J. Mitchell
For what it's worth, the vast majority of the XML out there (especially if
you're parsing RSS feeds, etc.) is written by monkeys and is totally
ill-formed.  It seems the days of 'it looked OK in my browser' are still here.

To find out if it's your app or the XML, you could try running the XML through
a validating parser.  There are also various tools out there which might be
able to parse the XML anyway -- xmllint, I believe, can do this.

Dustin (not by *any* stretch an expert on XML *or* Unicode)
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help me to debug this script .. I tried but ....

2006-11-05 Thread Dustin J. Mitchell
Kent Johnson wrote:
> Dustin J. Mitchell wrote:
>> Asrarahmed Kadri wrote:
>>> "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py",
>>> line 310, in RunScript
>>> exec codeObject in __main__.__dict__
>>>   File "C:\project stuff-programs\Scriptdate.py", line 18, in ?
>>> t1 = my_version_datecheck.dateCheck(dt1,0)
>>>   File "my_version_datecheck.py", line 38, in dateCheck
>>> import traceback
>>> NameError: global name 'traceback' is not defined
>> This tells you everything you need to know right here.
>>
>> What version of Python are you using?  I know traceback existed at least in
>> 2.3.  Might be time to consider an upgrade.
> 
> If traceback was not a valid module name the import would raise 
> ImportError, not NameError.
> 
> Something strange is going on here; have you shown us all the code?

Python caches the text of programs, and will show that in later tracebacks.
Try restarting your IDE and running the script again, or look on line 38 of
my_version_datecheck.py -- I bet it doesn't say "import traceback".

Dustin
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor