Re: downloading a CSV

2016-02-19 Thread noydb
Thanks!  That was pretty easy.

import urllib.request
url = 'http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_month.csv'
urllib.request.urlretrieve(url, csv_file)
csv_file = r"C:\Temp\earthquakeAll_last30days.csv"
urllib.request.urlretrieve(url, csv_file)

I do want to use python -- there's much more I need to do with the file after 
downloading.
-- 
https://mail.python.org/mailman/listinfo/python-list


downloading a CSV

2016-02-19 Thread noydb
Greetings All,

Python v 3.4, windows

I want to be able to download this CSV file and save to disk
>> http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_month.csv 

This (interacting with the web using python) is very new to me, so can anyone 
provide direction on how to go about doing this?  Is it involved?  Is there a 
good example out there that can illustrate the needs/mechanics/how-to?

Many thanks in advance!
-- 
https://mail.python.org/mailman/listinfo/python-list


extracting zip item to in-memory

2015-05-06 Thread noydb
I have a zip file containing several files and I want to extract out just the 
.xml file.  I have that code.  Curious if this xml file can be extracted into 
memory.  If so, how to?  I only need to move the file around, and maybe read 
some tags.

Thanks for any help!

python 2.7
-- 
https://mail.python.org/mailman/listinfo/python-list


analyzing time

2013-07-05 Thread noydb
Hello All,

I have a table with a column of type date, with dates and time combined (like 
'1/6/2013 3:52:69PM'), that spans many months.  How would I pull out records 
that are the first and last entries per day?

Also, if I wanted to find time clusters per day (or per week) -- like if an 
entry is made every day around 11am -- is there a way to get at that temporal 
statistical cluster?

Python 2.7, Windows 7.

Any guidance would be greatly appreciated!  Time seems tricky...

Thanks,

N
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: advice, python for binary to xml

2013-01-31 Thread noydb
:-)  yeah...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: advice, python for binary to xml

2013-01-31 Thread noydb
On Thursday, January 31, 2013 8:41:34 AM UTC-5, Maarten wrote:
> On Thursday, January 31, 2013 2:33:48 PM UTC+1, noydb wrote:
> 
> > I'm looking for knowlegde about how best to go about converting a binary 
> > file (from a GPS unit) to GPX/XML.  I am completely clueless on this, so 
> > any start-from-the-beginning info would be greatly appreciated!  I'm 
> > guessing the level of effort will be huge?
> 
> 
> 
> I assume that you've looked into GPSBabel? http://www.gpsbabel.org/
> 
> 
> 
> Maarten

Yes, I have.  Was hoping to use it, but client is very resistent to adding such 
things to their system - python is desireable.  So what GPSbabel does is what I 
need, just one translation, from Garmin's gdb file (binary) to gpx.
-- 
http://mail.python.org/mailman/listinfo/python-list


advice, python for binary to xml

2013-01-31 Thread noydb
I'm looking for knowlegde about how best to go about converting a binary file 
(from a GPS unit) to GPX/XML.  I am completely clueless on this, so any 
start-from-the-beginning info would be greatly appreciated!  I'm guessing the 
level of effort will be huge?
Python 2.7, Windows 7
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to use subprocess to execute an exe with args and an output

2013-01-30 Thread noydb
oh DUH!  that was it, just missing the -F.  Thank-you!!

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to use subprocess to execute an exe with args and an output

2013-01-30 Thread noydb
To add on, I need to eventually write a script that takes input, feeds it into 
this exe, and takes the output file to perform more 'tools'/manipulations on 
it.  Is call or Popen called for, why?  Or maybe some other module???
-- 
http://mail.python.org/mailman/listinfo/python-list


how to use subprocess to execute an exe with args and an output

2013-01-30 Thread noydb
I am looking for some guidance on using subprocess to execute an EXE with 
arguments and an output.  The below code works in that it returns a 0 exit 
code, but no output file is created.  I have tried a few different versions of 
this code (used Popen instead, some stderr/stdout), but no luck.  Can anyone 
offer an explanation or suggestion?  (GPSBabel is freeware)
Python 2.7 on windows7 64-bit

import subprocess
subprocess.call([r"C:\Program Files (x86)\GPSBabel\gpsbabel.exe",
"-i", "gdb", "-f", r"C:\Temp\GDBdata\testgps28.gdb",
"-o", "gpx", r"C:\Temp\gpx\test28output.gpx"])

If I use this below, I get a returncode of 1, exit code of 0.
import subprocess
x = subprocess.Popen([r"C:\Program Files (x86)\GPSBabel\gpsbabel.exe",
"-i", "gdb", "-f", r"C:\Temp\GDBdata\testgps28.gdb",
"-o", "gpx", r"C:\Temp\gpx\test28output.gpx",
"shell=True", "stdout=subprocess.PIPE", 
"stderr=subprocess.PIPE"])

x.wait()
print x.returncode

Thanks in advance for any help
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: strptime - dates formatted differently on different computers

2012-12-11 Thread noydb
On Tuesday, December 11, 2012 3:35:29 AM UTC-5, Greg Donald wrote:
> On Mon, Dec 10, 2012 at 10:34:31PM -0700, Michael Torrie wrote:
> 
> > I use a module I got from pypi called dateutil.  It has a nice submodule
> 
> > called parser that can handle a variety of date formats with good
> 
> > accuracy.  Not sure how it works, but it handles all the common American
> 
> > date formats I've thrown at it.
> 
> 
> 
> from dateutil.parser import parse
> 
> dt = parse( whatever )
> 
> 
> 
> I've throw all kind of date and timestamps at it.. have yet to see anything 
> it won't parse.
> 
> 
> 
> 
> 
> --
> 
> Greg Donald


Thanks - I tried this (dateutil.parser import parsed...), and it works.  I'm 
skeptical of it working for any crazy date string thrown at it, but for my 
purposes it should suffice -- and my purposes for now was purely just 
curiousity on how to handle if it became necessary.

I tried figuring out Steve D'Aprano's solution above on my system (windows 7, 
python 2.7) - no luck.  Sorry, I am a newbie, so I'm a bit lost on this --- my 
locale module doesnt offer a nl_langinfo function -- why would this be?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: strptime - dates formatted differently on different computers

2012-12-10 Thread noydb
NTFS partition
Windows 7
Python 2.7
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: date-time comparison, aware vs naive

2012-12-10 Thread noydb

> 
> >
> 
> >
> 
> http://docs.python.org/2/library/datetime
> 
> """ An object of type *time* or *datetime* may be naive or *aware"
> 
> 
> 
> aware refers to time-zone and daylight savings time, such political
> 
> ephemerals.  Two times can only be changed if one knows they're both in
> 
> the same one, or if one knows precisely what each is.
> 
> *
> 
> naive assumes the former, while aware trusts the latter.
> 
> 
> 
> 
> 
> To the OP:  please specify your python version, your OS, and show your
> 
> source. Also show the complete error traceback.  And while you're at it,
> 
> it might be useful to know the type of drive the file is on, since
> 
> Windows uses local times on FAT32 partitions, and gmt on NTFS  partitions.
> 
> 
> 
> I suspect you're on Windows, so I can't help you with this nonsense.  But I 
> can at least help you ask a clear question.
> 
> 
> 
> -- 
> 
> 
> 
> DaveA

Fair enough, thanks
-- 
http://mail.python.org/mailman/listinfo/python-list


strptime - dates formatted differently on different computers

2012-12-10 Thread noydb
Follow-on question to this earlier topic - 
https://groups.google.com/d/topic/comp.lang.python/wnUlPBBNah8/discussion 

Was curious to know if there was a way to handle different user computers with 
different operating system set date formats.  2/10/2006 vs 2-10-2006, for 
example.  Not an issue for my current task, but was just curious how this could 
be handled?

If in my code I am declaring the user entered date foramtted as
x = datetime.datetime.strptime(user_entered_time , "%m/%d/%Y %I:%M:%S %p") # 
format for my computer

but on another person's computer, their's is set as 2-10-2006 14:26:06, the 
code fails.  Can this be accounted for?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: date-time comparison, aware vs naive

2012-12-10 Thread noydb
On Monday, December 10, 2012 3:52:55 PM UTC-5, Steven D'Aprano wrote:
> On Mon, 10 Dec 2012 11:57:37 -0800, noydb wrote:
> 
> 
> 
> > I want to compare a user entered date-and-time against the date-and-time
> 
> > of a pdf file.  I posted on this (how to get a file's date-time) before,
> 
> > was advised to do it like:
> 
> > 
> 
> > import datetime, os, stat
> 
> > mtime = os.lstat(filename)[stat.ST_MTIME]   // the files modification 
> 
> > time
> 
> 
> 
> What language are you writing? Using // for comments is not Python.
> 
> 
> 
> 
> 
> > dt = datetime.datetime.fromtimestamp(mtime)
> 
> > 
> 
> > I am having problems with the comparison, that line is failing.
> 
> 
> 
> You haven't shown us the comparison line. Would you like us to guess what 
> 
> it does?
> 
> 
> 
> My guess is that you are doing this:
> 
> 
> 
> if mtime is dtime: ... 
> 
> 
> 
> Am I close?
> 
> 
> 
> If not, please forgive me, my crystal ball is often faulty.
> 
> 
> 
> 
> 
> > I think
> 
> > I may have figured out the issue -- I think it is a matter of the file's
> 
> > time being 'aware' and the user-input date-time being 'naive'.
> 
> 
> 
> "Aware" of what?
> 
> 
> 
> 
> 
> 
> 
> -- 
> 
> Steven

Forgive me, I was just copying the code from the original reply to my orignal 
question.

Forgive me for not posting the comparison line, it goes something like
if one_time > another_time:

Forgive me - the 'aware' time vs 'naive' time refers to documentation I found 
for the datetime module, see second sentence down 
http://docs.python.org/2/library/datetime.html 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: date-time comparison, aware vs naive

2012-12-10 Thread noydb
Found this, and it solved my problem
http://blogs.law.harvard.edu/rprasad/2011/09/21/python-string-to-a-datetime-object/
-- 
http://mail.python.org/mailman/listinfo/python-list


date-time comparison, aware vs naive

2012-12-10 Thread noydb
I want to compare a user entered date-and-time against the date-and-time of a 
pdf file.  I posted on this (how to get a file's date-time) before, was advised 
to do it like:

import datetime, os, stat 
mtime = os.lstat(filename)[stat.ST_MTIME]   // the files modification time 
dt = datetime.datetime.fromtimestamp(mtime) 

I am having problems with the comparison, that line is failing.  I think I may 
have figured out the issue -- I think it is a matter of the file's time being 
'aware' and the user-input date-time being 'naive'.  The user-input date-time 
has a parameter type of date (calender and time tool supplied to enter), but is 
it 'aware'?  The comparison is not working so I think that it is not aware.  I 
can successfully compare two pdf file times against one another.  So, is there 
a way to cast that user-input value (prints as 2/10/2012 3:19:57 PM) as an 
'aware' date-time?  How?  And can anyone confirm that my findings are probably 
correct?

Thanks for any help.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: date and time comparison how to

2012-10-29 Thread noydb
On Monday, October 29, 2012 11:11:55 PM UTC-4, Dave Angel wrote:
> On 10/29/2012 10:13 PM, noydb wrote:
> 
> > I guess I get there eventually!  
> 
> > This seems to work
> 
> >
> 
> > pdf_timeStamp = 
> > time.strftime("%m%d%y%H%M%S",time.localtime(os.path.getmtime(pdf)))
> 
> > intermediateTime = time.strptime(pdf_timeStamp, "%m%d%y%H%M%S")
> 
> > pdfFile_compareTime = time.mktime(intermediateTime)
> 
> >
> 
> > (and I'll do the same to the user entered date-n-time and then compare)
> 
> >
> 
> >
> 
> > Lastly, so can anyone chime in and tell me if this is a good method or not? 
> >  Is there a better way?
> 
> 
> 
> Please read the rest of the thread in particular the message 3 hours ago
> 
> from Gary Herron
> 
> 
> 
> import datetime, os, stat
> 
> mtime = os.lstat(filename)[stat.ST_MTIME]   // the files
> 
> modification time
> 
> dt = datetime.datetime.fromtimestamp(mtime)
> 
> 
> 
> Now you can compare two datetimes simply by
> 
>if dt1 < dt2:
> 
> 
> 
> Or you can subtract them, and examine the difference.
> 
> 
> 
> What's the need for all that string conversion stuff?
> 
> 
> 
> 
> 
> 
> 
> -- 
> 
> 
> 
> DaveA

okay, I see.
But for the user supplied date... I'm not sure of the format just yet... 
testing with a string for now (actual date-date might be possible, tbd later), 
so like '10292012213000' (oct 29, 2012 9:30pm).  How would you get that input 
into a format to compare with dt above?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: date and time comparison how to

2012-10-29 Thread noydb
I guess I get there eventually!  
This seems to work

pdf_timeStamp = 
time.strftime("%m%d%y%H%M%S",time.localtime(os.path.getmtime(pdf)))
intermediateTime = time.strptime(pdf_timeStamp, "%m%d%y%H%M%S")
pdfFile_compareTime = time.mktime(intermediateTime)

(and I'll do the same to the user entered date-n-time and then compare)


Lastly, so can anyone chime in and tell me if this is a good method or not?  Is 
there a better way?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: date and time comparison how to

2012-10-29 Thread noydb
if I do time.time() I get 1351562187.757, do it again I get 1351562212.2650001 
--- so I can compare those, the latter is later then the former.  Good.  SO how 
do I turn pdf_timeStamp (a string) above into time in this (as from 
time.time()) format?  Am I on the right track -- is that the way to do a time 
comparison?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: date and time comparison how to

2012-10-29 Thread noydb
Thanks, I did find this...

pdf_timeStamp = 
time.strftime("%m%d%y%H%M%S",time.localtime(os.path.getmtime(pdf)))

>> pdf_timestamp
>> '102909133000'

... but now how to do the comparison?  Cannot just do a raw string comparison, 
gotta declare it a date
-- 
http://mail.python.org/mailman/listinfo/python-list


date and time comparison how to

2012-10-29 Thread noydb
All,

I need help with a date and time comparison.

Say a user enters a date-n-time and a file on disk.  I want to compare the date 
and time of the file to the entered date-n-time; if the file is newer than the 
entered date-n-time, add the file to a list to process.

How best to do?  I have looked at the datetime module, tried a few things, no 
luck.

Is os.stat a part of it?  Tried, not sure of the output, the st_mtime/st_ctime 
doesnt jive with the file's correct date and time.  ??

Any help would be appreciated!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: round down to nearest number

2012-02-10 Thread noydb
On Feb 10, 4:58 am, Arnaud Delobelle  wrote:
> On 10 February 2012 06:21, Ian Kelly  wrote:
>
>
>
>
>
> > (3219 + 99) // 100 * 100
> >> 3300
> > (3289 + 99) // 100 * 100
> >> 3300
> > (328678 + 99) // 100 * 100
> >> 328700
> > (328 + 99) // 100 * 100
> >> 400
>
> >> Those are all rounded up to the nearest 100 correctly.
>
> > One thing to be aware of though is that while the "round down" formula
> > works interchangeably for ints and floats, the "round up" formula does
> > not.
>
>  (3300.5 + 99) // 100 * 100
> > 3300.0
>
> I'm surprised I haven't seen:
>
> >>> 212 - (212 % -100)
>
> 300
>
> Here's a function that:
> * rounds up and down
> * works for both integers and floats
> * is only two operations (as opposed to 3 in the solutions given above)
>
> >>> def round(n, k):
>
> ...     return n - n%k
> ...>>> # Round down with a positive k:
>
> ... round(167, 100)
> 100>>> round(-233, 100
>
> ... )
> -300>>> # Round up with a negative k:
>
> ... round(167, -100)
> 200>>> round(-233, -100)
> -200
> >>> # Edge cases
>
> ... round(500, -100)
> 500>>> round(500, 100)
> 500
> >>> # Floats
>
> ... round(100.5, -100)
> 200.0>>> round(199.5, 100)
>
> 100.0
>
> --
> Arnaud- Hide quoted text -
>
> - Show quoted text -

Thanks!  Covers all bases, good.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: round down to nearest number

2012-02-09 Thread noydb
That {>>> (3219 + 99) // 100} doesnt work if the number is other then
4 digits.


(for rounding up to nearest 100):
>>> (3219 + 99)//100
33
>>> (3289 + 99)//100
33
>>> (328678 + 99)//100
3287
>>> (328 + 99)//100
4
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: round down to nearest number

2012-02-09 Thread noydb
hmmm, okay.

So how would you round UP always?  Say the number is 3219, so you want
3300 returned.
-- 
http://mail.python.org/mailman/listinfo/python-list


round down to nearest number

2012-02-09 Thread noydb
How do you round down ALWAYS to nearest 100?  Like, if I have number
3268, I want that rounded down to 3200.  I'm doing my rounding like
>>> round(3268, -2)
But, how to round DOWN?
-- 
http://mail.python.org/mailman/listinfo/python-list


Formate a number with commas

2012-02-09 Thread noydb
How do you format a number to print with commas?

Some quick searching, i came up with:

>>> import locale
>>> locale.setlocale(locale.LC_ALL, "")
>>> locale.format('%d', 2348721, True)
'2,348,721'


I'm a perpetual novice, so just looking for better, slicker, more
proper, pythonic ways to do this.

Thanks!
-- 
http://mail.python.org/mailman/listinfo/python-list


building a dictionary dynamically

2012-02-06 Thread noydb
How do you build a dictionary dynamically?  Doesn't seem to be an
insert object or anything.  So I need an empty dictionary that I then
want to populate with values I get from looping through a list and
grabbing some properties.  So simply, I have (fyi, arcpy = module for
interacting with gis data)

>>> inDict = {}
>>> for inFC in inFClist:
>>> print inFC
>>> inCount =  int(arcpy.GetCount_management(inFC).getOutput(0))


where I want to make a dictionary like {inFC: inCount, inFC:
inCount, }

How do I build this???

And, is dictionaries the best route go about doing a comparison, such
that in the end I will have two dictionaries, one for IN and one for
OUT, as in I'm moving data files and want to verify that the count in
each file matches between IN and OUT.

Thanks for any help!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: test for list equality

2011-12-15 Thread noydb
Ahh, I see (on the sort issue), thanks All!

Still, any other slicker ways to do this?  Just for learning.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: test for list equality

2011-12-15 Thread noydb
On Dec 15, 11:36 am, noydb  wrote:
> I want to test for equality between two lists.  For example, if I have
> two lists that are equal in content but not in order, I want a return
> of 'equal' -- dont care if they are not in the same order.  In order
> to get that equality, would I have to sort both lists regardless?  if
> yes, how (having issues with list.sort)?
>
> Another way i tried, that I think is kind-of roundabout is like
> x = [2, 5, 1, 88, 9]
> y = [5, 2, 9, 1, 88]
> inBoth = list(set(x) & set(y))
>
> and then test that list.count is equal between inBoth and x and/or y.
>
> Any better suggestions?
>
> Thanks for any help!

My sort issue... as in this doesn't work
>>> if x.sort == y.sort:
... print 'equal'
... else:
... print 'not equal'
...
not equal


???
-- 
http://mail.python.org/mailman/listinfo/python-list


test for list equality

2011-12-15 Thread noydb
I want to test for equality between two lists.  For example, if I have
two lists that are equal in content but not in order, I want a return
of 'equal' -- dont care if they are not in the same order.  In order
to get that equality, would I have to sort both lists regardless?  if
yes, how (having issues with list.sort)?

Another way i tried, that I think is kind-of roundabout is like
x = [2, 5, 1, 88, 9]
y = [5, 2, 9, 1, 88]
inBoth = list(set(x) & set(y))

and then test that list.count is equal between inBoth and x and/or y.


Any better suggestions?

Thanks for any help!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to make fxn argument work with setting a field value

2011-09-08 Thread noydb
> The documentation mentions "getValue" and "setValue":
>
> http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#//002z00...- 
> Hide quoted text -
>
> - Show quoted text -

I have tried row.setValue(rankFld) = i for line 14.  Get syntax error
- cant assign to function call
-- 
http://mail.python.org/mailman/listinfo/python-list


how to make fxn argument work with setting a field value

2011-09-07 Thread noydb
What do I need to do to line 14 code below to get it to recognize the
field name and not the argument name?

I get this error with below code at line 13, the print row.rankFld
line
>RuntimeError: Row: Field rankFld does not exist
A field called rankFld does not, should not exist.  rankFld is
"RANKa" (in this first iteration), which does exist (gets added in
line 6, verified).
Line 14 fails too, if 13 is commented out.


##
import arcpy

fc = r"C:\test\scratch.gdb\sort_test1"

def rank(inFC, outFC, scoreFld, popFld, rankFld):
arcpy.AddField_management(inFC, rankFld, "LONG")
arcpy.management.Sort(inFC, outFC, [[scoreFld, "DESCENDING"],
[popFld, "DESCENDING"]])
i = 0
print rankFld # >RANKa
rows = arcpy.UpdateCursor(fc)
for row in rows:
i = i + 1
print row.rankFld
row.rankFld = i ## line 14
rows.updateRow(row)

return sortedFC
#

out1 = r"C:\test\scratch.gdb\rankfxn6"
out2 = r"C:\test\scratch.gdb\rankfxn7"

rank(fc, out1, "SCOREa", "COUNT1", "RANKa")
rank(out1, out2, "SCOREb", "COUNT2", "RANKb")
##
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Adding a ranking based on two fields

2011-09-07 Thread noydb
On Aug 25, 4:53 pm, Chris Rebert  wrote:
> On Thu, Aug 25, 2011 at 1:38 PM, noydb  wrote:
> > Hello All,
>
> > Looking for some advice/ideas on how to implement arankingto a
> > 'scores' field I have.  So this scores field has values ranging from
> > 1.00-4.  There is also a count field.  I want to add a rank field such
> > that all the records have a uniqueranking, 1 through the number of
> > records (thousands).  The rank isbasedon the score first, the count
> > second.  So, a record with a score of 4 and a count of 385 is ranked
> > higher than a record with a score of 4 and a count of 213 AND higher
> > than record with a score of 3.25 with a count of 4640.
>
> > My thought was to add the unique score values to a list and loop thru
> > the list... sort records with score=listItem, addranking... not quite
> > sure how to do this!
>
> things = getListOfYourThings()
> things.sort(reverse=True, key=lambda item: (item.score, item.count))
> for i, thing in enumerate(things):
>     thing.rank = i + 1
>
> Cheers,
> Chris
> --http://rebertia.com

Thanks for this!

Someone passed this along, too - helpful
http://wiki.python.org/moin/HowTo/Sorting
-- 
http://mail.python.org/mailman/listinfo/python-list


Adding a ranking based on two fields

2011-08-25 Thread noydb
Hello All,

Looking for some advice/ideas on how to implement a ranking to a
'scores' field I have.  So this scores field has values ranging from
1.00-4.  There is also a count field.  I want to add a rank field such
that all the records have a unique ranking, 1 through the number of
records (thousands).  The rank is based on the score first, the count
second.  So, a record with a score of 4 and a count of 385 is ranked
higher than a record with a score of 4 and a count of 213 AND higher
than record with a score of 3.25 with a count of 4640.

My thought was to add the unique score values to a list and loop thru
the list... sort records with score=listItem, add ranking... not quite
sure how to do this!

Any help would be much appreciated!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to convert a list of strings into a list of variables

2011-08-19 Thread noydb
Thanks to all for your responses!  Good lessons.  I implemented
something like what Jerry Hill suggested (dictionary), which works
well for my purposes.  The list of strings that is being passed into
this code is also provided by something I wrote so I do trust what is
being sent.  Might use what AB suggested down the line, as tool
expands.  Thanks!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to convert a list of strings into a list of variables

2011-08-18 Thread noydb
On Aug 18, 11:29 am, Jerry Hill  wrote:
> On Thu, Aug 18, 2011 at 11:19 AM, noydb  wrote:
> > I am being passed the list of strings.  I have variables set up
> > already pointing to files.  I need to loop through each variable in
> > the list and do things to the files.  The list of strings will change
> > each time, include up to 22 of the same strings each time.
>
> If you have a mapping of strings to values, you should just go ahead
> and store them in a dictionary.  Then the lookup becomes simple:
>
> def foo(list_of_strings):
>         mapping = {
>                 "bar0": "/var/log/bar0.log",
>                 "bar1": "/usr/local/bar/bar1.txt",
>                 "bar2": "/home/joe/logs/bar2.log",
>         }
>         for item in list_of_strings:
>                 filename = mapping[item]
>                 do_something(filename)
>
> (Untested)
>
> --
> Jerry

Thanks, implemented something along those lines, and it worked!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to convert a list of strings into a list of variables

2011-08-18 Thread noydb
On Aug 18, 11:12 am, David Robinow  wrote:
> On Thu, Aug 18, 2011 at 10:57 AM, noydb  wrote:
> > How would you convert a list of strings into a list of variables using
> > the same name of the strings?
>
> > So, ["red", "one", "maple"] into [red, one, maple]
>
>   Why would you want to?

I am being passed the list of strings.  I have variables set up
already pointing to files.  I need to loop through each variable in
the list and do things to the files.  The list of strings will change
each time, include up to 22 of the same strings each time.
-- 
http://mail.python.org/mailman/listinfo/python-list


How to convert a list of strings into a list of variables

2011-08-18 Thread noydb
How would you convert a list of strings into a list of variables using
the same name of the strings?

So, ["red", "one", "maple"] into [red, one, maple]

Thanks for any help!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How best to convert a string "list" to a python list

2011-05-13 Thread noydb
On May 13, 1:25 pm, Mark Niemczyk  wrote:
> There are a series of built-in methods for string objects; including the 
> split method which will accomplish exactly the result you are looking for.
>
> >>> x = "red;blue;green;yellow"
> >>> color_list = x.split(';')
> >>> color_list
>
> ['red', 'blue', 'green', 'yellow']
>
>
>
> Here is the link to a discussion of the build-in str methods (3.2), but this 
> documentation exists for prior versions of Python as well.
>
>      http://docs.python.org/py3k/library/stdtypes.html#str.split
>
> Good luck,
>
> Mark Niemczyk

Haha!  This is why I ask, because my code is pretty laughable and
elementary!  I'm learning...
Thanks Mark!
-- 
http://mail.python.org/mailman/listinfo/python-list


How best to convert a string "list" to a python list

2011-05-13 Thread noydb
I want some code to take the items in a semi-colon-delimted string
"list" and places each in a python list.  I came up with below.  In
the name of learning how to do things properly, do you experts have a
better way of doing it?

Thanks for any inputs!

***
x = "red;blue;green;yellow" ## string of semi-colon delimited colors

color_list = []
## sc = semi-colon

while x.find(";") <> -1:
sc_pos = x.find(";")
current_color = x[0:sc_pos] ## color w/o sc
current_color_sc = x[0:sc_pos+1] ## color with sc
color_list.append(current_color) ## append color to list
x = x.replace(current_color_sc, "") ## remove color and sc from
string
print current_color
print color_list
print x + "\n"

color_list.append(x) # append last color left in x (no sc at end of
string)
print color_list

print "done"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Two random lists from one list

2011-03-18 Thread noydb
Thanks All for your responses, all a help!
-- 
http://mail.python.org/mailman/listinfo/python-list


Two random lists from one list

2011-03-11 Thread noydb
Hello All,

I am just looking to see if there is perhaps a more efficient way of
doing this below (works -- creates two random teams from a list of
players).  Just want to see what the experts come up with for means of
learning how to do things better.

Thanks for any responses!

###
import random
players = ["jake", "mike", "matt", "rich", "steve", "tom", "joe",
"jay"]
teamA = random.sample(players, 4)
print teamA
teamB = []
for p in players:
if p not in teamA:
teamB.append(p)
print teamB
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: frequency of values in a field

2011-02-09 Thread noydb
On Feb 9, 3:28 pm, Ethan Furman  wrote:
> noydb wrote:
>
>  > Paul Rubin wrote:
>
>
>
>
>
> >> The Decimal module is pretty slow but is conceptually probably the right
> >> way to do this.  With just 50k records it shouldn't be too bad.  With
> >> more records you might look for a faster way.
>
> >>     from decimal import Decimal as D
> >>     from collections import defaultdict
>
> >>     records = ['3.14159','2.71828','3.142857']
>
> >>     td = defaultdict(int)
> >>     for x in records:
> >>         td[D(x).quantize(D('0.01'))] += 1
>
> >>     print td
>
> > I played with this - it worked.  Using Python 2.6 so counter no good.
>
> > I require an output text file of sorted "key value" so I added
> > (further code to write out to an actual textfile, not important here)
> >>> for z in sorted(set(td)):
> >>>     print z, td[z]
>
> > So it seems the idea is to add all the records in the particular field
> > of interest into a list (record).  How does one do this in pure
> > Python?
> > Normally in my work with gis/arcgis sw, I would do a search cursor on
> > the DBF file and add each value in the particular field into a list
> > (to populate records above).  Something like:
>
> > --> import arcgisscripting
> > --> # Create the geoprocessor object
> > --> gp = arcgisscripting.create()
> > --> records_list = []
> > --> cur = gp.SearchCursor(dbfTable)
> > --> row = cur.Next()
> > --> while row:
> > -->    value = row.particular_field
> > -->    records_list.append(value)
>
> Are you trying to get away from arcgisscripting?  There is a pure python
> dbf package on PyPI (I know, I put it there ;) that you can use to
> access the .dbf file in question (assuming it's a dBase III, IV, or
> FoxPro format).
>
> http://pypi.python.org/pypi/dbf/0.88.16if you're interested.
>
> Using it, the code above could be:
>
> -
> import dbf
> from collections import defaultdict
> from decimal import Decimal
>
> table = dbf.Table('path/to/table/table_name')
>
> freq = defaultdict(int)
> for record in table:
>      value = Decimal(record['field_of_interest'])
>      key = value.quantize(Decimal('0.01'))
>      freq[key] += 1
>
> for z in sorted(freq):
>      print z, freq[z]
>
> -
>
> Numeric/Float field types are returned as python floats*, so there may
> be slight discrepancies between the stored value and the returned value.
>
> Hope this helps.
>
> ~Ethan~
>
> *Unless created with zero decimal places, in which case they are
> returned as python integers.- Hide quoted text -
>
> - Show quoted text -



Oops, didn't see htis before I posted last.

Thanks!  I'll try this, looks good, makes sense.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: frequency of values in a field

2011-02-09 Thread noydb
On Feb 9, 3:08 pm, Josh English  wrote:
> On Wednesday, February 9, 2011 10:34:12 AM UTC-8, noydb wrote:
>
> > How do you add all the records in the particular field of interest
> > into long_list?
>
> Sorry to be unclear. In both cases I was tossing out pseudo-code, as I am not 
> familiar with the arggisscripting module. long_list is a list with the 
> records you want, or an iterator that goes through the records. The get_key 
> function does whatever you need it to do to get the key by which you are 
> counting.
>
>  Andreas offers a nice pythonic solution in this thread.
>
> Josh


I apologize if I am not being clear.  Bear with me, I am not a
programmer by trade, just someone who has to delve into some python
scripting occasionally (which I do enjoy!).

No, I do not mean "use no imports whatsoever".  Just don't want to use
ArcGIS sw's module arcgisscritping -- fine to use when needed for GIS
processing, but some of my scripts do not need it whatsoever, as I
suspect in this case. I have a solution in place, which is fine, but I
used arcgisscripting simply to put a search cursor on that field to
get the values.  This certainly can be done without arcgisscripting,
which does add a bit of time to the running of the script.  i just do
not know how outside of using arcgisscripting search cursor.  Just
looking to learn how...

So, in my scenario, taking into account suggested snippets above
long_list would start out empty.  The values to go into long_list are
in one field in a dbf table that contains thousands of records.  I
need to create a text file containing all the frequencies of values
(only to 2 decimal places... in the form "key count").  How do I get
those values from the field into the empty list so that this code.
Everything else is figured out (textfile, getting the frequencies (per
suggestions above)) - just want to know how to add all the values in
the column into the empty list?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: frequency of values in a field

2011-02-09 Thread noydb
On Feb 9, 1:21 pm, Josh English  wrote:
> On Wednesday, February 9, 2011 9:52:27 AM UTC-8, noydb wrote:
>
> > So it seems the idea is to add all the records in the particular field
> > of interest into a list (record).  How does one do this in pure
> > Python?
> > Normally in my work with gis/arcgis sw, I would do a search cursor on
> > the DBF file and add each value in the particular field into a list
> > (to populate records above).  Something like:
>
> I'm not sure I understand what you mean by "pure Python." Decimal and 
> collections are part of the standard library.
>
> If you mean "use no imports whatsoever," the code would look like:
>
> counts = {}
> for thing in long_list:
>   key = make_key(thing)
>   if key in counts:
>     counts[key] += 1
>   else:
>     counts[key] = 1
>
> But using a few imports is cleaner and just as easy to troubleshoot.
>
> Josh

How do you add all the records in the particular field of interest
into long_list?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: frequency of values in a field

2011-02-09 Thread noydb
>
> The Decimal module is pretty slow but is conceptually probably the right
> way to do this.  With just 50k records it shouldn't be too bad.  With
> more records you might look for a faster way.
>
>     from decimal import Decimal as D
>     from collections import defaultdict
>
>     records = ['3.14159','2.71828','3.142857']
>
>     td = defaultdict(int)
>     for x in records:
>         td[D(x).quantize(D('0.01'))] += 1
>
>     print td
>

I played with this - it worked.  Using Python 2.6 so counter no good.

I require an output text file of sorted "key value" so I added
(further code to write out to an actual textfile, not important here)
>> for z in sorted(set(td)):
>> print z, td[z]

So it seems the idea is to add all the records in the particular field
of interest into a list (record).  How does one do this in pure
Python?
Normally in my work with gis/arcgis sw, I would do a search cursor on
the DBF file and add each value in the particular field into a list
(to populate records above).  Something like:

>> import arcgisscripting
>> # Create the geoprocessor object
>> gp = arcgisscripting.create()
>> records_list = []
>> cur = gp.SearchCursor(dbfTable)
>> row = cur.Next()
>> while row:
>>value = row.particular_field
>>records_list.append(value)

-- 
http://mail.python.org/mailman/listinfo/python-list


frequency of values in a field

2011-02-08 Thread noydb
I am looking for ways to go about capturing the frequency of unique
values in one field in a dbf table which contains ~50k records.  The
values are numbers with atleast 5 digits to the right of the decimal,
but I want the frequency of values to only 2 decimal places.  I do
have a method to do this courtesy of a provided tool in ArcGIS.  Was
just curious about ways to do it without arcgis sw, using just python.

Saw this http://code.activestate.com/recipes/277600-one-liner-frequency-count/
using itertools.

I'd be curious to see how experienced pythoners' (or not too
experienced!) would go about doing this.

Thanks for any snippets provided, this should be interesting and
educating!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to add data into exisitng Excel file at next open row?

2010-12-05 Thread noydb
On Dec 5, 8:42 am, Steve Holden  wrote:
> On 12/3/2010 6:21 PM, noydb wrote:
>
>
>
>
>
> > How can you determine the next open row in an existing Excel file such
> > that you can start adding data to the cells in that row?  As in below,
> > I want a variable in place of the 6 (row 6 in the four ws1.Cells(x,1)
> > lines), but have no other way of knowing what row I am on besides
> > looking to the first free cell in column A.  How to do?  Examples I
> > see make it seem really complicated - this can't be that hard.
>
> > Thanks for any help.
>
> > worksheet = "C:\\Excel_Reports\\ea" + ea + "report"# + ".xls"
> > xlApp = win32com.client.Dispatch("Excel.Application")
> > xlApp.Visible = 1
> > xlApp.Workbooks.Open(worksheet) ## for existing file
> > ##xlApp.SheetsInNewWorkbook = 1
> > ##wb = xlApp.Workbooks()
> > ws1 = xlApp.Worksheets(1)
>
> > ws1.Cells(6,1).Value = "selection"
> > ws1.Cells(6,2).Value = count
> > ws1.Cells(6,3).Value = epcFloat
> > ws1.Cells(6,8).Value = currentGMT
>
> > wb.SaveAs(worksheet)
> > wb.Close(False) ## False/1
>
> You might want to take a look at the xlrd library. This lets you read
> Excel spreadsheets even on Unix platforms and without the use of COM
> magic. There's also an xlwt module for writing spreadsheets. However I
> understand that the two together may not be as convenient as modifying a
> spreadsheet in place.
>
> In particular, if sh is a spreadsheet then sh.nrows gives you the number
> of rows currently used in the sheet.
>
> regards
>  Steve
> --
> Steve Holden           +1 571 484 6266   +1 800 494 3119
> PyCon 2011 Atlanta March 9-17      http://us.pycon.org/
> See Python Video!      http://python.mirocommunity.org/
> Holden Web LLC                http://www.holdenweb.com/- Hide quoted text -
>
> - Show quoted text -

Thanks, good to keep in mind.  I have used xlrd before in cases where
i'm not sure if excel is installed on a user's machine.

Someone else helped, provided this>

   NextRow = ws1.Range("A1").SpecialCells(xlLastCell).Row + 1

Although to get it to work for me, I have to use the number code for
some reason, like >

   NextRow = ws1.Range("A1").SpecialCells(11).Row + 1
-- 
http://mail.python.org/mailman/listinfo/python-list


How to add data into exisitng Excel file at next open row?

2010-12-03 Thread noydb
How can you determine the next open row in an existing Excel file such
that you can start adding data to the cells in that row?  As in below,
I want a variable in place of the 6 (row 6 in the four ws1.Cells(x,1)
lines), but have no other way of knowing what row I am on besides
looking to the first free cell in column A.  How to do?  Examples I
see make it seem really complicated - this can't be that hard.

Thanks for any help.

worksheet = "C:\\Excel_Reports\\ea" + ea + "report"# + ".xls"
xlApp = win32com.client.Dispatch("Excel.Application")
xlApp.Visible = 1
xlApp.Workbooks.Open(worksheet) ## for existing file
##xlApp.SheetsInNewWorkbook = 1
##wb = xlApp.Workbooks()
ws1 = xlApp.Worksheets(1)

ws1.Cells(6,1).Value = "selection"
ws1.Cells(6,2).Value = count
ws1.Cells(6,3).Value = epcFloat
ws1.Cells(6,8).Value = currentGMT

wb.SaveAs(worksheet)
wb.Close(False) ## False/1
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to run an EXE, with argument, capture output value

2010-11-19 Thread noydb
Thanks to Jerry Hill above who helped.
This worked:

from pywinauto.application import Application
app = Application()
app.start_(r'C:\temp\hallbig2.exe')
app.Form1.Edit6.TypeKeys(r'C:\temp\input\Ea39j.txt')
E_Value = ""
while (E_Value == ""):
app.Form1.Compute.Click()
E_Value = app.Form1.Edit8.WindowText()
print repr(E_Value)
app.Kill_()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to run an EXE, with argument, capture output value

2010-11-19 Thread noydb
Any other help?  I am guessing not, just wanted to try one more time.
Could really use help, please!!

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to run an EXE, with argument, capture output value

2010-11-18 Thread noydb
On Nov 18, 6:20 pm, noydb  wrote:
> On Nov 18, 5:54 pm, noydb  wrote:
>
>
>
>
>
> > On Nov 18, 5:22 pm, Tim Harig  wrote:
>
> > > On 2010-11-18, noydb  wrote:
>
> > > > import subprocess
> > > > pig = subprocess.Popen(["C:\Halls\hallbig2.exe"],
> > > > stdin=subprocess.PIPE, stdout=subprocess.PIPE)
> > > > result = pig.communicate(input='C:\Halls\Input\Ea39j.txt')[-1] #I need
> > > > to capture the, what I think is the, last output
>
> > > From the subprocess documentation:
>
> > >            [62]communicate() returns a tuple (stdoutdata, stderrdata).
> > >            Note that if you want to send data to the process's stdin,
> > >            you need to create the Popen object with stdin=PIPE. Similarly,
> > >            to get anything other than None in the result tuple, you need
> > >            to give stdout=PIPE and/or stderr=PIPE too.
>
> > > By using index [-1] you are accessing the processes stderr stream.  I am
> > > not really sure why you changed it.  It doesn't give you the last output.
> > > Index 0 gives you *all* of stdout and index 1 gives you *all* of stderr,
> > > period.  If you wish to further disect the output to get say the last 
> > > line,
> > > then you will need to parse it separately.
>
> > Okay, I see now.  I did run it to start with 0 -- still same result no
> > matter if 0 or -1.
> > So, what is result (stdout, using [0]) in this case?  (yes, i know I
> > sound dumb - programming is not my background, obviously).  A list,
> > tuple???  How do you access stdout (or is it stdoutdata?) results?  I
> > have tried, get errors with all attempts.  The exe gui returns several
> > statistical values uopn inputing a text file (containing numerous
> > lines of  ) and clicking compute - I want just one
> > of the values.
>
> > > > print result
> > > > print pig.returncode
> > > >>> None
> > > >>> 0
>
> > > > So the tuple is empty. ??  The exe executes fine and returns output in
> > > > th exe tool itself.  The python script seems to execute fine, no
> > > > errors, '...returned exit code 0'.  Any ideas/suggestions?
>
> > > No the tuple contains two items (stdout, stderr).  The first is what the
> > > program printed to its stdout stream (which is most likely the output you
> > > see if you run the command at a terminal/console).  The second is what it 
> > > printed to its
> > > stderr stream which is a channel used for out of band data such as error 
> > > or
> > > status messages.  In this case, it is None, because you did open stderr 
> > > as a
> > > subprocess.PIPE.- Hide quoted text -
>
> > - Show quoted text -- Hide quoted text -
>
> > - Show quoted text -
>
> stdout is a file object- Hide quoted text -
>
> - Show quoted text -

if I do
>>> print pig.communicate()
('', None)

Doesn't that mean it is empty?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to run an EXE, with argument, capture output value

2010-11-18 Thread noydb
On Nov 18, 5:54 pm, noydb  wrote:
> On Nov 18, 5:22 pm, Tim Harig  wrote:
>
>
>
>
>
> > On 2010-11-18, noydb  wrote:
>
> > > import subprocess
> > > pig = subprocess.Popen(["C:\Halls\hallbig2.exe"],
> > > stdin=subprocess.PIPE, stdout=subprocess.PIPE)
> > > result = pig.communicate(input='C:\Halls\Input\Ea39j.txt')[-1] #I need
> > > to capture the, what I think is the, last output
>
> > From the subprocess documentation:
>
> >            [62]communicate() returns a tuple (stdoutdata, stderrdata).
> >            Note that if you want to send data to the process's stdin,
> >            you need to create the Popen object with stdin=PIPE. Similarly,
> >            to get anything other than None in the result tuple, you need
> >            to give stdout=PIPE and/or stderr=PIPE too.
>
> > By using index [-1] you are accessing the processes stderr stream.  I am
> > not really sure why you changed it.  It doesn't give you the last output.
> > Index 0 gives you *all* of stdout and index 1 gives you *all* of stderr,
> > period.  If you wish to further disect the output to get say the last line,
> > then you will need to parse it separately.
>
> Okay, I see now.  I did run it to start with 0 -- still same result no
> matter if 0 or -1.
> So, what is result (stdout, using [0]) in this case?  (yes, i know I
> sound dumb - programming is not my background, obviously).  A list,
> tuple???  How do you access stdout (or is it stdoutdata?) results?  I
> have tried, get errors with all attempts.  The exe gui returns several
> statistical values uopn inputing a text file (containing numerous
> lines of  ) and clicking compute - I want just one
> of the values.
>
>
>
>
>
> > > print result
> > > print pig.returncode
> > >>> None
> > >>> 0
>
> > > So the tuple is empty. ??  The exe executes fine and returns output in
> > > th exe tool itself.  The python script seems to execute fine, no
> > > errors, '...returned exit code 0'.  Any ideas/suggestions?
>
> > No the tuple contains two items (stdout, stderr).  The first is what the
> > program printed to its stdout stream (which is most likely the output you
> > see if you run the command at a terminal/console).  The second is what it 
> > printed to its
> > stderr stream which is a channel used for out of band data such as error or
> > status messages.  In this case, it is None, because you did open stderr as a
> > subprocess.PIPE.- Hide quoted text -
>
> - Show quoted text -- Hide quoted text -
>
> - Show quoted text -

stdout is a file object
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to run an EXE, with argument, capture output value

2010-11-18 Thread noydb
On Nov 18, 5:22 pm, Tim Harig  wrote:
> On 2010-11-18, noydb  wrote:
>
> > import subprocess
> > pig = subprocess.Popen(["C:\Halls\hallbig2.exe"],
> > stdin=subprocess.PIPE, stdout=subprocess.PIPE)
> > result = pig.communicate(input='C:\Halls\Input\Ea39j.txt')[-1] #I need
> > to capture the, what I think is the, last output
>
> From the subprocess documentation:
>
>            [62]communicate() returns a tuple (stdoutdata, stderrdata).
>            Note that if you want to send data to the process's stdin,
>            you need to create the Popen object with stdin=PIPE. Similarly,
>            to get anything other than None in the result tuple, you need
>            to give stdout=PIPE and/or stderr=PIPE too.
>
> By using index [-1] you are accessing the processes stderr stream.  I am
> not really sure why you changed it.  It doesn't give you the last output.
> Index 0 gives you *all* of stdout and index 1 gives you *all* of stderr,
> period.  If you wish to further disect the output to get say the last line,
> then you will need to parse it separately.

Okay, I see now.  I did run it to start with 0 -- still same result no
matter if 0 or -1.
So, what is result (stdout, using [0]) in this case?  (yes, i know I
sound dumb - programming is not my background, obviously).  A list,
tuple???  How do you access stdout (or is it stdoutdata?) results?  I
have tried, get errors with all attempts.  The exe gui returns several
statistical values uopn inputing a text file (containing numerous
lines of  ) and clicking compute - I want just one
of the values.

>
> > print result
> > print pig.returncode
> >>> None
> >>> 0
>
> > So the tuple is empty. ??  The exe executes fine and returns output in
> > th exe tool itself.  The python script seems to execute fine, no
> > errors, '...returned exit code 0'.  Any ideas/suggestions?
>
> No the tuple contains two items (stdout, stderr).  The first is what the
> program printed to its stdout stream (which is most likely the output you
> see if you run the command at a terminal/console).  The second is what it 
> printed to its
> stderr stream which is a channel used for out of band data such as error or
> status messages.  In this case, it is None, because you did open stderr as a
> subprocess.PIPE.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to run an EXE, with argument, capture output value

2010-11-18 Thread noydb
I will use 2.5.

I tried your suggestion, with this code

import subprocess
pig = subprocess.Popen(["C:\Halls\hallbig2.exe"],
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
result = pig.communicate(input='C:\Halls\Input\Ea39j.txt')[-1] #I need
to capture the, what I think is the, last output
print result
print pig.returncode
>> None
>> 0

So the tuple is empty. ??  The exe executes fine and returns output in
th exe tool itself.  The python script seems to execute fine, no
errors, '...returned exit code 0'.  Any ideas/suggestions?
-- 
http://mail.python.org/mailman/listinfo/python-list


How to run an EXE, with argument, capture output value

2010-11-17 Thread noydb
Hello All,

I would appreciate some guidance on this.  I'm a newbe, sorry if I
sound dumb - I kind of am on this stuff!

I have an executable that I want to run within python code.  The exe
requires an input text file, the user to click a 'compute' button, and
then the exe calculates several output values, one of which I want to
capture into a variable.  Can I use Python to supply the input file,
execute the exe and capture the output value, like such that the exe
really doesn't need to be 'seen'?  Or, would the user still have to
click the 'compute' button?

Any code snippets or guidance would be very much appreciated.  I have
found that

import os
os.system('C:\xTool\stats_hall.exe')

will run the exe.  And, maybe these execl/execle/execlp/etc functions
might be what I need for adding in the argument, but documentation
seems to indicate that these do not return output.  ??

Thanks much.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: save xls to csv/dbf without Excel/win32com.client

2010-06-06 Thread noydb
On Jun 5, 9:31 pm, Tim Chase  wrote:
> On 06/05/2010 06:47 PM, noydb wrote:
>
> > Is there a way to save a .xls file (the first worksheet) as a .dbf
> > or .csv without opening an instance of Excel with win32com.client
> > (been awhile, is this the best module these days for v2.5)?  In case a
> > computer does not have Excel (2007) installed.
>
> Use the "xlrd" module[1]
>
> 
> import csv
> import xlrd
>
> FILE_NAME = 'example.xls'
> wb = xlrd.open_workbook(FILE_NAME)
>
> for name in wb.sheet_names():
>    out = file('%s.csv' % name, 'wb')
>    writer = csv.writer(out)
>    sheet = wb.sheet_by_name(name)
>    for row in xrange(sheet.nrows):
>      writer.writerow([
>        sheet.cell_value(row, col)
>        for col in xrange(sheet.ncols)
>        ])
>    out.close()
> #
>
> You say you only want the first sheet, so adjust accordingly.
>
> -tkc
>
> [1]http://pypi.python.org/pypi/xlrd/

Many thanks Tim, this worked well!

In the interest of learning, anyone have a XLS to DBF solution?
-- 
http://mail.python.org/mailman/listinfo/python-list


save xls to csv/dbf without Excel/win32com.client

2010-06-05 Thread noydb
Is there a way to save a .xls file (the first worksheet) as a .dbf
or .csv without opening an instance of Excel with win32com.client
(been awhile, is this the best module these days for v2.5)?  In case a
computer does not have Excel (2007) installed.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rounding up to the next 100

2010-01-21 Thread noydb
Sorry, although what I really need is the string-number rounded UP
every time.  So if the number is 3890.32, it needs to go to 3900; if
the number is 3811.345, it needs to go to 3900 also.

So, Florian's answer works.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rounding up to the next 100

2010-01-21 Thread noydb
On Jan 21, 4:30 pm, michael.coll-ba...@verizonwireless.com wrote:
> > From: noydb
> > If one has a floating number as a string, is there a spiffy way to
> > round that string-number UP to the nearest 100?
>
> > XstrNmbr = 3579.127893 -- would want to round that to 3600.
>
> What's wrong with round?  round( XstrNmbr, -2 ) seems to do the trick.
> Or do you want to get rid of the decimal point as well?
>
> The information contained in this message and any attachment may be
> proprietary, confidential, and privileged or subject to the work
> product doctrine and thus protected from disclosure.  If the reader
> of this message is not the intended recipient, or an employee or
> agent responsible for delivering this message to the intended
> recipient, you are hereby notified that any dissemination,
> distribution or copying of this communication is strictly prohibited.
> If you have received this communication in error, please notify me
> immediately by replying to this message and deleting it and all
> copies and backups thereof.  Thank you.

Thanks Arnaud!

Michael - Nothing is wrong with round -- when I tried it initially, I
was confused on the base -- seeing it from this example helped clear
it up.
-- 
http://mail.python.org/mailman/listinfo/python-list


Rounding up to the next 100

2010-01-21 Thread noydb
If one has a floating number as a string, is there a spiffy way to
round that string-number UP to the nearest 100?

XstrNmbr = 3579.127893 -- would want to round that to 3600.

Thanks for any help!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pause a script before termination

2009-11-11 Thread noydb
On Nov 11, 11:43 am, noydb  wrote:
> Hi All,
>
> I want to pause my script before it terminates, just so a user can
> have a moment to read some print statements I include at the end.  How
> can this be accomplished?
>
> Thanks!

Never mind, duh, found my answer now

import time
time.sleep(10)  #10 second pause
-- 
http://mail.python.org/mailman/listinfo/python-list


Pause a script before termination

2009-11-11 Thread noydb
Hi All,

I want to pause my script before it terminates, just so a user can
have a moment to read some print statements I include at the end.  How
can this be accomplished?

Thanks!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: string character count

2009-07-02 Thread noydb
thanks everyone for all the ideas -- simple stuff, I know for you all,
but very helpful for me.
-- 
http://mail.python.org/mailman/listinfo/python-list


string character count

2009-06-30 Thread noydb
If I have a string for a file name such that I want to find the number
of characters to the left of the dot, how can that be done?

I did it this way:
x = "text12345.txt"
dot = x.find('.')
print dot

Was curious to see what method others would use - helps me learn.  I
guess I was most curious to see if it could be done in one line.

And, how would a char count be done with no dot -- like if the string
were "textstringwithoutdot" or "no dot in text string"?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: putting date strings in order

2009-05-14 Thread noydb
On May 14, 4:13 pm, Scott David Daniels  wrote:
> Peter Otten wrote:
> > Hm, if ordered_raster_list is guaranteed to contain one string item for
> > every month the above can be simplified to
>
> > months = [
> >     'precip_jan', 'precip_feb', 'precip_mar', 'precip_apr',
> >     'precip_may', 'precip_jun', 'precip_jul', 'precip_aug',
> >     'precip_sep', 'precip_oct', 'precip_nov', 'precip_dec']
>
> > start = 2
> > ordered_raster_list = months[start-1:] + months[:start-1]
>
> Or even:
>  >
>      multi_months = [
>          'precip_jan', 'precip_feb', 'precip_mar', 'precip_apr',
>          'precip_may', 'precip_jun', 'precip_jul', 'precip_aug',
>          'precip_sep', 'precip_oct', 'precip_nov', 'precip_dec'] * 2
>      start = 2
>      ordered_raster_list = multi_months[start - 1: start + 11]
>
> --Scott David Daniels
> scott.dani...@acm.org

Peter and Scott --

ordered_raster_list is guaranteed to have one string item for all 12
months -- it is just NOT guaranteed to have those in chronological
order, which is what is required, whether the data starts in january
(thus ending in dec of same year) or august (thus ending in jul of the
following year) or whenever.  The initial order of the list is
dictated by when the raster (precip_) was added to it's
container.  One would hope the rasters would be added in order, but I
cannot count on that and shouldn't.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: putting date strings in order

2009-05-14 Thread noydb
On May 12, 12:26 pm, John Machin  wrote:
> On May 13, 1:58 am, Jaime Fernandez del Rio 
> wrote:
>
>
>
>
>
> > On Tue, May 12, 2009 at 5:02 PM, MRAB  wrote:
> > > John Machin wrote:
>
> > >> MRAB  mrabarnett.plus.com> writes:
>
> > >>> Sort the list, passing a function as the 'key' argument. The function
> > >>> should return an integer for the month, eg 0 for 'jan', 1 for 'feb'. If
> > >>> you want to have a different start month then add
>
> > >> and if you don't like what that produces, try subtract :-)
>
> > > Oops!
>
> > >>> the appropriate
> > >>> integer for that month (eg 0 for 'jan', 1 for 'feb') and then modulo 12
> > >>> to make it wrap around (there are only 12 months in a year), returning
> > >>> the result.
>
> > > Actually, subtract the start month, add 12, and then modulo 12.
>
> > Both on my Linux and my Windows pythons, modulos of negative numbers
> > are properly taken, returning always the correct positive number
> > between 0 and 11. I seem to recall, from my distant past, that Perl
> > took pride on this being a language feature. Anyone knows if that is
> > not the case with python, and so not adding 12 before taking the
> > modulo could result in wrong results in some implementations?
>
> If that happens, it's a 
> bug.http://docs.python.org/reference/expressions.html#binary-arithmetic-o...
>
> If you look at function i_divmod() in the 2.x branch's Objects/
> intobject.c, you'll be reassured to see that it doesn't just take
> whatever C serves up :-)- Hide quoted text -
>
> - Show quoted text -

Thanks to those who provided suggestions.  I ended up using code
similar to what Jaime provided above first -- truly eloquent and
simple, especially compared to my original thoughts of several messy
loops.  I knew it could be done way better.  Thanks very much Jaime!!
That was a good learning experience for me.

fairly finished portion of code:

ordered_raster_list = []

pRasters = gp.ListRasters("precip_*", "All") # an enumeration object,
arcgis method
pRast = pRasters.next()
while pRast:
##month = pRast[-3:]
##print month
print pRast
ordered_raster_list.append(pRast)
pRast = pRasters.next()


print ordered_raster_list #unordered at this point

# create a dictionary dictating the order of the the precip_
rasters
monthsD = {"precip_jan" : 1, "precip_feb" : 2, "precip_mar" : 3,
"precip_apr" : 4, "precip_may" : 5, "precip_jun" : 6,
   "precip_jul" : 7, "precip_aug" : 8, "precip_sep" : 9,
"precip_oct" : 10, "precip_nov" : 11, "precip_dec" : 12}

# sort the list based on the dictionary
ordered_raster_list.sort(None, lambda x : monthsD[x])

print ordered_raster_list #ordered

start = 2 #user to define, starting month

ordered_raster_list = ordered_raster_list[start - 1:] +
ordered_raster_list[:start - 1]

print ordered_raster_list #ordered but starting in the middle, feb in
this case, ending with jan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: putting date strings in order

2009-05-12 Thread noydb
On May 11, 11:30 pm, Paul Rubin <http://phr...@nospam.invalid> wrote:
> noydb  writes:
> > Anyone have any good ideas?  I was curious to see what people came up
> > with.
>
> Is this a homework assignment?  Some hints:
>
> 1) figure out how to compare two month names for chronological order,
>    leaving out the issue of the starting month not being january.
> 2) figure out how to adjust for the starting month.  The exact
>    semantics of the "%" operator might help do this concisely.

Ha!  No, this is not a homework assignment.  I just find myself to be
not the most eloquent and efficient scripter and wanted to see how
others would approach it.

I'm not sure how I follow your suggestion.  I have not worked with the
%.  Can you provide a snippet of your idea in code form?

I thought about assigning a number string (like 'x_1') to any string
containing 'jan' -- so x_jan would become x_1, and so on.  Then I
could loop through with a counter on the position of the number (which
is something i will need to do, comparing one month to the next
chronological month, then that next month to its next month, and so
on).  And as for the starting postion, the user could declare, ie, aug
the start month.  aug is position 8.  therefore subtract 7 from each
value, thus aug becomes 1 but then I guess early months would have
to be add 5, such that july would become 12.  Ugh, seems sloppy to me.

Something like that   seems poor to me.  Anybody have a bteer
idea, existing code???
-- 
http://mail.python.org/mailman/listinfo/python-list


putting date strings in order

2009-05-11 Thread noydb
All,

How best to go about this?  >>

I have a list containing strings referring to months, like ["x_apr",
"x_jul", "x_jan", "x_aug", "x_may", etc] -- always using the 3-chars
for month.  The list will contain all 12 months, however the starting
month may not necessarily be jan.  I want to order the list
chronologically, but starting with the user-defined starting month.
So a list could be [x_aug, x_sep,  x_jul].  The list might just
start off in any random order, but I need to ensure, in the end, that
the list is in chronological order and starting with the proper month
per user needs.

Anyone have any good ideas?  I was curious to see what people came up
with.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rename of .mdb file -- lock

2008-12-11 Thread noydb
On Dec 11, 9:38 pm, "gudonghua+pyt...@gmail.com" 
wrote:
> On Dec 12, 10:15 am, noydb  wrote:
>
>
>
> > All,
>
> > I have the code below, which unzips a zipfile containing only one
> > file.  Once it is unzipped, I want to rename the file based on a user
> > provided name.  But I get this (WindowsError: [Error 32] The process
> > cannot access the file because it is being used by another process)
> > error, which does not make sense to me as no other apps are open.
>
> > Any suggestions?
>
> > Thanks!
>
> > CODE
> > # Declare the zip file directory and name (shouldn't change, in a
> > permanent location)
> > mdb_zip = ("C:\\ProjWork\\mdb_geoDB_91.zip")
>
> > output_dir = ("C:\\Temp")
>
> > # ZipFile for read
> > z = zipfile.ZipFile(mdb_zip, 'r')
> > zFile = z.namelist()
>
> > # Put contents of zipfile into a list
> > zList = z.namelist()
>
> > # Loop thru list, write zipfile contents to new directory
> > for zItem in zList:
> >     print "Unpacking",zItem
> >     zRead = z.read(zItem)
> >     z1File = open(os.path.join(output_dir, zItem),'wb')
> >     z1File.write(zRead)
> >     z1File.close
>
>      z1File.close()
>
>
>
> > print "Finished extracting zip file"
>
> > uChoice = "test44.mdb" ## to be user chosen someday
> > new91mdb = os.path.join(output_dir, zItem) # C:\TEMP\GDB_9_1.mdb
>
> > ##os.rename(new91mdb, (os.path.join(output_dir, uChoice)))
> > os.rename(new91mdb, (os.path.join(output_dir, "C:\TEMP\test1.mdb")))
>
> > del new91mdb- Hide quoted text -
>
> - Show quoted text -- Hide quoted text -
>
> - Show quoted text -

Thanks!  That was simple enough.

And...
##os.rename(new91mdb, (os.path.join(output_dir, uChoice)))
os.rename(new91mdb, (os.path.join(output_dir, "C:\TEMP\test1.mdb")))

... of those two lines, the top one worked.
--
http://mail.python.org/mailman/listinfo/python-list


Rename of .mdb file -- lock

2008-12-11 Thread noydb
All,

I have the code below, which unzips a zipfile containing only one
file.  Once it is unzipped, I want to rename the file based on a user
provided name.  But I get this (WindowsError: [Error 32] The process
cannot access the file because it is being used by another process)
error, which does not make sense to me as no other apps are open.

Any suggestions?

Thanks!

CODE
# Declare the zip file directory and name (shouldn't change, in a
permanent location)
mdb_zip = ("C:\\ProjWork\\mdb_geoDB_91.zip")

output_dir = ("C:\\Temp")


# ZipFile for read
z = zipfile.ZipFile(mdb_zip, 'r')
zFile = z.namelist()

# Put contents of zipfile into a list
zList = z.namelist()


# Loop thru list, write zipfile contents to new directory
for zItem in zList:
print "Unpacking",zItem
zRead = z.read(zItem)
z1File = open(os.path.join(output_dir, zItem),'wb')
z1File.write(zRead)
z1File.close
print "Finished extracting zip file"

uChoice = "test44.mdb" ## to be user chosen someday
new91mdb = os.path.join(output_dir, zItem) # C:\TEMP\GDB_9_1.mdb

##os.rename(new91mdb, (os.path.join(output_dir, uChoice)))
os.rename(new91mdb, (os.path.join(output_dir, "C:\TEMP\test1.mdb")))


del new91mdb
--
http://mail.python.org/mailman/listinfo/python-list


Re: simple UnZip

2008-07-02 Thread noydb
On Jul 2, 10:07 am, Cédric Lucantis <[EMAIL PROTECTED]> wrote:
> Le Wednesday 02 July 2008 15:39:51 noydb, vous avez écrit :
>
>
>
>
>
> > Can someone help me with this script, which I found posted elsewhere?
> > I'm trying to figure out what is going on here so that I can alter it
> > for my needs, but the lack of descriptive names is making it
> > difficult.  And, the script doesn't quite do anything worthwhile -- it
> > unzips one file from a zipfile, not all files in a zipfile.
>
> > ***
> > import zipfile, os, sys, glob
>
> > os.chdir("C:\\Temp")
> > zips = glob.glob('*.zip')
>
> > for fzip in zips:
> >     if zipfile.is_zipfile(fzip):
> >         print fzip," is a zip"
> >         z = zipfile.ZipFile(fzip,'r')
> >         lstName = z.namelist()
> >         sHgt = lstName[0]
> >         print "Unpacking",sHgt
> >         hgt = z.read(sHgt)
> >         fHgt = open(sHgt,'wb')
> >         fHgt.write(hgt)
> >         # fHgt.flush
> >         fHgt.close
> > print "Finished"
> > ***
>
> > I changed it somewhat to
> > &&&
> > import zipfile, os, sys
>
> > event_zip = ("C:\\Temp\\data4event.zip")
>
> > z = zipfile.ZipFile(event_zip, 'r')
>
> > zList = z.namelist()
>
> > for zItem in zList:
> >     print "Unpacking",zItem
> >     zRead = z.read(zItem)
> >     z1File = open(zItem,'wb')
> >     z1File.write(zRead)
> >     z1File.close
>
> namelist() returns a list of relative file names, so you can just put them
> anywhere you want with:
>
> zlFile = open(os.path.join(DESTDIR, zItem), 'wb')
>
> or change the current directory, but the first way should be preferred.
>
> > print "Finished"
> > &&&
>
> > This works, but I want to be able to specify a different output
> > location.
>
> --
> Cédric Lucantis- Hide quoted text -
>
> - Show quoted text -

Thanks everyone!  I did read the help on zipfile.  I know it was
simple, but for newbies, sometimes it just helps to see how it is done
and learn from that.
--
http://mail.python.org/mailman/listinfo/python-list


simple UnZip

2008-07-02 Thread noydb
Can someone help me with this script, which I found posted elsewhere?
I'm trying to figure out what is going on here so that I can alter it
for my needs, but the lack of descriptive names is making it
difficult.  And, the script doesn't quite do anything worthwhile -- it
unzips one file from a zipfile, not all files in a zipfile.

***
import zipfile, os, sys, glob

os.chdir("C:\\Temp")
zips = glob.glob('*.zip')

for fzip in zips:
if zipfile.is_zipfile(fzip):
print fzip," is a zip"
z = zipfile.ZipFile(fzip,'r')
lstName = z.namelist()
sHgt = lstName[0]
print "Unpacking",sHgt
hgt = z.read(sHgt)
fHgt = open(sHgt,'wb')
fHgt.write(hgt)
# fHgt.flush
fHgt.close
print "Finished"
***

I changed it somewhat to
&&&
import zipfile, os, sys

event_zip = ("C:\\Temp\\data4event.zip")

z = zipfile.ZipFile(event_zip, 'r')

zList = z.namelist()

for zItem in zList:
print "Unpacking",zItem
zRead = z.read(zItem)
z1File = open(zItem,'wb')
z1File.write(zRead)
z1File.close
print "Finished"
&&&

This works, but I want to be able to specify a different output
location.

The scenario is that the zip file will always be the same (gets copied
over daily), but it needs to be unzipped to a specific different
directory.

Can anyone help?

Thanks!
--
http://mail.python.org/mailman/listinfo/python-list