Re: Changing variable to integer

2006-12-17 Thread Juho Schultz
vertigo wrote:
  Perhaps you meant something more along the lines of this:
 
  def PrintWordCountFloat(words):
  number = 0
  for index, word in enumerate(words):
  print %s %f % (index, word)
  number = number + 1
  print Total words: %d %(number)
  PrintWordCountFloat(range(10))
  0 0.00
  1 1.00
  2 2.00
  3 3.00
  4 4.00
  5 5.00
  6 6.00
  7 7.00
  8 8.00
  9 9.00
  Total words: 10
 
  Or similar; I can't read your mind. Just know that enumerate(iterable)
  yields (index, value) for each item in iterable.


 sorry, i was not precise. words is a dictionary.
 1. How can i show it's all variable (with key and value) ?
 2. How can i show sorted dictionary (by key) ?
 3. Is there any function which could do fast iteration on elements of
 sorted dictionary ?

 Thanx

I hope this helps a bit:

 words = {help:20, copyright:25, credits:35}
# show dictionary
 for w, s in words.iteritems(): print w, s
...
credits 35
help 20
copyright 25
# show sorted dictionary
# dicts are not ordered, so you have to sort them.
 for w, s in sorted(words.iteritems()): print w, s
...
copyright 25
credits 35
help 20

-- 
Juho Schultz

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


Re: I think Python is a OO and lite version of matlab

2006-12-08 Thread Juho Schultz
Allen wrote:
 Does anyone agree with me?
 If you have used Matlab, welcome to discuss it.

Matlab is a tool for scientists and engineers.
Python is a tool for programmers.

I think you are looking at Python from the scientist perspective.
Python's numpy and matplotlib modules would probably feel familiar to
anyone with some matlab experience. But these are not a part of the
language - it is not even a part of the standard library.

I will not go deep into the programmer perspective.
Some more programmer tools: Java, Tcl, Perl, PHP, Lisp, Ruby. Comparing
Python to these makes sense. I think comparing Matlab to any of those
would be absurd. Have a look at modpython.org - is there a need for a
similar modmatlab?

Now, back to the scientist perspective.

In 1999, I was starting my M.Sc. in astrophysics and had to select my
data analysis tools. I needed the standard scientific tools:
scripting, numerics, graphics -  Matlab + shell is good enough for
this. But I also needed a library for FITS file processing, which was
not available in Matlab. So Matlab alone was not enough.

Matlab + IRAF + shell was one alternative. Shell + IDL (Interactive
Data Language) was another. There were also other possibilities
(Fortran for numerics,  C or Ftools for FITS). To cut it short, after a
while I ended up with shell + IDL as my main tools, occasionally using
the others.

About two years later my scripts were so complex I decided to learn a
scripting language. I was lucky enough to choose Python. Soon I found
pyraf, pyfits and numarray, later gnuPlot.py and matplotlib - IDL was
no longer needed. Python was enough.

Then one day I was looking for a postdoc position. I found something
else, and now I do text mining. I still need the science tools:
scripting, numerics, graphics.

I also need:
1) Regular expressions
2) XML library
3) Database interface

Python covers it all. I think Matlab has a Database interface, but how
about the others?

--
Juho Schultz

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


Re: question about function not executing

2006-11-26 Thread Juho Schultz
Hint:

Posting only the piece of code causing the problem will give you more
answers...

Ara Kooser wrote:
 Hello all,

   I hope I am posting this correctly. I am running Python 2.4.2 on
 Slackware 11.0 using IDLE. I am in the process of learning python so I
 am writing a text adventure game using functions and global variables
 only. I know there is a better way to do this but that is for later.

When I run the python program it works fine until I try to go west
 from my inital start room. I get the room description but no raw_input
 prompt. I just get dumped back to  in the python shell. I think I
 am missing something simple. I pasted in the code below. I am using
 gmail so I hope the formatting stays. If not I can send the .py as an
 attachment if needed. Thanks.

 Ara


clip

Giving the command 'w', you call meadow1()

 elif prompt_o1 == w:
 meadow1()

 def meadow1():

clip
 print
 prompt_meadow1

So you end up here, the meadow1() function returns to the
except ValueError:
and ends then as expected.


 def meadow1_desc():
 prompt_meadow1

Same problem would occur in here.

I guess you want to call this:

 def prompt_meadow1():

 prompt_m1 = raw_input(Type a command: ).lower()

So write
prompt_meadow1()
instead of
prompt_meadow1

(experiment in python shell and you see the difference.
 raw_input
built-in function raw_input
 raw_input()
now python waits for your input

For the player, create a class.

class player(object):

def __init__(self):
 self.poisoned = False

def take_poison(self):
 print 'You are poisoned'
 self.poisoned = True
 # effects of poison in here:
 # take some hitpoints
 # maybe reduce some stats
 # and so on...

# now, generate a player instance
p = player() # calls __init__
# poison the player
p.take_poison()

-- 
Juho Schultz

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


Re: String Replace only if whole word?

2006-11-17 Thread Juho Schultz
Michael Yanowitz wrote:
 Hello:

   I am hoping someone knows if there is an easier way to do this or someone
 already implemented something that does this, rather than reinventing the
 wheel:
   I have been using the string.replace(from_string, to_string, len(string))
 to replace names in a file with their IP address.
   For example, I have definitions file, that looks something like:
 10.1.3.4   LANDING_GEAR
 20.11.222.4   ALTIMETER_100
 172.18.50.138 SIB
 172.18.50.138 LAPTOP
 172.18.51.32  WIN2000
 127.0.0.1 LOCALHOST

   and I have a text file (a Python script) that has these names in the file.
 In most cases the string.replace() command works great. But there is one
 instance which it fails:
 Suppose I had in the file:
  if (LAPTOP_IS_UP()):
It would replace the string with:
  if (172.18.50.138_IS_UP()):

Is there any easy way to avoid this, only replace if a whole word
 matches?
 I probably need something which determines when a word ends, and I will
 define
  a word as containing only 'A'-'Z','a'-'z','0'-'9','_' . As long as the
 string
 contains more of the word digits after the match, don't replace?

 Thanks in advance:
 Michael Yanowitz

You need regular expressions for this. Use the re module.
http://docs.python.org/lib/module-re.html

from the docs:

re.sub(pattern, repl, string[, count])
Return the string obtained by replacing the leftmost non-overlapping
occurrences of pattern in string by the replacement repl.

Your pattern would be [^A-Za-z0-9_]word[^A-Za-z0-9_]

[^xy] is approximately not in ('x', 'y')

-- 
Juho Schultz

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


Re: Standard Forth versus Python: a case study

2006-10-12 Thread Juho Schultz
John Doty wrote:

 The problem:

 I have a bunch of image files in FITS format. For each raster row in
 each file, I need to determine the median pixel value and subtract it
 from all of the pixels in that row, and then write out the results as
 new FITS files.


This may be personal bias... I have spent a few years with FITS files
so every time I see 'FITS' I think 'astronomy' - maybe you are doing
something else. (Someone wrote he does not know what FITS is - see
fits.gsfc.nasa.gov In a nutshell: FITS file is a list of header-data
units. Each header is text containing optional keyword-value pairs and
reading instructions for the data unit. Usually astronomical image data
but it can be anything.)

Sounds like subtracting sky background from the frames, though for some
reason (speed?) column-wise. You could have a look at either PyRAF
(www.stsci.edu/resources/software_hardware/pyraf) or PyMidas
(www.eso.org/sampo/pymidas/). Running some semi-official
sky-subtraction algorithm would at least give you a good case to test
against.

You could also check if ftools already does this. I have not used it
much, but sometimes it saves huge amounts of coding time.
heasarc.gsfc.nasa.gov/docs/software/ftools/ftools_menu.html

 This is a real problem I need to solve, not a made-up toy problem. I was
 originally thinking of solving it in C (I know where to get the pieces
 in that language)

Could you tell a bit more of the data? Are you aiming for accuracy,
speed or getting as complete time series as possible? (for me, speed
has never been an issue) Photometry/astrometry/something else? Is there
some trade-off like get best possible result in X seconds?

--
Juho Schultz

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


Re: user modules

2006-10-05 Thread Juho Schultz
Cameron Walsh wrote:
 Hi,

 I'm writing a python program to analyse and export volumetric data.  To
 make development and extension easier, and to make it more useful to the
 public when it is released (LGPL), I would like to enable users to place
 their own python files in a user_extensions directory.  These files
 would implement a common interface in order for the main program to be
 able to read them and execute the necessary code.

 My question is what is the best way of implementing this?

 I have investigated importing them as modules, but unless the user
 modifies the main program I cannot see how the main program can learn of
 the existence of specific modules.


One simple solution would be a shell script that adds user_extensions
(or whatever) to $PYTHONPATH and then starts your main program.

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


Re: user modules

2006-10-05 Thread Juho Schultz
Cameron Walsh kirjoitti:

 Hi,

 I'm writing a python program to analyse and export volumetric data.  To
 make development and extension easier, and to make it more useful to the
 public when it is released (LGPL), I would like to enable users to place
 their own python files in a user_extensions directory.  These files
 would implement a common interface in order for the main program to be
 able to read them and execute the necessary code.

 My question is what is the best way of implementing this?

 I have investigated importing them as modules, but unless the user
 modifies the main program I cannot see how the main program can learn of
 the existence of specific modules.

 For example:

 from user_modules import *
 # directory 'user_modules' contains __init__.py allowing this
 # From here I would need a list of the imported modules, in order to
 # execute a common command on each of them, such as

 for module in imported_modules:
   module.initialise()
   module.get_tab_window()


 How do I get from the first bit to the second bit, or is there a better
 way of obtaining the functionality I need?


 --Cameron.
Sorry... I was typing faster than reading or thinking.

You could have a __init__.py file within user_extensions with
__all__ = [package1, package2]

If you want every python file within some directory in here, you can
auto-generate the __init__.py file in user_extension before importing.
(Or you could have some sort of tester for new .py files detected and
only after you are sure it works, add it.)

from user_extensions import *

would import everything mentioned in __all__. You also have access to
their names through
user_extensions.__all__

The last step would be to put the modules into a list. After the
import,

user_ext_list = [eval(elem) for elem in user_extensions.__all__ ]
for ext in user_ext_list:
ext.initialize()
ext.get_tab_window()

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


Re: user modules

2006-10-05 Thread Juho Schultz
Juho Schultz wrote:
 Cameron Walsh wrote:
  Hi,
 
  I'm writing a python program to analyse and export volumetric data.  To
  make development and extension easier, and to make it more useful to the
  public when it is released (LGPL), I would like to enable users to place
  their own python files in a user_extensions directory.  These files
  would implement a common interface in order for the main program to be
  able to read them and execute the necessary code.
 
  My question is what is the best way of implementing this?
 
  I have investigated importing them as modules, but unless the user
  modifies the main program I cannot see how the main program can learn of
  the existence of specific modules.
 

 One simple solution would be a shell script that adds user_extensions
 (or whatever) to $PYTHONPATH and then starts your main program.

Sorry... I was typing faster than reading or thinking.

You could have a __init__.py file within user_extensions with
__all__ = [package1, package2]

If you want every python file within some directory in here, you can
auto-generate the __init__.py file in user_extension before importing.
(Or you could have some sort of tester for new .py files detected and
only after you are sure it works, add it.)

from user_extensions import *

would import everything mentioned in __all__. You also have access to
their names through
user_extensions.__all__

The last step would be to put the modules into a list. After the
import,

user_ext_list = [eval(elem) for elem in user_extensions.__all__ ]
for ext in user_ext_list:
ext.initialize()
ext.get_tab_window()

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


Re: Comment on this script. Possible error in communication with list arg between functions

2006-07-24 Thread Juho Schultz
Phoe6 wrote:
 Hi all,
  Part of my script is to check for pre-requisite rpms to be
 installed.
 If its installed, I just display the rpm version as in rpm database,
 otherwise I output a message saying:
 ' rpm is not installed' and collect the rpm name in a list
 (notInstalled).
 At the end if the len(notInstalled) is greater than 0 then I display
 them all asking it to be installed and exit the program.
 My Script is below:
 ---
 def checkForRpm(rpmname):
 ''' Check for the presence of the RPM. '''
 cin,cout,cerr = os.popen3('rpm -q ' + rpmname)
 output = cout.read()
 global notInstalled
 if len(output) = 0:
 print rpmname + ' not installed.'
 notInstalled.append(rpmname)
 else:
 print output



 def preReqCheckRpms():
 ''' Check for the required RPMS '''
 listOfRpms = ['firefox','senthil',]


 for eachRpm in listOfRpms:
 checkForRpm(eachRpm)
 global notInstalled
 if len(notInstalled)  0:
 print 'The following RPMS are not installed:'
 for eachRpm in notInstalled:
 print eachRpm
 print 'Please install them for the installation to
 continue.'
 sys.exit(-1)


 * This is NOT Working.
 * notInstalled.append(rpmname) is not taking effect in
 checkForRpm(rpmname)
 * I dont know how to communicate the notInstalled list to
 preReqCheckRpms.

 --
 Senthil

I think return values should be used for communication between
functions. Maybe something like this could work for you (not tested).

def checkForRpm(rpmname):
# cut start of function
# Strings with 0 lenght are False
if output:
print output
else:
print rpmname + ' is not installed'
return output

def checkPreReqs():
missingRpms = []
for requiredRpm in listOfRpms:
if not checkForRpm(requiredRpm):
missingRpms.append(requiredRpm)
# you could also do this by a list comprehension
missingRpms = [reqRpm for reqRpm in listOfRpms if not
checkForRpm(reqRpm)]
# or you could use the builtin function filter() - see
filter.__doc__ for that

# now, list of lenght 0 is False.
if missingRpms:
# print error messages, exit.

--
Juho Schultz

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


Re: building lists of dictionaries

2006-07-23 Thread Juho Schultz
Jean_Francois Moulin wrote:
 Hi all,

 I tried this piece of code (FWIW, it was taken as is from a help section of 
 mpfit, a mathematical routine for least square fitting):

 parinfo = [{'value':0., 'fixed':0, 'limited':[0,0], 'limits':[0.,0.]}]*6

 The first line builds a list of six dictionaries with initialised keys.

 This is not so!
 I end up with all dictionaries being identical and having their 'fixed' key 
 set to 1, and limited[0]==1 and limits[0]==50.

 I do not understand this behaviour...

 Thanks for helping a newbie.

 JF


xvec = [{'value':0}]*6
xids = [id(x) for x in xvec]
print xids

Should print a list of six integers, all equal.
So all elements in your list are the same.

Another way to construct the desired list:

yvec = [{'value':0} for i in range(6)]
yids = [id(y) for y in yvec]
print yids

The elements in this list should be all different.

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


Re: building lists of dictionaries

2006-07-23 Thread Juho Schultz

Tim Chase wrote:

 parinfo = [{'value':0., 'fixed':0, 'limited':[0,0],
 'limits':[0.,0.]}.copy() for i in xrange(0,6)]

 However, this will still reference internal lists that have
 been referenced multiple times, such that

   parinfo[5]['limited']
 [0, 0]
   parinfo[4]['limited'][0] = 2
   parinfo[5]['limited']
 [2, 0]


Interesting. Cut-and-paste to my python prompt and I get
 parinfo[5]['limited']
[0, 0]

Tried both Python 2.4.1 and 2.5 beta, Linux, GCC 4.0.2

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


Re: RegEx conditional search and replace

2006-07-05 Thread Juho Schultz
Martin Evans wrote:
 Sorry, yet another REGEX question.  I've been struggling with trying to get
 a regular expression to do the following example in Python:

 Search and replace all instances of sleeping with dead.

 This parrot is sleeping. Really, it is sleeping.
 to
 This parrot is dead. Really, it is dead.


 But not if part of a link or inside a link:

 This parrot a href=sleeping.htm target=newis sleeping/a. Really, it
 is sleeping.
 to
 This parrot a href=sleeping.htm target=newis sleeping/a. Really, it
 is dead.


 This is the full extent of the html that would be seen in the text, the
 rest of the page has already been processed. Luckily I can rely on the
 formating always being consistent with the above example (the url will
 normally by much longer in reality though). There may though be more than
 one link present.

 I'm hoping to use this to implement the automatic addition of links to other
 areas of a website based on keywords found in the text.

 I'm guessing this is a bit too much to ask for regex. If this is the case,
 I'll add some more manual Python parsing to the string, but was hoping to
 use it to learn more about regex.

 Any pointers would be appreciated.

 Martin

What you want is:

re.sub(regex, replacement, instring)
The replacement can be a function. So use a function.

def sleeping_to_dead(inmatch):
  instr = inmatch.group(0)
  if needsfixing(instr):
return instr.replace('sleeping','dead')
  else:
return instr

as for the regex, something like
(a)?[^]*(/a)?
could be a start. It is probaly better to use the regex to recognize
the links as you might have something like
sleeping.sleeping/sleeping/sleeping.html in your urls. Also you
probably want to do many fixes, so you can put them all within the same
replacer function.

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


Re: converting file formats to txt

2006-07-04 Thread Juho Schultz
Steven D'Aprano wrote:
 On Tue, 04 Jul 2006 06:32:13 -0700, Gaurav Agarwal wrote:

  Hi,
 
  I wanted a script that can convert any file format (RTF/DOC/HTML/PDF/PS
  etc) to text format.

 PDF is (I believe) a compressed, binary format of PS. Perhaps you should
 look at the program pdf2ps -- maybe it will help.
 
 
 -- 
 Steven.

Or try the program pdftotext?


-- Juho Schultz

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


Re: print shell output in a file

2006-06-30 Thread Juho Schultz

Juergen Huber wrote:
 hello,

 one more question i will have!

 now i have written a little programm, which delivers me an output on the
 shell!



 Is there a way to put this output in an file?!?! i searched about 2h for
 this, but i couldn`t find an answer!

 thnks, juergen

Others have suggested creating a file.

You could also let the shell to do the work.

If you run the program normally, output goes to screen:
python myprog.py

Run and redirect the output to a file:
python myprog.py  output_of_myprog.txt

This also makes controlling the output filename much easier.

You could find the following useful:
http://www.swc.scipy.org/lec/shell01.html

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


Re: break the loop in one object and then return

2006-06-26 Thread Juho Schultz
Alex Pavluck wrote:
 I am trying to write the following code to block up evaluation and
 prompting for entering new information.  However, when I break the loop
 in one object and then return it does not start at the beginning again
 but rather at the point where it exited.  Can someone look at the
 following code and give me some feedback.

If you want a loop, write a loop.

eval() is a built-in function. Better leave the names of builtins as
they are.


 yournum = input(I am thinking of a number between 1 and 100.\n  Guess
 which number: )
 mynum = (yournum-5)

If the users first guess is 2, mynum becomes -3...

Better use this - to ensure 100 = mynum = 1, and the user can guess
right on 1st try.
import random
mynum = random.randint(1,100)

input evaluates a user-supplied string, and is a bit dangerous.
(Run your original program, and give mynum as your second guess.)
So use yournum = int(raw_input(I am thinking...

you could use one while loop instead of two functions and one global
variable.

while (yournum != mynum):
if yournum  mynum:
print Too low.
else:
print Too high.
yournum = int(raw_input(Guess again:))
print You got it!

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


Re: Python Evangelism

2006-03-10 Thread Juho Schultz
Magnus Lycka wrote:
 rtilley wrote:
 

 I think it's the name. Python. Let's change it to something nicer. 
 Think about it... if you found a Ruby, you'd pick it up and put it in 
 your pocket. If you ran across a Python, you'd run away.
 
 
 I think you have a point, but I also think it's a bit
 late to change it after 15 years or so, considering all
 books, web sites etc. We're stuck with Python, and can
 only do the best of that. Actually, in Swedish, Jag
 mår pyton i.e. I feel like python means I feel
 sick, and det luktar pyton i.e. it smells python,
 means it stinks. That doesn't make Python easier to
 sell here... Still to late to change...
 

In Finnish ajaa käärme pyssyyn (force a snake into a rifle) means 
doing something almost impossible. If you have to put a snake into a 
rifle, try Python - a bite does not kill you. So it works both ways.

 I think a good example on the problem with letting
 techies like us do naming is that grand successor
 of Unix developed by the great minds at Bell Labs.
 
 First, they name it after a movie which is famous
 for being exceptionally bad--Plan 9 (from outer space).
 Really grand company there!
 
 Then, when they make a real product of it, they call
 it Inferno, and some part of it gets called Limbo.
 
Inferno - the Lamborghini Diablo of operating systems
What is the problem here?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why python doesn't use syntax like function(,,x) for default parameters?

2006-03-10 Thread Juho Schultz
Antoon Pardon wrote:
 Op 2006-03-10, Roy Smith schreef [EMAIL PROTECTED]:
 
Dmitry Anikin [EMAIL PROTECTED] wrote:

There are often situations when a function has independent
parameters, all having reasonable defaults, and I want to
provide just several of them. In fact, I can do it using
keyword parameters, but it's rather long and you have to
remember/lookup names of parameters.

Specifying the names of the keyword parameters costs you a little typing 
once, but saves everybody (including yourself) a lot of grief later when 
you're trying to figure out what the heck your code does 6 months later.
 
 
 Could you explain what is so hard in figuring out:
 
   func(,,4)
 

Your func has only three parameters, and only one non-default.
I think all have reasonable defaults, I want to provide several
means you might end up with bugs like this.

func(,,,1.2e-3,7.6e18,3.124576,3567.0,)
func(,,1.24e3,1,21.26e4,,,1220,57,35,0) # bug
TypeError: func() takes exactly 8 arguments (9 given)

Now what are the correct arguments?
1220.57, 35,and 0
1220,57.35, and 0
1220,57,and 35.0

With keywords parameters, this is easy to answer.

func(y=1.2e-3, z=7.6e18, i=3.124576, j=3567.0)
func(x=1.24e3, y=1, z=21.26e4, j=1220, k=57,35, w=0) # bug

SyntaxError: non-keyword arg after keyword arg.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: File Permissions

2006-03-10 Thread Juho Schultz
VJ wrote:
 Hi All
 
 Basically i want to write into a file .If the permissions are not there
 then print a error message.
 How do i achive this ???
 
 Thanks,
 VJ
 

One way would be a try-except block, and leave the permission checking 
error message generation, etc. to the operating system.

try:
 outfile = file(outfilename,w)
except IOError, errormsg
 print Could not write to file %s: %s % (outfilename, errormsg)

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


Re: implementation of complex type

2006-03-09 Thread Juho Schultz
Russ wrote:
 I tried the following:
 
 
x = complex(4)
y = x
y *= 2
print x, y
 
 (4+0j) (8+0j)
 
 But when I tried the same thing with my own class in place of
 complex above, I found that both x and y were doubled. I'd like to
 make my class behave like the complex class. Can someone tell me the
 trick? Also, where can I find the code for for the complex class? I
 hope it's written in Python! Thanks.
 

This is like the difference of tuples and lists.

Your own class is mutable.
y=x # Names x and y are now bound to the same object.
y*=2 # change the object bound to names x and y.

Builtin complex is immutable, so you can not manipulate the contents.
y*=2 # creates a new object (value = 2*y), binds it to name y.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Getting File Permissions

2006-03-07 Thread Juho Schultz
Hari wrote:
 Hi,
 For getting permissions of a file, the following script has been
 suggested in the same group
 
 import os, stat
 st = os.stat(myfile)
 mode = st[stat.ST_MODE]
 print mode is, octal(mode  0777)
 
 But while executing I am getting error message as follows
 
 Traceback (most recent call last):
  File stdin, line 1, in ?
 NameError: name 'octal' is not defined
 
 Since I am new to python, can any one help me to solve this error?
 A bunch of thanks in advance.
 
 Hari
 

You can use oct instead of octal.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What version of python is running a script

2006-03-07 Thread Juho Schultz
Fernando Rodríguez wrote:
 
 Hi,
 
 How can my script tell which version of python is running it?
 
 Thanks
 
 

import sys
# examine these variables
sys.version_info
sys.version
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Vectorization and Numeric (Newbie)

2006-02-28 Thread Juho Schultz
Ronny Mandal wrote:
 Assume you have a mathematical function, e.g. f(x) = x + 4
 
 To calculate all the values from 1 to n, a loop is one alternative.
 

Numeric and friends (numarray,numpy) have something like numarray.arange 
- they return arrays similar to the lists returned by standard libs 
range function. I would recommend using the built-in array operations as 
much as possible - in most cases they are much faster than looping, and 
your code remains simpler.

 But to make this function work with vectors instead i.e
 f(x_vector) = result_vector,
 how should the function then be implemented?
 

In most numeric libraries, vectors and scalars can be added etc.
For the simple f(x) case you can use just the simplest approach:

def f(x):
 return x+4

and call this with scalar and vector args.
f_pi = f(3.14159265)
f_1to200 = f(numarray.arange(1,200))
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to run shell commands within python

2006-02-16 Thread Juho Schultz
fileexit wrote:
 How can I execute shell commands from within python.  Specifically, I
 am looking for something like the shell cat.  But this also made me
 wonder how to execute shell commands anyway, just if i needed to do
 that in the future.
 
You can use os.system() for that.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python advocacy in scientific computation

2006-02-15 Thread Juho Schultz
Michael Tobis wrote:
 Someone asked me to write a brief essay regarding the value-add
 proposition for Python in the Fortran community. Slightly modified to
 remove a few climatology-related specifics, here it is.
 

Thank you - this was very good reading.

 I would welcome comments and corrections, and would be happy to
 contribute some version of this to the Python website if it is of
 interest.
 

A slight broadening of the perspective could show another advantage:
Python is also used for data processing, at least in astronomy. Modeling 
and processing the data in the same environment is very practical. Spend 
more time on modeling and processing the critical data sections - 
critical data section may depend on model parameters and sampling (which 
is often incomplete and uneven). You also avoid wasting CPU cycles to 
model things not in the data.

A theorist may be perfectly happy with Fortran, and an observer could do 
his stuff with simple scripts. But if they need to work together, Python 
is a very good option.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a numarray question

2006-02-15 Thread Juho Schultz
[EMAIL PROTECTED] wrote:
 hello everyone
 
 would anyone please tell me what is the best (fastest) way of replacing
 values in numarray arrays?
 
 lets say i have an array that may contain 0s, and i just want to get
 rid of those 0s by replacing them with another number. what would be
 the most efficient way to do that?
 
 many thanks in advance!
 
One way to do that is

data2 = numarray.choose(numarray.equal(data,0), (data, another_number))

I am not sure this is the most efficient way. If you get other 
suggestions, you can compare them with the timeit module.

http://www.python.org/doc/2.4.2/lib/module-timeit.html

But if you plan to do calculations with the data, I think replacing 
zeros is not critical for performance.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Determining an operating system's default browser

2006-02-10 Thread Juho Schultz
John McMonagle wrote:
 Is there a python module which can determine an operating system's
 default web browser application.
 
 I would like to use it in the following context:  I have a GUI
 application where all the documentation is written as html pages.  I
 wish to have these html help pages open in the default browser when
 selected from the application's Help menu
 
 If python can determine the path to the default browser, I can then just
 spawn it.
 
 Regards,
 
 John McMonagle
 
 
 
I think the htmlview command is used for this purpose (displaying html 
documentation of applications) on many Linuxes. So you could try 
os.system('htmlview'). Given the variety of Unixes (and even Linuxes) 
out there this is not a general solution.

So I would try htmlview first. If it does not work, the program could 
ask the user for his favourite browser the 1st time he looks at docs, 
and save this to a configuration file.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Too Many if Statements?

2006-02-10 Thread Juho Schultz
Steven D'Aprano wrote:
 On Fri, 10 Feb 2006 06:50:25 -0800, slogging_away wrote:
 
 
Excellent suggestion, (behold the power of the command line!).  I ran
two saved versions of the script that had produced the symptom
originally described.  The fist seemed to be caused by too many 'if'
statements, the second by adding another array, but both came up with
the same system error at the command prompt level shown here:

SystemError: com_backpatch: offset too large
 
 
 Is this a Python error or a shell error?
 
 If it is a Python error, perhaps you would like to post the entire
 traceback? 
 
 
 

I would believe CamelCaseErrorMessages are produced by Python.

The message is exactly the same I reported with the 2500 elifs. I fooled 
around a bit with this, and it seems that also for/while blocks 
containing more than ~4860 lines give this error.

slogging_away claims his script is about 4900 lines, most of that in a 
for loop, so my bet is he has trouble with the same bug.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: line wrapping problem

2006-02-09 Thread Juho Schultz
S Borg wrote:
 Hello,
 
  I am parsing text from one document to another. I have a scheme
 similar to:
 
  for x in myfoobar:
print  mytextfile, %s % mydictionary[x],   #all on same line
  print  mytextfile, '\n'  #new line
 
 
 I am getting line breaks before my explicit line break. Am I
 unwittingly copying '\n' characters from the original file?
 How should I fix this(What is the 'Pythonic' solution)?
 
 thanks,
 -S
 

mytextfile.write(%s % mydictionary[x])

should work. IMO file.write() is self-explanatory but print  file is 
a bit obscure.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: line wrapping problem

2006-02-09 Thread Juho Schultz
ZeD wrote:
 Ciao, Juho Schultz! Che stavi dicendo?
 
Moro, ZeD! Kunhan pulisen. Should we stick to English?
 
should work. IMO file.write() is self-explanatory but print  file is
a bit obscure.
 
 is obscure only if you have never used a shell :)
 
(I have used the shell a bit. I started using Linux at work when 2.2 
series kernels did not exist.)

Assume a newbie plays around with a piece code. If the code has 
f.write(x) or print  f,x - in which case the newbie is more likely to 
break the code by rebinding f to something non-file? And in which case 
he will more likely understand the error message, something like f has 
no write attribute?

I am sure the  can be useful - it is quick to add after a simple print 
when you want less chatter and more logfiles. But IMO it is not 
self-documenting. Having to very different uses for an operator in the 
same language is sort of confusing.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Too Many if Statements?

2006-02-08 Thread Juho Schultz
Bryan Olson wrote:
 Alan Morgan wrote:
 
 slogging_away wrote:

 Hi - I'm running Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310
 32 bit (Intel)] on win32, and have a script that makes numerous checks
 on text files, (configuration files), so discrepancies can be reported.
 The script works fine but it appears that I may have hit a wall with
 'if' statements.

 Due to the number of checks perfromed by the script on the text files,
 (over 500), there are quite a few 'if' statements in the script, (over
 1150).  It seems that it is at the point that when I add any additional
 'if' statements the script will not run.  No error is produced - it
 just returns to the python prompt much the same as when a successful
 'Check Module' command is selected.  If I delete some other 'if'
 statements the new ones work so it appears that it has hit a limit on
 the number of 'if' statements.  This has stunted any further checks for
 the script to make on the text files.

 Hs anyone ever run into this sort of thing?



 I generated files with 1, 25000, and 5 simple if statements 
 and ran
 them.  1 was okay, 25000 gave a bizarre internal error, and 5 
 segfaulted
 and died.  My system has plenty of memory and it isn't obvious to me 
 why python
 should be so bothered about this.  I'm not sure why I can have 10x the 
 number of
 if statements that cause you trouble.  There might be some overall 
 limitation
 on the number of statements in a file.
 
 
 I made a script with 100,000 if's, (code below) and it appears
 to work on a couple systems, including Python 2.4.2 on Win32-XP.
 So at first cut, it doesn't seem to be just the if-count that
 triggers the bug.

I tried that code. It runs fine.

However, the following gives a SystemError with only 2500 elif's.

#!/usr/bin/env python
lines = [ 'n = -1','m = 0','if n  0:','   m = 2*n',]
for i in range(2500):
 lines.append('elif n == %i:' % i)
 lines.append('m = 2*n')
prog = '\n'.join(lines)
progfile = file('if.py','w')
progfile.writelines(prog)
progfile.close()
exec prog

Traceback (most recent call last):
   File iftest.py, line 10, in ?
 exec prog
SystemError: com_backpatch: offset too large

I tried this with Python 2.3.3 and 2.3.4 (Linux) and both fail.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to copy a Python object

2006-02-07 Thread Juho Schultz
[EMAIL PROTECTED] wrote:
 Already thanks for the reply,
 
 but how to write your own copy operator? Won't you always be passing
 referrences to new_obj?
 

If you need to modify the behaviour of copy or deepcopy, you can give 
your class __copy__ and __deepcopy__ methods. Then copy.copy and 
copy.deepcopy will use these. As a silly example, you could use:

def __copy__(self):
 raise IOError, 'Permission denied.'

http://www.python.org/doc/2.4.2/lib/module-copy.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problems writing tuple to log file

2006-02-03 Thread Juho Schultz
[EMAIL PROTECTED] wrote:
 i am having a problem writing a tuple to a text file.  my code is
 below.
 
 what i end up getting is a text file that looks like this
 
 burger, 7up
 burger, 7up
 burger, 7up
 
 and this is instead of getting a list that should look like this
 
 burger, 7up
 fries ,coke
 cake ,milk
 
 note that i have print statements that print out the results of the
 scraping and they are fine.  they print out burger, fries, cake and
 then 7up, coke, milk
 
 however there is something faulty in my writing of the tuple to the
 text file.  perhaps related to the indentation that causes it to write
 the same stuff over and over?
 
 
 
 for row in bs('div'):

What kind of function is 'bs'? Should you use 'row'
(which you are looping over) inside the loop?
Seems that your code is equal to

for row in range(len(bs('div'))):

   for incident in bs('span'):

Just like you use 'incident' here, inside the other loop.


   foodlist = []
   b = incident.findPrevious('b')
   for oText in b.fetchText( oRE):
   #foodlist.append(oText.strip() + ',)
   foodlist += oText.strip() + ','
   food = ''.join(foodlist)
   print food
 

After print food you repeat the loop, overwriting food until last 
round. And after you have found the last food, you put it in tuple.

 tuple = (food + drink \n)

A tip: 'tuple' is a built-in function, just like 'open' you use.
This statement overwrites that function with a string.
It is usually a good idea to leave the built-ins as they are,
and use some other names for variables.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: beta.python.org content

2006-01-27 Thread Juho Schultz
Steve Holden wrote:
 How does
 
   http://beta.python.org/about/beginners/
 
 look?
 
 regards
  Steve

I think the content is good, but I would suggest putting some bullet 
points with links at the top. IMO top part of the beginner page should 
somehow indicate that tutorial and FAQ is accessible from this page.

The page looks a bit dull - there is nothing bright-colored there.
Have a look at the www.holdenweb.com in your sig to see what I mean.
The small lines of red and yellow on the upper right and the orange 
picture on used there makes the page a lot more alive.
-- 
http://mail.python.org/mailman/listinfo/python-list


Nitpicking - slightly misleading traceback

2006-01-26 Thread Juho Schultz
if ((data[x][y]  0) or
 (datadict.has_key[key])):

Traceback (most recent call last):
   File reduce.py, line 524, in remove_badvalues
 if ((data[x][y]  0) or
TypeError: unsubscriptable object

However, the bug sits on the next line. I used square brackets when 
normal brackets were needed - should have written datadict.has_key(key) 
as the old code had datadict[key]. In the real code variable names are 
so long that I must split the line. I feel the traceback is misleading.

I guess the best solution is to write code without bugs...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using non-ascii symbols

2006-01-24 Thread Juho Schultz
Christoph Zwerschke wrote:

 These operators ≤ ≥ ≠ should be added to the language having the 
 following meaning:
 
   = = !=
 
 this should improve readibility (and make language more accessible to 
 beginners).
 

I assume most python beginners know some other programming language, and 
are familiar with the = and friends. Those learning python as their 
first programming language will benefit from learning the = when they 
learn a new language.

Unicode is not yet supported everywhere, so some editors/terminals might 
display the suggested one-char operators as something else, effectively 
guess what operator I was thinking.

Fortran 90 allowed , = instead of .GT., .GE. of Fortran 77. But F90 
uses ! as comment symbol and therefore need /= instead of != for 
inequality. I guess just because they wanted. However, it is one more 
needless detail to remember. Same with the suggested operators.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: append to the end of a dictionary

2006-01-24 Thread Juho Schultz
Yves Glodt wrote:
 Hi there,
 
 I seem to be unable to find a way to appends more keys/values to the end 
 of a dictionary... how can I do that?
 
 E.g:
 
 mydict = {'a':'1'}
 
 I need to append 'b':'2' to it to have:
 
 mydict = {'a':'1','b':'2'}
 
mydict['b'] = '2'
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OT: excellent book on information theory

2006-01-20 Thread Juho Schultz
Bengt Richter wrote:
 On Thu, 19 Jan 2006 14:12:24 +0200, Juho Schultz [EMAIL PROTECTED] wrote:
 
Last month I spent about an hour trying to explain why
a*2.5e-8 = x
raises a SyntaxError and why it should be written
x = a*2.5e-8
The guy who wrote the 1st line has MSc in Physics from Cambridge (UK).
In mathematics, there is no difference between the two lines.
 
 
 ISTM probable that his original equation was really saying
 assert a*2.5e-8 == x
 which is not very different from
 assert x == a*2.5e-8
 
 Did you mention that = is not == in python?
 I too would resist the idea that
 assert a*2.5e-8 == x
 should be written as
 x = a*2.5e-8
 
 Regards,
 Bengt Richter

He tried to assing 2.5e-8 times value of variable a to variable x.
It had nothing to do with testing equality or asserting.
It is just that he had absolutely no programming skills at all.
However, he is learning quite fast.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OT: excellent book on information theory

2006-01-19 Thread Juho Schultz
Anton Vredegoor wrote:
 
 Returning to the original book, why did they write a lot of it (at
 least the first few pages until I gave up, after having trouble
 understanding formulas about concepts I have no such trouble with when
 framed in less jargonized from) in unintelligible mathemathical
 notation when there's Python?
 

Because the intended audience is probably reads formulas better than
they read Python. The 1st sentence of the Introduction: This book is 
aimed at senior undergraduates and graduate students in Engineering, 
Science, Mathematics and Computing.

Last month I spent about an hour trying to explain why
a*2.5e-8 = x
raises a SyntaxError and why it should be written
x = a*2.5e-8
The guy who wrote the 1st line has MSc in Physics from Cambridge (UK).
In mathematics, there is no difference between the two lines.

 I prefer a nice Python function over some strange latech symbols. If
 not Python there's always pseudo code or good old natural language.
 Don't tell me those math formulas are what it 'really' is, or even that
 it's more precise that way. The old trick of 'but there are some things
 that cannot be expressed in any other way than by using formulas'
 doesn't get one many optimization points in my world.
 
 Anton
 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Find and slice problem

2006-01-18 Thread Juho Schultz
[EMAIL PROTECTED] wrote:
 Hi guys, been going around in circles with this so I hope you can help!
 
 My current situation is I'm using Grinder and Jython to test pages, but
 the log on process is giving me some headaches. After entering the
 correct username and password, you then need to enter 3 characters from
 the security phrase. I'm attempting to read the HTML to find out with
 characters I need (e.g. 1st, 3rd and 6th char) then look up those
 values in the security phrase, but I'm getting stuck on the following
 function:
 
 code
 
 def getValue(page,delimEnd) :
 EndVar = page.find(delimEnd)
 thisVar =  page[EndVar-1:EndVar]
 return thisVar
 
 /code
 
 What I'm attemping to pass in is some multiline HTML(above) and pick up
 the proceeding character, but it seems to be reading from the end of
 the HTML instead!

page.find(delimEnd) returns -1 if delimEnd is not found, and after that 
you take page[-2:-1], i.e. second last character.

So you could add a test for that, if EndVar == -1 etc.
but I recommend using page.index(delimEnd) which raises an error if 
delimEnd is not found.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how do real python programmers work?

2006-01-13 Thread Juho Schultz
bblais wrote:

 In Python, there seems to be a couple ways of doing things.   I could
 write it in one window, and from a Unix shell call
python myscript.py
 and be like C++, but then I lose the interactiveness which makes
 prototyping easier.  If I use the python shell, I can use import (and
 reload), or execfile perhaps.
 
 How do experienced python programmers usually do it?  Is there a
 usually about it, or is it up to personal taste?  Are there any
 convenient ways of doing these things?
 

Disclaimer: I do not consider myself an experienced python programmer.

For scripts and small programs (one file, one developer) I use emacs and 
python shell. For larger projects I use Eclipse and pydev.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Maximum List size (item number) limit?

2006-01-11 Thread Juho Schultz
Kriston-Vizi Janos wrote:
 Dear Mr. Kern, and Members,
 
 Thank you very much for the fast answer, my question became 
 over-simplified.
 
 My source code is appended below. It uses two text files (L.txt and 
 GC.txt) as input and merges them.
 
 Both L.txt and GC.txt contains 3000 rows. When running, the code stops 
 with error message:
 
 'The debugged program raised the exception IndexError list index out of 
 range
 File: /home/kvjanos/file.py, Line: 91'
 
 And I noticed that all the lists that should contain 3000 items, 
 contains less as follows:
 NIR_mean_l = 1000 items

 Code that's failing:

 # Processing L file
 line_no_l =0# Input L file line number
 type_l = 1  # Input L file row type: 1 (row n),2 (row n+1) or 3 (row n+2)
 # Append L values to lists.
 for line in inp_file_l.xreadlines():
 line_no_l = line_no_l + 1
 if line_no_l == 1:  # To skip the header row
continue  
 data_l = []   # An L row  
 data_l = line.split()
 if type_l == 1: 
NIR_mean_l.append(data_l[2])  # Append 3rd item of the row to the list
NIR_stdev_l.append(data_l[3])  # Append 4th item of the row to the list
type_l = 2  # Change to row n+1
 else:
 if type_l == 2:
 R_mean_l.append(data_l[2])
 R_stdev_l.append(data_l[3])
 type_l = 3
 else:
 G_mean_l.append(data_l[2])
 G_stdev_l.append(data_l[3]) 
 area_l.append(data_l[1])  
 type_l = 1
 inp_file_l.close()
 

Looking at the data files, it seems there is no header row to skip.
Skipping 1st row seems to cause the discrepancy of vector sizes,
which leads to the IndexError. should NIR_mean_l[0] be 203 or 25?

As the comments in your code suggest, the code adds values to
NIR_mean_l only from lines 1, 4, 7, ...
R_mean_l only from lines 2, 5, 8, ...
G_mean_l only from lines 3, 6, 9, ...
Try with 12 lines of input data and see how the vectors
are 4 elements before filtering/writing.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Maximum List size (item number) limit?

2006-01-11 Thread Juho Schultz
[EMAIL PROTECTED] wrote:
 Juho Schultz
 
NIR_mean_l only from lines 1, 4, 7, ...
R_mean_l only from lines 2, 5, 8, ...
G_mean_l only from lines 3, 6, 9, ...
 
 
 This can be the problem, but it can be right too.

I guess he is expecting 3000 elements, not 1000, as he wrote:

And I noticed that all the lists that should contain 3000 items, 
contains less as follows:
NIR_mean_l = 1000 items
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to improve this simple block of code

2006-01-11 Thread Juho Schultz
py wrote:
 Say I have...
 x = 132.00
 
 but I'd like to display it to be 132 ...dropping the trailing
 zeros...I currently try this
 
 if x.endswith(0):
 x = x[:len(x)-1]
 if x.endswith(0):
 x = x[:len(x)-1]
 if x.endswith(.):
 x = x[:len(x)-1]
 
 I do it like this because if
 x = 132.15  ...i dont want to modify it.  But if
 x = 132.60 ...I want it to become 132.6
 
 is there a better way to do this?  It seems a bit ugly to me.
 
 T.I.A
 (thanks in advance)
 

x = x.rstrip('0') # removes trailing zeros
x = x.rstrip('.') # removes trailing dot(s)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Visualisation Engine for Python

2006-01-05 Thread Juho Schultz
rodmc wrote:
 I am looking for a 2D data visualisation or graphics library for
 Python. Can anyone point me in the right direction?
 
 
 Thanks in advance,
 
 rod
 

Two tools I have used are Gnuplot-py
http://gnuplot-py.sourceforge.net/
and matplotlib
http://matplotlib.sourceforge.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to check if a string is an int?

2005-12-21 Thread Juho Schultz
Neuruss wrote:
 Can't we just check if the string has digits?
 For example:
 
 
x = '15'
if x.isdigit():
 
   print int(x)*3
 
   
 45
 
 
No, we can't. '-15' has non-digits but is a valid int.

Another point is that the try-except
can also be used for string-to-float conversion

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


Re: os.path.splitext() and case sensitivity

2005-12-21 Thread Juho Schultz
rbt wrote:
 Hi,
 
 Is there a way to make os.path.splitext() case agnostic?
 
 def remove_file_type(target_dir, file_type):
 for root, dirs, files in os.walk(target_dir):
 for f in files:
 if os.path.splitext(os.path.join(root, f))[1] in file_type:
 pass
 
 remove_file_type(sysroot, ['.tmp', '.TMP'])
 
 As you can see, the way I do it now, I place file extensions in a list. 
 However, I'd like to able just to say '.tmp' and for that to work on any 
 type of file that has tmp (no matter the case) in the extension.
 
 Many thanks!!!


One solution would be to convert the extensions to lowercase
(or uppercase, if you prefer that)

if fileExtension.lower() == .tmp:
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: text manipulation

2005-12-16 Thread Juho Schultz
Johhny wrote:
 Hello,
 
 I am trying to write a script in python (to replace a perl script with
 limited functionality). Now I have some issues. Currently I am using
 the perl to load the file then regex parse certain lines to remove
 characters (uncomment lines and change variables). I would like to take
 that into the python script. I have had a look at the module string
 and I dont think its what Im looking for.
 
 Here is an example of some text I would like to manipulate
 
 #comment here
 #user_defined_variable = no
 #
 
 I would like to make that
 
 #comment here
 user_defined_variable = yes
 #
 
 With perl/sed Its very easy, However Im having issues to do it in
 python. Any advice would be great.
 
 Regards,
 
 Johhny.
 

Have you also looked at the built-in string methods?


The following script is probably something you
could start with - it just uncomments lines
and replaces values of some variables.

# dictionary of the variable names
# contains the replacement values
newvalues = {'userdefinedvar1':'yes',
'userdefinedvar2':'123.654.345.234'}

# read file to input
output = []
for line in input:
 # check if it is a comment with =
 if line.startswith('#') and ('=' in line):
 name, oldvalue = (line.lstrip('#')).split('=')
 # line.lstrip removes leading comments,
 # split('=') finds the assignment
 if newvalues.has_key(name):
 # replace line
 output.append(%s = %s % (name, newvalue[name]))
 else:
 # or just uncomment
 output.append(%s = %s % (name, oldvalue))
 else:
 output.append(line)

# write output to file
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to creat a file?

2005-12-02 Thread Juho Schultz
sandorf wrote:
 I'm new to python. Have a simple question.
 
 open function can only open an existing file and raise a IOerror when
 the given file does not exist. How can I creat a new file then?
 

You already have two correct answers. A warning: if you open a existing
file for writing, it is truncated (the old contents of that file
disappear.) For adding new content to the end of an existing file,
you can use:

f = open(filename,'a')
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Nested loop

2005-11-30 Thread Juho Schultz
viewcharts wrote:
 I am reading two text files comparing the values in one to the other, 
 this requires two loops. The problem is that when the inner loop is 
 finished, it never goes back into the loop. Any suggestions?
 
 
 for refSymbol in symbols.readlines():
 for lookupSymbol in myfile.readlines(): 
 showme = lookupSymbol.split('\t')
 if showme[3] == refSymbol.strip():
 priceNew.write(refSymbol.strip()+ +showme[10])
 
 
 

When the inner loop is finished for the 1st time,
myfile has been read. So next time you start to the
loop, myfile.readlines() returns an empty list.

Something like this should be better:

lookupSymList = myfile.readlines()
for refSymbol in symbols.readlines():
  for lookupSymbol in lookupSymList:
  showme = lookupSymbol.split('\t')
  if showme[3] == refSymbol.strip():
  priceNew.write(refSymbol.strip()+ +showme[10])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cursor Position.

2005-11-09 Thread Juho Schultz
Samantha wrote:
 I will be using Tkinter. All I need is a way to get the X,Y position from a 
 mouse click. I am trying to have an image loaded to click on, but that seems 
 to be a problem. So if I can just get the position from the screen of a 
 graphics program, showing an image, it will work for me.
 S

If you use TkInter, use also these: 
http://www.pythonware.com/library/tkinter/introduction/index.htm
http://infohost.nmt.edu/tcc/help/pubs/tkinter/

For mouse click position, this might be helpful:
http://www.pythonware.com/library/tkinter/introduction/events-and-bindings.htm
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: append to non-existing list

2005-11-09 Thread Juho Schultz
Yves Glodt wrote:
 Hello,
 
 if I do this:
 
 for row in sqlsth:
 pkcolumns.append(row[0].strip())
 etc
 
 
 without a prior:
 
 pkcolumns = [];
 
 
 I get this error on first iteration:
 UnboundLocalError: local variable 'pkcolums' referenced before assignment
 
 I guess that's normal as it's the way python works...?!?
 
 My question is: Is there no way to append to a non existing list?
 
 I am lazy for declaring it first, IMHO it bloats the code, and (don't 
 know if it's good to say that here) where I come from (php) I was used 
 to not-needing it...
 
 
 regards,
 Yves

You mean you want to type pkcolumns only once to keep your code short?
Would something like this be useful?

pkcolumns = [row.strip() for row in sqlsth]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pylab and pyserial plot in real time

2005-11-08 Thread Juho Schultz
[EMAIL PROTECTED] wrote:
 Hiya,
 
 I've got a PIC microcontroller reading me humidity data via rs232, this
 is in ASCII format. I can view this data easily using hyperterminal or
 pyserial and convert it to its value (relative humidty with ord(input))
 
 But what im trying to do is plot the data in real time, ideally with
 pylab - as it looks simple to use and simple is the way i want to go!
 
This might be close to what you are trying to do:

import time
import pylab
# interactive mode on
pylab.ion()
timefig = pylab.figure(1)
timesub = pylab.subplot(111)
dt = 0.1
t = pylab.arange(0.0, 2.0, dt)
h = 1.2*pylab.sin(t)
lines = pylab.plot(t,h)
for i in range(8):
 t = t + dt
 h = 1.2*pylab.sin(t)
 lines[0].set_data(t,h)
 timesub.set_xlim((t[0],t[-1]))
 pylab.draw()
 time.sleep(1.0)

It shows a piece of sine curve, and updates the x-axis with time.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: any python module to calculate sin, cos, arctan?

2005-11-08 Thread Juho Schultz
Shi Mu wrote:
 any python module to calculate sin, cos, arctan?

math

There are two versions of arctan: atan and atan2.
atan2(y,x) does the quadrant selection
you do not get from atan(y/x)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I create a dir using Python.

2005-11-08 Thread Juho Schultz
sumi wrote:
 How do i create a dir using python.
 
You could use
os.mkdir(my_dir_name)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Not Equal to Each Other?

2005-11-04 Thread Juho Schultz
[EMAIL PROTECTED] wrote:
 How do I 'define' set?  Is there something to include (like import
 random)?
 
set is a built-in type in Python 2.4
If you use 2.3 you can use the sets module with import sets


 while (choice == 3) and len(set(cellboard[0:8]))==len(cellboard[0:8]):
 # DEFINE TWO RANDOM VARIABLES (ONE FOR ARRAY, ONE FOR NUMBER
 VALUE)
 solvingrandom = random.randint(1,9)
 cellboardrandom = random.randint(0,8)
 set(cellboard[0:8])
 
 # CHECK TO MAKE SURE THE RANDOMLY ASSIGNED CELL DOES NOT HAVE A
 VALUE
 if (cellboard[cellboardrandom] is not ('1' or '2' or '3' or '4'
 or '5' or '6' or '7' or '8' or '9')):
 cellboard[cellboardrandom] = solvingrandom
 
 The above is my code (right now it will only work for the first row's
 numbers).  Anything else I need to add?
 
Simplify your code a bit:

'2' is not ('1' or '2' or '3' or '4' or '5' or '6' or '7' or '8' or '9')
evaluates to True
'1' is not ('1' or '2' or '3' or '4' or '5' or '6' or '7' or '8' or '9')
evaluates to False
Somehow I do not believe you want that behavipur.

If cellboard contains characters, you could use:
if (cellboard[cellboardrandom] not in '123456789')

for integers, the following should work:
if not (1 = cellboard[cellboardrandom] = 9)

Using None to code empty cells, you could even have:
if (cellboard[cellboardrandom] is None)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: * TypeError - Need help passings args

2005-11-02 Thread Juho Schultz
Ernesto wrote:
 My program is below.  I'm trying to use two Windows .exe files with
 my command line python interface.  I get user input, then call
 launchWithoutConsole.  This was working OK until I introduced the
 'args' part.  Now I get the following error everytime I call
 launchWithoutConsole:
 
   return subprocess.Popen([command] + args,
 startupinfo=startupinfo).wait()
 
 TypeError: can only concatenate list (not str) to list
 
 I'm not sure if it's the WAY I'm passing it or if it's the function
 itself (which I retrieved from
 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/409002
 )
 
 Please help.  Thanks!
 
[command] is a list.  So also args should be a list,
otherwise [command] + args produces an error.
Add a few square brackets to the calls, just like in the link.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: * TypeError - Need help passings args

2005-11-02 Thread Juho Schultz
Ernesto wrote:
 Thanks, that ran without errors.  The only problem now is that it
 launches devcon.exe without actually passing the parameters to the
 program.  It's as if I just typed devcon at a Windows command prompt
 and pressed enter.  I can't figure out why it doesn't accept my
 parameter.
 
I run python 2.3 on Linux os subprocess module and Windows executables 
are not too familiar to me. But according to docs subprocess.Popen() 
should accept both list and string arguments.

Your strings have backslashes so check docs.python.org/ref/strings.html

a = 'disable @USB\VID_0403PID_6010MI_00\715E4F681'
print a
disable @USB\VID_0403PID_6010MI_0015E4F681

\7 is the ASCII bell so your args may be different from what you think.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OpenSSL in Python

2005-11-01 Thread Juho Schultz
dcrespo wrote:
 Hi to all,
 
 What do I have to install to get the following code work (Win XP,
 Python 2.4.2)
 
 
 from OpenSSL import SSL
 import config
 
 KEY_FILE = config.SSL_KEY_FILE
 CERT_FILE = config.SSL_CERT_FILE
 
 
 --
 
 I've been looking for OpenSSL for python. I found pyOpenSSL, but it
 requires the OpenSSL library, which I only found on
 http://www.openssl.org/, but don't know how to install.
 

Open source is very often distributed as source tarballs that contain
installation instructions. So:

Download archive - extract - read files named INSTALL, README, ...

Repeating the advice you have from some other posters:
You have to install both OpenSSL (the library) and
pyOpenSSL (so python can use the library).

 Other thing is the config module... I'm lost. Someone knows? :-S
 

I'd guess config is local module related to your system setup.
Nothing with that name comes with Python or pyOpenSSL.

 My main purpose is to enable xml-rpc server over an SSL connection.
 
After installing pyOpenSSL have a look at

pyOpenSSL-0.6/examples/SecureXMLRPCServer.py

 Thanks
 
 Daniel
 
I hope this helped a bit.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Jpg

2005-10-28 Thread Juho Schultz
Tuvas wrote:
 I am building a GUI interface at the moment, and would like to have
 support for displaying a jpg file, and a FITS file if possible. Is
 there any way to do this? My interface has been written in Tkinter at
 the moment, especially because of it's great portability, I wouldn't
 have to install the other interface software on every computer that I
 use (At the moment it is 3, and will signifigantly increase). I'd
 prefer to only use built-in functions, but if it can't be done, I'm
 willing to look for something else. Is there any way I can do this?
 Thanks!
 

For FITS file reading, an alternative to pCFITSIO is PyFITS 
(http://www.stsci.edu/resources/software_hardware/pyfits).
I guess both need numarray...

gifImage = Tkinter.PhotoImage(file=file.gif)
ima = yourCanvas.create_image(xpos,ypos,image=gifImage)

is the quickest way to display gifs. My version of Tkinter (1.177)
does not directly support jpg, but with PIL that should be possible.

Ugly but quick solution (for Linux): produce gifs from FITS/jpg
files with os.system(convert) and feed them to Tkinter.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: nested escape chars in a shell command

2005-10-19 Thread Juho Schultz
Eli Criffield wrote:
 I'm try run an ssh command in pexpect and I'm having trouble getting
 everything escaped to do what i want.
 
 Here's a striped down script showing what i want to do.
 
 --
 #!/usr/bin/env python
 import pexpect
 import sys
 if len(sys.argv)  3:
 print ssh.py host command
 sys.exit(1)
 
 host = sys.argv[1]
 command = sys.argv[2]
 
 child = pexpect.spawn('''sh -x -c stty -echo ; ssh -t -o
 'StrictHostKeyChecking no' %s '%s' |awk '{print \%s:\$0}' 
 '''%(host,command,host), timeout=30)
 
 child.setlog(sys.stdout)
 child.expect(pexpect.EOF)
 --
 
 The problem in the pexpect.spawn line, It doesn't like the \%s:\ part
 of the awk command. This is necessary so i can see what server the
 command is running on, In the full script the command will be running
 on about 100 servers at a time.
 It parses out into:
 + stty -echo
 + ssh -t -o 'StrictHostKeyChecking no' testserver date
 + awk '{print testserver:$0}'
 It totally strips out the 
 
 The stty -echo is required because part of what the program does is it
 tries to remember any passwords that are asked for, So you can run a
 command like su -c id and it will remember roots password for the
 next
 server and try that. -echo keeps the root password from being echoed to
 the screen.
 
 The second problem with the command is while su -c id works (taking
 out the awk part) running any command with more then one word after the
 -c in su fails, It strips out the '
 like so:
 ./sshexpect testserver su -c 'ls -l /root'
 + stty -echo
 + ssh -t -o 'StrictHostKeyChecking no' testserver 'su -c ls' -l /root
 su: user /root does not exist
 
 I have tried every combination of escaping i can think of can i can't
 get either problem solved.
 
 Any ideas?
 
 Eli
 

You can pass the argument list of your command to
pexpect.spawn(comm, args=['arg1','arg2'])
If the argument list is empty, pexpect tries to get the arguments
from the comm you passed to it. I guess this gives you problems.

Try using the args parameter. 
Simplest would be args=[' '] just to avoid the processing.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: my array subset method could be improved?

2005-10-14 Thread Juho Schultz
Jim O'D wrote:
 Hi all
 
 I have an array a=array([2,3,1]).
 
 I want to extract an array with all the elements of a that are less than 0.
 
 Method 1.
 new = array([i for i in a if i  0])
 
 Method 2.
 new = a[nonzero(a0)]
 
 I'm using Numeric arrays but can't seem to find a function that does this.
 
 Am I missing a more obvious way to do it quickly?
 
 Thanks
 
 Jim

new = Numeric.compress(Numeric.less(a,0),a)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to make this code faster

2005-10-13 Thread Juho Schultz
[EMAIL PROTECTED] wrote:
 def f(x,y):
 return math.sin(x*y) + 8 * x
 I have code like this:
 
 def main():
 n = 2000
 a = zeros((n,n), Float)
 xcoor = arange(0,1,1/float(n))
 ycoor = arange(0,1,1/float(n))
 
 
 for i in range(n):
 for j in range(n):
 a[i,j] = f(xcoor[i], ycoor[j])  # f(x,y) = sin(x*y) + 8*x
 
 print a[1000,1000]
 pass
 
 if __name__ == '__main__':
 main()
 
 
 I try to make this run faster even using psyco, but I found this still
 slow, I tried using java and found it around 8x faster...
 

I guess the double loop (4E6 rounds) makes your program so slow.

I assume you are using numarray or numeric for this.
The built-in array operations are a lot faster.
Try using them instead. And function calls are not free either.
Xcoor and ycoor are equal, so there is no need to generate them both.

I guess the following would be a lot faster:

def func():
n = 2000
a = numarray.zeros((n,n), Float)
coor = numarray.arange(0,1,1/float(n))

for i in range(n):
a[:,i] = numarray.sin(coor*coor[i]) + 8*coor

print a[1000,1000]
pass
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: recursive function

2005-10-07 Thread Juho Schultz
mg wrote:
 Hello,
 
 In a recursive function like the following :
 
 
 def foo( j ) :
  j += 1
  while j  n : j = foo( j )
  return j
 
 
 in found that the recursivity is limited (1000 iterations). Then, I have 
 two questions :
 - why this mecanism has been implemented ?
 - it is possible to increase or remove (and how) the number of iterations ?
 
 Regards,
 Mathieu

Try the following for answers to both questions:

import sys
print sys.setrecursionlimit.__doc__

I guess 1000 is the default value.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python plotting with greek symbols within labels recommendations?

2005-10-05 Thread Juho Schultz
[EMAIL PROTECTED] wrote:
 hello all,
 
 this message is geared toward those of you in the scientific community.
 i'm looking for a python plotting library that can support rendering
 greek symbols and other various characters on plot axes labels, etc. I
 would prefer something that adheres to tex formatting (as implemented
 in latex, matlab, etc and has the form $\alpha$ to represent the greek
 character alpha for example).
 
 thus far, i've found that matplotlib
 (http://matplotlib.sourceforge.net/) can do this, albeit the
 implementation is so poor that you cannot mix standard text with
 symbols on the same plot element.
 
 

If you already have installed matplotlib, have a look at
matplotlib-0.X.Y/examples/tex_demo.py
It shows you how to mix text and symbols.
The other examples in the directory could also be useful.

Essentially you need to remember 
matplotlib.rc('text', usetex=True)
before plotting.

If you need complex stuff (fractions, sums, integrals) try
putting an r before the string: pylab.ylabel(
rDensity $\left(\rho =\frac{x^2+\frac{x+1}{x-1}}{\kappa(x)K_{ij}}\right))
works fine, at least on my system.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Background process for ssh port forwarding

2005-10-04 Thread Juho Schultz
Jesse Rosenthal wrote:
 Hello all,
 
 I'm writing a script which will backup data from my machine to a server
 using rsync. It checks to see if I am on the local network. If I am, it
 runs rsync over ssh to 192.168.2.6 using the pexpect module to log in.
 That's the easy part.
 
 Now, when I'm not on the local network, I first want to open up an ssh
 connection to do port forwarding, so something like this:
 
 def hostforward():
 #This is based on the assumption that the passfile is the gnus
 #authinfo file, or has a similar format...
 f = open(PASS_FILE, r)
 f_list = f.read().split(' ')
 f.close()
 #Now, we get the entry after password (be slicker to make it a
 #dictionary, but maybe wouldn't work as well).
 pass_index = f_list.index('password') + 1
 forwardpass = f_list[pass_index]
 #now we connect
 command = 'ssh -l %s -L 2022:%s:22 %s' % \
   (login, my_server, forwarding_server)
 connection = pexpect.spawn(command)
 connection.expect('.*assword:')
 connection.sendline(forwardpass)
 
 If I end this with 'connection.interact()', I will end up logged in to the
 forwarding server. But what I really want is to go on and run rsync to
 localhost port 2022, which will forward to my_server port 22. So, how can
 I put the ssh connection I set up in hostforward() in the background?
 I need to make sure that connection is made before I can run the rsync
 command.
 
 I've looked at threading, but that seems excessive. There must be an
 easier way. Whatever I do, though, I'll need to use pexpect to spawn the
 processes, since I'll need to log in to ssh servers with a password.
 
 Thanks for any help.
 
 --Jesse
 
 
I am not sure I understand you correctly (my english is a bit limited)
Can you not use something like:

rsync --timeout=5 -e ssh --with-many-options
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Straight line detection

2005-09-30 Thread Juho Schultz
PyPK wrote:
 Does anyone know of a simple implementation of a straight line
 detection algorithm something like hough or anything simpler.So
 something like if we have a 2D arary of pixel elements representing a
 particular Image. How can we identify lines in this Image.
 for example:
 
 ary =
 [[1,1,1,1,1],
  [1,1,0,0,0],
  [1,0,1,0,0],
  [1,0,0,1,0],
  [1,0,0,0,1]]
 So if 'ary' represents pxl of an image which has a horizontal line(row
 0),a vertical line(col 0) and a diagonal line(diagonal of ary). then
 basically I want identify any horizontal or vertical or diagonal line
 anywhere in the pxl array.
 
 Thanks.
 

I would recommend using a module for computing, my choice would be
numarray: www.stsci.edu/resources/software_hardware/numarray
You could even write your own version of hough, should not be too complex.
A fwee things you need to consider:


1) Are all the lines through the image, or would a row with 
[0,0,1 ...(a few dozen ones in here) ... 1,0] be a line?

2) Do you also need edge detection? Then you might need to convolve
the image with a Laplacian or something like that, e.g.
new[i,j] = (4*old[i,j])-old[i-1,j]-old[i+1,j]-old[i,j-1]-old[i,j+1]

3) How full are the images?
It is much easier if only a small fraction of your image is lines,
in your example more than half of image pixels are lines.

4) How big images are you processing? I always have at least
one million pixels, so the rest may not work for small images.

To do some quicklook checks you can of course go through each row/column
and check if the values are different enough, something like

mat = numarray.array(ima)
x = mat.mean()
dx = mat.stddev()

then check if some rows are different from others, maybe
(mat[:,i].mean()  (x + N*dx)) for white lines or
(mat[:,i].mean()  (x - N*dx))) for black lines
you probably need do a few tests to get a good value of N.

repeat for columns (mat[j,:]) and diagonals:
numarray.diagonal(mat,o) where
o is offset from mat[0,0]

and if you need non-diagonal elements, say
ima = [[1 0 0 0 0]
   [0 0 1 0 0]
   [0 0 0 0 1]]
would contain a line of ones, then

vect = ima.flat

gives the image as a rank-1 array and you can then take strides
(every nth element) just like with normal lists, array[a:b:n]
takes every nth element in array[a:b], so vect[::7] would be [1 1 1]

I hope this helps a bit.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Changing the module not taking effect in calling module

2005-09-27 Thread Juho Schultz
Gopal wrote:
 Hi,
 
 I've a module report.py having a set of funtions to open/close/write
 data to a log file. I invoke these functions from another module
 script.py.
 
 Whenever I'm changing something in report.py, I'm running the file
 (however, it has not effect). After that I'm running script.py again.
 However, the output is not taking effect.
 
 If I shut the IDLE interpreter and all the other files and then reopen
 again; and then run script.py, the output is taking effect.
 
 Is there any way to improve it? I'm new to Python.
 
 -Gopal.
 

you could try reload(module) instead of import module or running the file.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: plateform info.

2005-09-20 Thread Juho Schultz
Monu Agrawal wrote:
 Hi I want to know whether the program is being run on windows or on
 Xnix. Is there any variable or method which tells me that it's windows?
 

os.name - the value is posix for Linux/Unix, nt or ce for Windows,
and so on...
-- 
http://mail.python.org/mailman/listinfo/python-list