Re: [Tutor] need help with syntax

2006-01-11 Thread Danny Yoo


On Tue, 10 Jan 2006, bill nieuwendorp wrote:

 I am trying to convert binary file to ascii

 here is the format spec

 steps = int 4
 value = int 4
 time = float 4 * steps


Hi Bill,

Ok, that structure seems fairly simple so far.


  import struct
  import string
  f = file('binary_file','rb')
  line = f.readline()
 

Ah.  Don't do this.  *grin*

If our file is binary, the only safe function we can use to read from such
a file is read().  newlines() just shouldn't be a concept in binary
files: using readline() on a binary file is a major no-no.

Imagine what happens if your file only contains ten steps.  As a hint:
look at ord('\n').


You mentioned earlier that you're expecting an integer, an integer, and
then a sequence of float.  Don't count bytes if you can help it: let
Python's struct.calcsize() do this for you.

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

Your machine may align bytes differently than you might expect: it may be
best to let the machine handle that for you.


Best of wishes to you!

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


Re: [Tutor] How can I make a python script go directory by directory and excecute on files of choice

2006-01-11 Thread Ed Singleton
On 11/01/06, Liam Clarke [EMAIL PROTECTED] wrote:
 Hi Srinivas -

 For walking a directory, you can use os.walk() or os.path.walk(), but
 I prefer the path module here -
 http://www.jorendorff.com/articles/python/path/.

The Path module is excellent, but it's walk still doesn't take into
account the depth of the current file in the folder structure.

If you need that, I wrote (with Kent's help) a simple script that will
take it into account (you need the Path module above for it to work).

def traverse(directory, function, depth=0):
import path
thedir = path.path(directory)
for item in thedir.files():
function(item, depth)
for item in thedir.dirs():
traverse(item,function, depth+1)

It can be used like:

def doprint(item, depth):
print item

traverse(rC:\Temp, doprint)

Hope it's helpful to someone.

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


[Tutor] extra characters in XML

2006-01-11 Thread Ben Vinger
Hello all

I want to do the following in an XML file:

XFile = open(XmlFile,'r')
for line in XFile.readlines():
if line.find('end_time')  0:
  print line

However, it does not work due to extra characters that
appear in the XML file.  For example if I use the
previous code without the if condition, on a console
it looks like:
 e n d _ t i m e 
And if you output that to a text file and open that in
a text editor, the text editor shows a square instead
of a space in between every character.  What is going
on?

Thanks
Ben





___ 
Yahoo! Photos – NEW, now offering a quality print service from just 8p a photo 
http://uk.photos.yahoo.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] pointers

2006-01-11 Thread Burge Kurt
Hi,

I f I want to translate C code to Python and have a function like 

void get_args(int argc, char* argv[], Argument* args)
{

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


Re: [Tutor] pointers

2006-01-11 Thread Burge Kurt
Sorry for the previous message I did it by mistake..the function was like below:

void get_args(int argc, char* argv[], Argument* args){ //check the amount of the arguments if(argc%2 == 0)
{ printf(Error, incorrect argument numbers : %d\n,argc);  print_help(); exit(1); } 
.
.
}

My first question about the pointers here; how can I convert them to Python? 

And second and may be a little stupid; do I need to define argc how can I get arguments in python ?

Thanks in advance,

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


Re: [Tutor] extra characters in XML

2006-01-11 Thread Ben Vinger
Found the following (which solved the problem, though
not on the console) at
http://www.jorendorff.com/articles/unicode/python.html

  import codecs
  # Open a UTF-8 file in read mode
  infile = codecs.open(infile.txt, r, utf-8)
  # Read its contents as one large Unicode string.
  text = infile.read()
  # Close the file.
  infile.close()

The same function is used to open a file for writing;
just use w (write) or a (append) as the second
argument.


--- Ben Vinger [EMAIL PROTECTED] wrote:

 Hello all
 
 I want to do the following in an XML file:
 
 XFile = open(XmlFile,'r')
 for line in XFile.readlines():
 if line.find('end_time')  0:
   print line
 
 However, it does not work due to extra characters
 that
 appear in the XML file.  For example if I use the
 previous code without the if condition, on a console
 it looks like:
  e n d _ t i m e 
 And if you output that to a text file and open that
 in
 a text editor, the text editor shows a square
 instead
 of a space in between every character.  What is
 going
 on?
 
 Thanks
 Ben
 
 
 
 
   

___
 
 Yahoo! Photos – NEW, now offering a quality print
 service from just 8p a photo
 http://uk.photos.yahoo.com
 ___
 Tutor maillist  -  Tutor@python.org
 http://mail.python.org/mailman/listinfo/tutor
 






___ 
Yahoo! Messenger - NEW crystal clear PC to PC calling worldwide with voicemail 
http://uk.messenger.yahoo.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] extra characters in XML

2006-01-11 Thread Kent Johnson
Ben Vinger wrote:
 Found the following (which solved the problem, though
 not on the console) at
 http://www.jorendorff.com/articles/unicode/python.html
 
   import codecs
   # Open a UTF-8 file in read mode
   infile = codecs.open(infile.txt, r, utf-8)
   # Read its contents as one large Unicode string.
   text = infile.read()
   # Close the file.
   infile.close()
 
 The same function is used to open a file for writing;
 just use w (write) or a (append) as the second
 argument.

Ben,

Most likely your XML file is 16-bit unicode, not utf-8. When ascii text 
is represented as unicode, every other byte will be a null byte. That is 
the extra character that shows up as a space or box depending on who is 
interpreting it. The utf-8 codec must be swallowing the null bytes.

The first line of your XML should show what encoding it is if it is 
different from utf-8. What is in that line?

In your code above, instead of utf-8 try utf_16_be and utf_16_le, one of 
them should work.

Kent

 
 
 --- Ben Vinger [EMAIL PROTECTED] wrote:
 
 
Hello all

I want to do the following in an XML file:

XFile = open(XmlFile,'r')
for line in XFile.readlines():
if line.find('end_time')  0:
  print line

However, it does not work due to extra characters
that
appear in the XML file.  For example if I use the
previous code without the if condition, on a console
it looks like:
 e n d _ t i m e 
And if you output that to a text file and open that
in
a text editor, the text editor shows a square
instead
of a space in between every character.  What is
going
on?

Thanks
Ben




  

 
 ___
 
Yahoo! Photos – NEW, now offering a quality print
service from just 8p a photo
http://uk.photos.yahoo.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

 
 
 
 
   
   
   
 ___ 
 Yahoo! Messenger - NEW crystal clear PC to PC calling worldwide with 
 voicemail http://uk.messenger.yahoo.com
 ___
 Tutor maillist  -  Tutor@python.org
 http://mail.python.org/mailman/listinfo/tutor
 
 


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


Re: [Tutor] pointers

2006-01-11 Thread Bernard Lebel
Hi Burge,

You can access command line argument via sys.argv:

import sys
print sys.argv

This prints a list of the command line arguments. Since argv is a
list, it means you can check its length to get the argument count:

print len( sys.argv )

There is always at least one argument in this list, if no argument was
supplied, then you get an empty string.


Hope this helps
Bernard



On 1/11/06, Burge Kurt [EMAIL PROTECTED] wrote:
 Sorry for the previous message I did it by mistake..
 the function was like below:

 void get_args(int argc, char* argv[], Argument* args)
 {
 //check the amount of the arguments
 if(argc%2 == 0)
{
printf(Error, incorrect argument numbers : %d\n,argc);
print_help();
exit(1);
 }

 .
 .
 }

 My first question about the pointers here; how can I convert them to Python?

 And second and may be a little stupid; do I need to define argc how can I
 get arguments in python ?

 Thanks in advance,

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



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


Re: [Tutor] pointers

2006-01-11 Thread Kent Johnson
Burge Kurt wrote:
 Sorry for the previous message I did it by mistake..
 the function was like below:
  
 void get_args(int argc, char* argv[], Argument* args)
 {
 //check the amount of the arguments
 if(argc%2 == 0)
{
printf(Error, incorrect argument numbers : %d\n,argc);
print_help();
exit(1);
 }

 .
 .
 }
  
 My first question about the pointers here; how can I convert them to 
 Python?

Python doesn't have pointers in the sense of direct references to 
memory. Python has very good built in support for higher-level 
structures than C has. Strings and lists are both built in.

As Bernard has pointed out, where a C function might have a count (argc) 
and a pointer to an array of pointers to strings (char* argv[]), Python 
uses just a list of strings.

I'll guess that Argument* args is a pointer to an array of Argument 
objects. In Python this would be represented by a list of Argument objects.

Use of lists and strings should be covered in any introductory Python 
tutorial or book; you might find one you like here:
http://wiki.python.org/moin/BeginnersGuide/NonProgrammers
http://wiki.python.org/moin/IntroductoryBooks

Kent

  
 And second and may be a little stupid; do I need to define argc how can 
 I get arguments in python ?
  
 Thanks in advance,
  
 Burge
 
 
 
 
 ___
 Tutor maillist  -  Tutor@python.org
 http://mail.python.org/mailman/listinfo/tutor


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


[Tutor] CPU Utilization

2006-01-11 Thread DS
I am implementing a computational cluster and am using a job controller
(for want of a better term) that contacts the worker computers,
determines how busy they currently are, and then assigns more work if
the worker computer is below a certain cpu utilization threshhold. 

For the cpu threshhold, I've been thinking I'd have the worker computer
shell out to perform the top command, parse the results, and report
those values to the job controller.

Is there a better way, or more pythonic, way to do this?

Thanks

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


Re: [Tutor] pointers

2006-01-11 Thread w chun
On 1/11/06, Kent Johnson [EMAIL PROTECTED] wrote:
 Burge Kurt wrote:
 
  void get_args(int argc, char* argv[], Argument* args)
 
  My first question about the pointers here; how can I convert them to
  Python?

 Python doesn't have pointers in the sense of direct references to
 memory. Python has very good built in support for higher-level
 structures than C has. Strings and lists are both built in.

the main reason why pointers are used in C (and C++) is so that the
called function has the ability to modify the object (since it is
passed by reference).

in Python, references to objects passed in are also live, meaning
that if it is a mutable (modifiable) object, you can manipulate it
directly without using the asterisk/star (*).

in bernard's example, we've replaced char* argv[] as an argument to
main by doing an import of sys and using the argv attribute of the sys
module, i.e., sys.argv.  to access individual arguments, you would
replace something like:

for (int i = 0; i  argc; i++) {
:
... argv[i] ...
:
}

... with ...

for i in range(len(sys.argv)):
:
... sys.argv[i] ...
:

... or ...

for eachArg in sys.argv:
:
... eachArg ...
:


 I'll guess that Argument* args is a pointer to an array of Argument
 objects. In Python this would be represented by a list of Argument objects.

it looks like it's a set of variable arguments (varargs).  Python has
support for this too, and it's one of the rare places you will see
asterisks (*) used.

we replace void get_args(int argc, char* argv[], Argument* args)
with def get_args(*args).  (recall that argv is sys.argv and argc is
len(sys.argv).)  then to access each extra argument, you would:

for eachArg in args:
   :
... eachArg ...

hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Core Python Programming, Prentice Hall, (c)2006,2001
http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] pointers

2006-01-11 Thread Danny Yoo


On Wed, 11 Jan 2006, Burge Kurt wrote:

 I f I want to translate C code to Python and have a function like

 void get_args(int argc, char* argv[], Argument* args)
 {


Hi Burge,

Also wanted to note that the Standard Library already contains an
argument-parsing library, so you may want to take advantage of it.  The
library is called 'optparse':

http://python.org/doc/lib/module-optparse.html

It's something to keep in mind, just in case during your porting effort
you have the freedom to reuse the Standard Library.

Good luck!

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


Re: [Tutor] CPU Utilization

2006-01-11 Thread Hugo González Monteverde
Hi,

top is very interactive so it would not be easy at all to parse.

I can suggest reading /proc/loadavg if you're in Linux.

proc(5) ('man 5 proc') says that /proc/loadavg is
 The load average numbers give the number of jobs in
 the run queue averaged over 1, 5 and 15 minutes.
 They are the same as the load average numbers given
 by uptime(1) and other programs.

It can be easily parsed with split()

Hope that helps,

Hugo


DS wrote:
 I am implementing a computational cluster and am using a job controller
 (for want of a better term) that contacts the worker computers,
 determines how busy they currently are, and then assigns more work if
 the worker computer is below a certain cpu utilization threshhold. 
 
 For the cpu threshhold, I've been thinking I'd have the worker computer
 shell out to perform the top command, parse the results, and report
 those values to the job controller.
 
 Is there a better way, or more pythonic, way to do this?
 
 Thanks
 
 ds
 ___
 Tutor maillist  -  Tutor@python.org
 http://mail.python.org/mailman/listinfo/tutor
 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] need help with syntax

2006-01-11 Thread Liam Clarke

 You mentioned earlier that you're expecting an integer, an integer, and
 then a sequence of float.  Don't count bytes if you can help it: let
 Python's struct.calcsize() do this for you.

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

 Your machine may align bytes differently than you might expect: it may be
 best to let the machine handle that for you.


Erk, Danny, is of course, right.

Perhaps I could rewrite my earlier suggestion as -

stepValPattern = 2i
bytesToRead = struct.calcsize(stepValPattern)
bytes = f.read(bytesToRead)
(steps, value) = struct.unpack(stepValPattern, bytes)

floatPattern = %df % steps
bytesToRead = struct.calcsize(floatPattern)
bytes = f.read(bytesToRead)
floatList = struct.unpack(floatPattern, bytes)

f.read() works like following, (rough explanation follows) Let's say
you have a 10 byte file -

00 0E A1 DC B3 09 FF AA B1 B2 00

f.read(3) will return 00 0E A1.

Your file reference is now pointing at the 4th byte of the file, like so.

00 0E A1 DC B3 09 FF AA B1 B2 00
...^   -current read position

So calling f.read(3) again will return

DC B3 09

Calling f.tell() will return the curernt read position, which would
now be 6, the 7th byte (remembering computers count from 0 up.)
f.seek(x) tells Python to move the read position to the xth byte of the file.

You can use that with text files. I.E. If you've just called
f.readlines(), you can use f.seek(0) to return to the start of the
file.

Anyway, I digress, but I'm trying to clarify how struct and f.read()
work together.

So, let's pretend all integers are 4 bytes, ditto all floats, and
there's no byte alignment going on whatsoever. (of course, in real
life you can't, hence using struct.calcsize())

So, you have a file like so -

03 00 00 00 0A 00 00 00 09 0B 21 CD

That's

step  value   step number of floats
03 00 00 00| 0A 00 00 00| 09 0B 21 CD
^ -- read pos

stepValPattern = 2i
bytesToRead = struct.calcsize(stepValPattern)
#bytesToRead is 8 (idealised ints)
bytes = f.read(bytesToRead)

At this point, bytes is 03 00 00 00 0A 00 00 00
(Python would show it as a string \x03\x00\x00\x00\x0A\x00\x00\x00)

And your file now looks like this -
step  value   floats
03 00 00 00| 0A 00 00 00| 09 0B 21 CD
...^ -- read pos

Okay, so now to read the floats.

(steps, value) = struct.unpack(stepValPattern, bytes)
#Converts 03 00 00 00 0A 00 00 00 to (3, 9) 9 chosen at random
#steps equals 3

So now we substitute steps into the floatPattern

floatPattern = %df % steps
#floatPattern now equals 3f which is the same
#struct pattern as fff

bytesToRead = struct.calcsize(floatPattern)
#bytesToRead is 12
bytes = f.read(bytesToRead)
floatList = struct.unpack(floatPattern, bytes)


Does that make sense?

I hope so... but suffice to say - struct.calcsize() ensures cross
platform compatibility... I tend not to use the endian identifier
unless I'm dealing with a data source that will always, absolutely be
a certain endianess, saves having to rejig your patterns for each
different platform.

And use f.read(x) for binary data.

Regards,

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


Re: [Tutor] CPU Utilization

2006-01-11 Thread DS
Thanks for your responses.

Michael Janssen wrote:

It's perhaps easier to read the information from the /proc filesystem
(this is where top gets it itself). man proc tells where the info is
stored (guess: /proc/stat).

  

stat does look in some ways easier.  I will say that I found the
statistics somewhat baffling, but I'm sure it's all there.


Hugo González Monteverde wrote:

Hi,

top is very interactive so it would not be easy at all to parse.

  

Actually top has a batch mode.  This works pretty well.

*def* xmlrpc_idlecpu(self):
u = commands.getoutput('top -b -n 1')
*return* u.split('\n')[2].split(',')[3]

I can suggest reading /proc/loadavg if you're in Linux.

proc(5) ('man 5 proc') says that /proc/loadavg is
 The load average numbers give the number of jobs in
 the run queue averaged over 1, 5 and 15 minutes.
 They are the same as the load average numbers given
 by uptime(1) and other programs.

It can be easily parsed with split()
  

That's an interesting idea to use that.  Although if you have big jobs
and little jobs you might not know whether you can add another job to
that computer or not, because you would necessarily be attempting to
derive the utilization from those statistics. 


Thank you both for your answers.

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


[Tutor] Returning multiple values from a script

2006-01-11 Thread Hans Dushanthakumar
Hi,
   Can a script return multiple values to the os?

What I have in mind is something like the following:


1) Test.py
---
import sys

r = 7
sys.exit(r)
# What I really want to do is something along the lines of sys.exit(r,
Hans)



2) Script1.py (This script executes script test.py and prints out its
exit code): 
--
import os

t = test.py
res = os.system('python test.py)
print res



Thanks,
Hans
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] div_t

2006-01-11 Thread Burge Kurt
Hi,

What is the usage of div_t in python?

I have some unsigned integer variables and want to use ;

div_tdiv_T;
div_t div_N;
div_t div_B;
.
.
..

Best for all,

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


Re: [Tutor] Returning multiple values from a script

2006-01-11 Thread Kent Johnson
Hans Dushanthakumar wrote:
 Hi,
Can a script return multiple values to the os?

Is there a reason why you have to call the second test.py using 
os.system()? I would write it to be imported and called.

test.py
--

def findR():
   return 7, 'Hans'


script1.py
-

import test

res = test.findR()
print res

Kent

 
 What I have in mind is something like the following:
 
 
 1) Test.py
 ---
 import sys
 
 r = 7
 sys.exit(r)
 # What I really want to do is something along the lines of sys.exit(r,
 Hans)
 
 
 
 2) Script1.py (This script executes script test.py and prints out its
 exit code): 
 --
 import os
 
 t = test.py
 res = os.system('python test.py)
 print res

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


Re: [Tutor] div_t

2006-01-11 Thread bob
At 02:59 PM 1/11/2006, Burge Kurt wrote:
Hi,

What is the usage of div_t in python?

I have some unsigned integer variables and want to use ;

div_t div_T;
div_t div_N;
div_t div_B;

Your question is meaningless to me! Please clarify.

div_t is not a Python constant or built_in.

div_t div_T; is not a Python expression.

Python integers are signed.

Does any of this refer to another lannguage? 

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


Re: [Tutor] Returning multiple values from a script

2006-01-11 Thread Hans Dushanthakumar
Yes I agree that it'd be cleaner to import the second script and call
it.

The reason I'm keen to find a alternate method is that I have a whole
lot of scripts that were designed to run only as standalone scripts. ie
each of these scripts is not a function that I could just call from
another script. They are all of the format:

1) Test.py
---
import sys

sys.exit(5)


Now I'm trying to write a master script that'd run each one of these
scripts. I'm sure it would have been a lot easier if the scripts were of
the following format. Unfortunately they are not.:

Test.py
---
import sys

Def test():
return(5, Junk)

if __name__ == __main__:
   test()


Well if there is no other way I think I'll have to alter all the scripts
to be of the above format. Just wondering if anyone has any suggestions
...

Cheers
Hans


-Original Message-
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On
Behalf Of Kent Johnson
Sent: Thursday, 12 January 2006 12:06 p.m.
Cc: Python Tutor
Subject: Re: [Tutor] Returning multiple values from a script

Hans Dushanthakumar wrote:
 Hi,
Can a script return multiple values to the os?

Is there a reason why you have to call the second test.py using
os.system()? I would write it to be imported and called.

test.py
--

def findR():
   return 7, 'Hans'


script1.py
-

import test

res = test.findR()
print res

Kent

 
 What I have in mind is something like the following:
 
 
 1) Test.py
 ---
 import sys
 
 r = 7
 sys.exit(r)
 # What I really want to do is something along the lines of sys.exit(r,
 Hans)
 
 
 
 2) Script1.py (This script executes script test.py and prints out its 
 exit code):
 --
 import os
 
 t = test.py
 res = os.system('python test.py)
 print res

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


Re: [Tutor] Returning multiple values from a script

2006-01-11 Thread Kent Johnson
Hans Dushanthakumar wrote:
 Yes I agree that it'd be cleaner to import the second script and call
 it.
 
 The reason I'm keen to find a alternate method is that I have a whole
 lot of scripts that were designed to run only as standalone scripts. ie
 each of these scripts is not a function that I could just call from
 another script. They are all of the format:
 
 1) Test.py
 ---
 import sys
 
 sys.exit(5)
 
 
 Now I'm trying to write a master script that'd run each one of these
 scripts. I'm sure it would have been a lot easier if the scripts were of
 the following format. Unfortunately they are not.:
 
 Test.py
 ---
 import sys
 
 Def test():
 return(5, Junk)
 
 if __name__ == __main__:
test()
 
 
 Well if there is no other way I think I'll have to alter all the scripts
 to be of the above format. Just wondering if anyone has any suggestions

ISTM that you have to change all the scripts anyway if you want to 
return two values...why not change them to call a different function 
(other than sys.exit) that does what you want? Do the scripts still have 
to run standalone?

For example you could make a module mysys.py:

returnedvalue = None

def exit(value):
   global returnedvalue
   returnedvalue = value

Then just edit the scripts to import mysys and call mysys.exit(), run 
the script with import and get the returnedvalue from mysys.

If you want a base hack that I couldn't possibly recommend :-) I suppose 
you could replace sys.exit() with a function of your own choosing. 
Something like this should work...

   import sys
   returnedvalue = None
  
   def mysysexit(value):
  ...   global returnedvalue
  ...   returnedvalue = value
  ...
   original_exit = sys.exit # if you need to keep the old value...
   sys.exit = mysysexit
  
   sys.exit(5) # here you can just import the module you want to run
   returnedvalue
5

Isn't Python wonderful!
Kent

 ...
 
 Cheers
 Hans
 
 
 -Original Message-
 From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On
 Behalf Of Kent Johnson
 Sent: Thursday, 12 January 2006 12:06 p.m.
 Cc: Python Tutor
 Subject: Re: [Tutor] Returning multiple values from a script
 
 Hans Dushanthakumar wrote:
 
Hi,
   Can a script return multiple values to the os?
 
 
 Is there a reason why you have to call the second test.py using
 os.system()? I would write it to be imported and called.
 
 test.py
 --
 
 def findR():
return 7, 'Hans'
 
 
 script1.py
 -
 
 import test
 
 res = test.findR()
 print res
 
 Kent
 
 
What I have in mind is something like the following:


1) Test.py
---
import sys

r = 7
sys.exit(r)
# What I really want to do is something along the lines of sys.exit(r,
Hans)



2) Script1.py (This script executes script test.py and prints out its 
exit code):
--
import os

t = test.py
res = os.system('python test.py)
print res
 
 
 ___
 Tutor maillist  -  Tutor@python.org
 http://mail.python.org/mailman/listinfo/tutor
 ___
 Tutor maillist  -  Tutor@python.org
 http://mail.python.org/mailman/listinfo/tutor
 
 


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


Re: [Tutor] div_t

2006-01-11 Thread Kent Johnson
Burge Kurt wrote:
 Hi,
  
 What is the usage of div_t in python?
  
 I have some unsigned integer variables and want to use ;
  
 div_t div_T;
 div_t div_N;
 div_t div_B;

I guess this is more C code. It doesn't have any Python equivalent - 
Python doesn't declare variables and doesn't have unsigned integers.

You might be interested in the divmod() function:
   help(divmod)
Help on built-in function divmod in module __builtin__:

divmod(...)
 divmod(x, y) - (div, mod)

 Return the tuple ((x-x%y)/y, x%y).  Invariant: div*y + mod == x.

   divmod(10, 3)
(3, 1)

You will in general get a better response from this list if you tell us 
what problem you are trying to solve, rather than showing brief snippets 
of C. Even better is to attempt a solution in Python and let us see 
where you get stuck. Have you read any of the tutorials I pointed out? 
Programming Python is quite different from C and you should try to get 
the flavor of it.

Kent

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


[Tutor] calloc

2006-01-11 Thread Burge Kurt
Hi again (:

How can I use calloc in python ? Before computing and processing my data I want to know how many bytes are available?

Thanks in advance and best wishes,

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


Re: [Tutor] Returning multiple values from a script

2006-01-11 Thread Hans Dushanthakumar
Thanks for your reply Kent.

Is it possible to dynamically import a module?

The foll snippet of code throws an error ImportError: No module named
testname


t = [test1.py, test2.py] #Actually this list is filled in by a
Tkinter Listbox selection.

for f in t:
testname = f[:-3]
import %s%(testname)
print testname.run_test()


Any other means of importing dynamically?




-Original Message-
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On
Behalf Of Kent Johnson
Sent: Thursday, 12 January 2006 2:02 p.m.
Cc: Python Tutor
Subject: Re: [Tutor] Returning multiple values from a script

Hans Dushanthakumar wrote:
 Yes I agree that it'd be cleaner to import the second script and call 
 it.
 
 The reason I'm keen to find a alternate method is that I have a whole 
 lot of scripts that were designed to run only as standalone scripts. 
 ie each of these scripts is not a function that I could just call 
 from another script. They are all of the format:
 
 1) Test.py
 ---
 import sys
 
 sys.exit(5)
 
 
 Now I'm trying to write a master script that'd run each one of these 
 scripts. I'm sure it would have been a lot easier if the scripts were 
 of the following format. Unfortunately they are not.:
 
 Test.py
 ---
 import sys
 
 Def test():
 return(5, Junk)
 
 if __name__ == __main__:
test()
 
 
 Well if there is no other way I think I'll have to alter all the 
 scripts to be of the above format. Just wondering if anyone has any 
 suggestions

ISTM that you have to change all the scripts anyway if you want to
return two values...why not change them to call a different function
(other than sys.exit) that does what you want? Do the scripts still have
to run standalone?

For example you could make a module mysys.py:

returnedvalue = None

def exit(value):
   global returnedvalue
   returnedvalue = value

Then just edit the scripts to import mysys and call mysys.exit(), run
the script with import and get the returnedvalue from mysys.

If you want a base hack that I couldn't possibly recommend :-) I suppose
you could replace sys.exit() with a function of your own choosing. 
Something like this should work...

   import sys
   returnedvalue = None
  
   def mysysexit(value):
  ...   global returnedvalue
  ...   returnedvalue = value
  ...
   original_exit = sys.exit # if you need to keep the old value...
   sys.exit = mysysexit
  
   sys.exit(5) # here you can just import the module you want to run
   returnedvalue
5

Isn't Python wonderful!
Kent

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


Re: [Tutor] Returning multiple values from a script

2006-01-11 Thread Hans Dushanthakumar
Oops answered my own question. Dynamic importing is done using the
__import__ function:

t = [test1.py, test2.py] #Actually this list is filled in by a
Tkinter Listbox selection.

for f in t:
testname = f[:-3]
test = __import__(%s%(testname))
res = test.run_test()

Cheers
Hans


-Original Message-
From: Hans Dushanthakumar 
Sent: Thursday, 12 January 2006 2:28 p.m.
Cc: Python Tutor
Subject: RE: [Tutor] Returning multiple values from a script

Thanks for your reply Kent.

Is it possible to dynamically import a module?

The foll snippet of code throws an error ImportError: No module named
testname


t = [test1.py, test2.py] #Actually this list is filled in by a
Tkinter Listbox selection.

for f in t:
testname = f[:-3]
import %s%(testname)
print testname.run_test()


Any other means of importing dynamically?




-Original Message-
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On
Behalf Of Kent Johnson
Sent: Thursday, 12 January 2006 2:02 p.m.
Cc: Python Tutor
Subject: Re: [Tutor] Returning multiple values from a script

Hans Dushanthakumar wrote:
 Yes I agree that it'd be cleaner to import the second script and call 
 it.
 
 The reason I'm keen to find a alternate method is that I have a whole 
 lot of scripts that were designed to run only as standalone scripts.
 ie each of these scripts is not a function that I could just call 
 from another script. They are all of the format:
 
 1) Test.py
 ---
 import sys
 
 sys.exit(5)
 
 
 Now I'm trying to write a master script that'd run each one of these 
 scripts. I'm sure it would have been a lot easier if the scripts were 
 of the following format. Unfortunately they are not.:
 
 Test.py
 ---
 import sys
 
 Def test():
 return(5, Junk)
 
 if __name__ == __main__:
test()
 
 
 Well if there is no other way I think I'll have to alter all the 
 scripts to be of the above format. Just wondering if anyone has any 
 suggestions

ISTM that you have to change all the scripts anyway if you want to
return two values...why not change them to call a different function
(other than sys.exit) that does what you want? Do the scripts still have
to run standalone?

For example you could make a module mysys.py:

returnedvalue = None

def exit(value):
   global returnedvalue
   returnedvalue = value

Then just edit the scripts to import mysys and call mysys.exit(), run
the script with import and get the returnedvalue from mysys.

If you want a base hack that I couldn't possibly recommend :-) I suppose
you could replace sys.exit() with a function of your own choosing. 
Something like this should work...

   import sys
   returnedvalue = None
  
   def mysysexit(value):
  ...   global returnedvalue
  ...   returnedvalue = value
  ...
   original_exit = sys.exit # if you need to keep the old value...
   sys.exit = mysysexit
  
   sys.exit(5) # here you can just import the module you want to run
   returnedvalue
5

Isn't Python wonderful!
Kent

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


Re: [Tutor] Returning multiple values from a script

2006-01-11 Thread John Fouhy
On 12/01/06, Hans Dushanthakumar [EMAIL PROTECTED] wrote:
 Any other means of importing dynamically?

There's an __import__ builtin. It's a function that takes a string and
returns the module.

eg:

 sys = __import__('sys')
 sys.platform
'win32'

[actually, it does a bit more than just that; read the docs]

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


Re: [Tutor] Returning multiple values from a script

2006-01-11 Thread Orri Ganel
Hans Dushanthakumar wrote:

Thanks for your reply Kent.

Is it possible to dynamically import a module?

The foll snippet of code throws an error ImportError: No module named
testname


t = [test1.py, test2.py] #Actually this list is filled in by a
Tkinter Listbox selection.

for f in t:
testname = f[:-3]
import %s%(testname)
print testname.run_test()


Any other means of importing dynamically?
  

Well, it's not recommended, but the following will work (I'll leave the 
lectures on why it's not recommended to the more learned on the list  ;-) ):

eval(import %s % testname)


-- 
Email: singingxduck AT gmail DOT com
AIM: singingxduck
Programming Python for the fun of it.

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


Re: [Tutor] Returning multiple values from a script

2006-01-11 Thread Orri Ganel
Hans Dushanthakumar wrote:

Oops answered my own question. Dynamic importing is done using the
__import__ function:

t = [test1.py, test2.py] #Actually this list is filled in by a
Tkinter Listbox selection.

for f in t:
testname = f[:-3]
test = __import__(%s%(testname))
res = test.run_test()

Cheers
Hans

  

I think your method is less a Bad Idea (tm) than mine, so please 
disregard previous message.

Cheers,
Orri

-- 
Email: singingxduck AT gmail DOT com
AIM: singingxduck
Programming Python for the fun of it.

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


Re: [Tutor] Returning multiple values from a script

2006-01-11 Thread Kent Johnson
Hans Dushanthakumar wrote:
 Oops answered my own question. Dynamic importing is done using the
 __import__ function:
 
 t = [test1.py, test2.py] #Actually this list is filled in by a
 Tkinter Listbox selection.
 
 for f in t:
 testname = f[:-3]
 test = __import__(%s%(testname))

If testname is a string, as it is here, %s%(testname) has the same 
value as testname itself, you can just use __import__(testname)

Kent

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


Re: [Tutor] calloc

2006-01-11 Thread Danny Yoo


On Thu, 12 Jan 2006, Burge Kurt wrote:

 How can I use calloc in python ? Before computing and processing my data
 I want to know how many bytes are available?

Hi Burge,

There's no concept of manual memory allocation in Python, and we don't
have direct access to calloc/malloc/free.

You're asking a lot of C-ish questions: have you looked through the Python
Tutorial to get aquainted with the language yet?  See:

http://www.python.org/doc/tut/




One of the main distinctions between Python and C is that Python
programming has a very dynamic feel to it.  Program properties that may be
static in other languages are fairly dynamic in Python.

For example, rather than predefine a line buffer to read lines from a
file, we use the readline()  method of a file, which itself dynamically
expands if the line is very long.

The small program:

##
file = open(/etc/passwd)
for line in file:
print line
##

does what you might expect: it displays every line in the file.  Note here
that there are no hardcoded places where we've defined how long line must
be.  (An equivalent C program would be slightly more difficult to write
unless we changed its semantics to read the file character-by-character or
block-by-block where each unit is the same size, rather than line-by-line
where each line's length can vary.)

All the memory allocation and deallocation is handed by the Python
runtime.  Regions of memory that no longer are reachable are freed by
garbage collection (or reference counting).  This GC scheme reduces the
chance of making silly memory-related errors such as double-free or memory
leaking.

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


Re: [Tutor] declaring list

2006-01-11 Thread Logesh Pillay
hello list

I asked yesterday how we can declare an array in python.  Thanks Brian
van den Broek and Frank Schley for your responses.

A[None] * n works for me.

To answer Brian's question, I was writing the standard backtracking
procedure to find the permutations of 1..n taken r at a time.

def permutations (n, r):
A, Used = [None] * (r+1), [False] * (n+1)
def choose (m):
if m  r:
print A[1:],
else:
for j in range (1, n+1):
if not Used [j]:
Used [j] = True
A[m] = j
choose (m+1)
Used [j] = False
choose (1)

Thanks 
Logesh Pillay

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


[Tutor] Finding the Index of a member of a Tuple

2006-01-11 Thread Steve Haley
Hello everyone,

I need to do something very simple but I'm having trouble finding the way to do it - at least easily. I have created a tuple and now need to find the position of individual members of that tuple. Specifically, the tuple is something like: words = (you, me, us, we, and, so, forth) and I need to be able to name a member, for example, us and find what the position (index) of that word is in the tuple. 


I would have thought there would be a simple built in functionfor that but I just went through the built in functions in the Python Library Reference and I didn't find anything. I could probably figure out how to write a whileloop or something to do a sequential search until I found the right member but I really believe there must be an easier way and I'm just not seeing it. You can probably tell I'm just learning Python so any help would be appreciated.


Thanks very much in advance,
Steve
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Finding the Index of a member of a Tuple

2006-01-11 Thread bob
At 08:31 PM 1/11/2006, Steve Haley wrote:
Hello everyone,

I need to do something very simple but I'm having trouble finding 
the way to do it - at least easily.  I have created a tuple and now 
need to find the position of individual members of that 
tuple.  Specifically, the tuple is something like: words = (you, 
me, us, we, and, so, forth) and I need to be able to 
name a member, for example, us and find what the position (index) 
of that word is in the tuple.

I would have thought there would be a simple built in function for 
that but I just went through the built in functions in the Python 
Library Reference and I didn't find anything.  I could probably 
figure out how to write a while loop or something to do a sequential 
search until I found the right member but I really believe there 
must be an easier way and I'm just not seeing it.  You can probably 
tell I'm just learning Python so any help would be appreciated.

Unfortunately there is no list method find. Sigh. Here's how I'd do it:

# create a dictionary with each word as key and ordinal as value
words = dict([(n,m) for m,n in enumerate((you, me, us, we, 
and, so, forth))])
words[me] # returns 1 

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


Re: [Tutor] calloc

2006-01-11 Thread Danny Yoo


On Thu, 12 Jan 2006, Burge Kurt wrote:

 Again thank you :( and sorry for asking that much questions in one day
 and I know most of them were nonsense ..

Don't worry about it; please feel free to continue to ask questions on the
list.  It wasn't quite clear what experience you had before: I have to
assume that you've had a lot of C, but other than that, I'm quite
clueless.


 I read the tutorial and still forget lots of parts again and again
 reading it!

I feel mixed about recommending the official Python Tutotrial: it goes way
too fast for my tastes.  I pointed it out just because it's probably the
quickest way to get a taste of the language, but it's not substantial.

I'd instead recommend a different tutorial; there are several listed from
the link here:

http://wiki.python.org/moin/BeginnersGuide/Programmers

I think that Dive into Python is especially good, but of course, whatever
tutorial there that reads easiest for you is best.


Good luck to you!

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


[Tutor] Locating directory of script?

2006-01-11 Thread Liam Clarke
Hi all,

Let's say I have a script called bob.py in a directory called
c:\pythonstuff, which is in my PATH env_var, and python is also in my
PATH, and from a completely different directory I call python bob.py
is there a right way to determine what directory bob.py resides in?

So far I've found that

import inspect

class Foo:
pass

sourceP = inspect.getsourcefile(Foo)

works, but I'm not too sure how resilient that is...

Regards,

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


Re: [Tutor] Finding the Index of a member of a Tuple

2006-01-11 Thread Brian van den Broek
bob said unto the world upon 11/01/06 10:47 PM:
 At 08:31 PM 1/11/2006, Steve Haley wrote:
 
Hello everyone,

I need to do something very simple but I'm having trouble finding 
the way to do it - at least easily.  I have created a tuple and now 
need to find the position of individual members of that 
tuple.  Specifically, the tuple is something like: words = (you, 
me, us, we, and, so, forth) and I need to be able to 
name a member, for example, us and find what the position (index) 
of that word is in the tuple.

I would have thought there would be a simple built in function for 
that but I just went through the built in functions in the Python 
Library Reference and I didn't find anything.  I could probably 
figure out how to write a while loop or something to do a sequential 
search until I found the right member but I really believe there 
must be an easier way and I'm just not seeing it.  You can probably 
tell I'm just learning Python so any help would be appreciated.
 
 
 Unfortunately there is no list method find. Sigh. Here's how I'd do it:
 
 # create a dictionary with each word as key and ordinal as value
 words = dict([(n,m) for m,n in enumerate((you, me, us, we, 
 and, so, forth))])
 words[me] # returns 1 
 

I assume Bob meant that tuples have no index or find method. His 
suggested procedure will work, but it seems more work than:

  t = (I'm, a, tuple., I, have, only, magic, methods.)
  l = list(t)
  l.index(have)
4
  t[4]
'have'
 

I say more work as the way above builds a list to turn into a 
dictionary. But, since dictionary access is fast, it might be quicker 
for long tuples where the sought item is near then end. If it matters, 
test.

HTH,

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


Re: [Tutor] Locating directory of script?

2006-01-11 Thread Brian van den Broek
Liam Clarke said unto the world upon 12/01/06 12:32 AM:
 Hi all,
 
 Let's say I have a script called bob.py in a directory called
 c:\pythonstuff, which is in my PATH env_var, and python is also in my
 PATH, and from a completely different directory I call python bob.py
 is there a right way to determine what directory bob.py resides in?
 
 So far I've found that
 
 import inspect
 
 class Foo:
   pass
 
 sourceP = inspect.getsourcefile(Foo)
 
 works, but I'm not too sure how resilient that is...
 
 Regards,
 
 Liam Clarke

Hey Liam,

  import this
The Zen of Python, by Tim Peters

snip the wisdom
  this.__file__
'/usr/lib/python2.4/this.pyc'
 

HTH,

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


Re: [Tutor] Finding the Index of a member of a Tuple

2006-01-11 Thread Terry Carroll
On Wed, 11 Jan 2006, Steve Haley wrote:

 I need to do something very simple but I'm having trouble finding the way to
 do it - at least easily.  I have created a tuple and now need to find the
 position of individual members of that tuple.  Specifically, the tuple is
 something like: words = (you, me, us, we, and, so, forth) and
 I need to be able to name a member, for example, us and find what the
 position (index) of that word is in the tuple.

Does it have to be a tuple?  If you make it a list, you can use index():

 words = [you, me, us, we, and, so, forth]
 words.index(and)
4

If it must be a tuple, you can't do that directly:

 words = (you, me, us, we, and, so, forth)
 words.index(and)
Traceback (most recent call last):
  File stdin, line 1, in ?
AttributeError: 'tuple' object has no attribute 'index'


but you can wrap it in a list conversion:

 words = (you, me, us, we, and, so, forth)
 list(words).index(and)
4

I'm not sure why tuple wouldn't have this capability; but it doesn't.

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