[Tutor] IDLE

2017-12-29 Thread Jay Kelman
I’m a beginner. I downloaded Python and when I look at IDLE it tells me to 
update TCL. I downloaded updated Active TCL and installed it but can’t figure 
how to use update to get IDLE corrected.

Any help?

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] New blog that has solution for python programs

2017-06-03 Thread Jay Lozier



On 06/02/2017 09:07 PM, Mats Wichmann wrote:

I don't think "what the authors might want" is the only factor here.
Personally, I think these programming challenge sites probably do more
harm than good, discouraging people that they're not good enough to be a
programmer because they can't solve the (often exceedingly tricky)
problems on their own. I think they're often dick-measuring contests,
for elite programmers to show off and sneer at "lesser mortals" who
can't solve the problems.

In the real world, nobody has to solve these sorts of problems under the
constraints given. In real life programming, you get to look for
existing solutions, you get to consult with your colleagues, pass ideas
back and forth, etc. If you need a solution to X, and your colleague
already solved it for another project, you say "Hey Fred, I'm stealing
your code" and if Fred gets upset you talk to his project manager who
tells Fred to cooperate.

Indeed... they're a slightly tamer variant of the even worse "clickbait"
articles like "how to answer the 10 top Python interview questions", not
a single one I've ever seen being something I'd expect to be part of a
competent interview process.

However, I still don't like the idea of answering people's quizzes. I
won't violently disagree with Steven's viewpoint, however.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
"Hey Fred, I'm stealing your code" - in the group I am in we are 
expected to use each other's code. Reusing known, good, working code 
saves time, money, and effort. Also, we are expected to ask each other 
for advice as needed.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] PyctvhccTV TtV v.:vgvon v3 Tkinter GgUI program

2016-10-24 Thread Jay Talbot
Qk.   vv"::.:

On Oct 24, 2016 6:08 PM, "Elliott Andrews" 
wrote:

Hi there, I am making a program in python based on a Subway operation. All
descriptions and comments codes are provided in the attached program. I've
been using IDLE to run the program and it seems to work the way I want it
too.

However I have heard from many, that global variables are bad practise in
any programming language, and so I want to basically replace all my global
variables with another variable that does the same thing.

The problem is, some data is entered and then when the data is submitted,
the GUI window terminates and automatically re-opens for another data
entry. I need some sort of variable to store some data while the program
resetts itself.

Sorry is this sounds really broad, and I am happy to clarify and points.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Read, Write, Split and Append lines from a text file

2014-07-19 Thread Jay Lozier

  
  
Please include the complete stack
trace error message

It will help in determining what the error is.

Jay 
On 07/19/2014 05:27 PM, LN A-go-go
  wrote:


  
I have given it all I got: a week trying to open, read,
  write, split, append, convert to integers and then manipulate
  the data.  I have attached the file I want to pull the names
  and numbers from.  I'll cut and paste it incase that doesn't
  work and then include a sample of the python shell code.  


AK 36
  AL 39
  AR 39
  AZ 45
  CA 61
  CO 54
  CT 61
  DC 93
  DE 62
  FL 51
  GA 47
  HI 72
  IA 54
  ID 36
  IL 62
  IN 50
  KS 41
  KY 41
  LA 40
  MA 62
  MD 62
  ME 58
  MI 57
  MN 54
  MO 49
  MS 43
  MT 47
  NC 50
  ND 45
  NE 41
  NH 54
  NJ 57
  NM 57
  NV 55
  NY 62
  OH 51
  OK 34
  OR 57
  PA 55
  RI 63
  SC 45
  SD 45
  TN 42
  TX 44
  UT 34
  VA 53
  VT 67
  WA 58
  WI 56
  WV 43
  WY 33


# and now my newbie attempt:
# I can get this far in approach #1
>>> filename =
  "z:/Geog482/egund919/Program1/BOJ.txt"
  >>> myfile = open(filename,"r")
  >>> newfile =
  "z:/Geog482/egund919/Program1/BOJ_B.txt"
  >>> mynewfile = open(newfile,"w")
  >>> while True:
   line = myfile.readline()
   print line
   mynewfile.write(line)
   if not line: break
 
  States OJ
AK 36
AL 39
AR 39
AZ 45
CA 61
CO 54
CT 61
DC 93
DE 62
FL 51
GA 47
HI 72
IA 54
ID 36
IL 62
IN 50
KS 41
KY 41
LA 40
MA 62
MD 62
ME 58
MI 57
MN 54
MO 49
MS 43
MT 47
NC 50
ND 45
NE 41
NH 54
NJ 57
NM 57
NV 55
NY 62
OH 51
OK 34
OR 57
PA 55
RI 63
SC 45
SD 45
TN 42
TX 44
UT 34
VA 53
VT 67
WA 58
WI 56
WV 43
WY 33




In approach number 2: trying to append, convert
  to integer, but the list comes up empty:


>>> infile =
  open('C:/Python27/egund919/Program1/BOJ_B.txt','r')
  >>> import string
  >>> state_name = []
  >>> data_value = []
  >>> counter = 0
  >>> x = 0
  >>> line = infile.readline()
  >>> while True:
    line = infile.readline()
    if not line: break
    counter = counter + 1
    States, OJ = string.split(line)
    XSTATES = str(States)
    XNUM = int(OJ)
    state_name.append(XSTATES)
    data_value.append(XNUM)
   
  >>> type(data_value)
  
  >>> print(data_value)
  []
  >>> print (line)
  

All I get is errors from here on out.




LN

  
  
      
  
  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor



-- 
Jay Lozier
jsloz...@gmail.com
  

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Strange issue output not showing up as floats

2014-06-21 Thread Jay Lozier


On 06/20/2014 07:59 PM, Deb Wyatt wrote:

Hello.  I hope everyone is having a good day.  I am working on an assignment 
that is supposed to output floats.  I'm using floats in the computations and 
according to Python's rules the output should be floats, but it's not.  When I 
test in Python shell the calculations display correctly, as floats.

I'm using Python 2.7 for this assignment.

input is as follows  (not in code order):
balance = 4213
annualInterestRate = 0.2
monthlyPaymentRate = 0.04
payment = monthlyPaymentRate * balance
balance = balance - payment
total_paid = payment

output looks like this:

Month: 1
Minimum monthly payment: 168
Remaining balance: 4111
Month: 2
Minimum monthly payment: 164
Remaining balance: 4013
Month: 3
Minimum monthly payment: 160
Remaining balance: 3916
...etc...

Would any of you have a clue what could be wrong?
Deb in WA, USA


Deb,

Can you show us your full code listing or if it is lengthy the relevant 
section showing the print statement. My guess is your print formating is 
not specified correctly and it is rounding to the nearest whole number.


Jay

--
Jay Lozier
jsloz...@gmail.com

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] (no subject) - (added) Number guessing game

2014-05-08 Thread Jay Lozier

  
  

On 05/08/2014 06:00 AM, Kevin Johnson
  wrote:


  Hi,


Total
  beginner to python and am working my way through Michael
  Dawsons 'Absolute beginner' book. Just got stuck on the last
  bit of the challenges from chapter 3. Essentially need to
  create a game where the user picks a number between 1 and 100
  and the computer has to guess, program should indicate to the
  computer if the guess need to be higher or lower, it should
  also count the number of attempts and call a halt to the game
  if a set number of attempts is reached.


The
  highlighted bit is where I think I'm going wrong but I just
  can't think how to make the computer remember the previously
  closest highest and lowest guesses, not sure if you have all
  read Micheal Dawsons book but I've not covered a whole lot by
  chapter 3 and so any hints/solutions need to be pretty basic
  as I don't want to get ahead of myself.
  

  
  Thanks,
  Kevin



  #numbers game again but...
  #user picks number between 1 and 100
  #and computer guesses
  
  
  import random
  

  
  user_number = int(input("Pick a number between 1 and
100: "))
  computer_guess = random.randint(1, 100)
  guesses = 1
  
  
  while computer_guess != user_number:
      print("The computers guess is", computer_guess)
      if computer_guess > user_number:
          print("Lower...")
      else:
          print("Higher...")
      if guesses == 10:
          print("You lose computer!")
          break
      if
  computer_guess > user_number:
         
  computer_guess = random.randrange(1,
  (computer_guess-1))
     
  else:
         
  computer_guess = random.randint((computer_guess + 1),
  100)
      guesses += 1
      if computer_guess == user_number:
          print("Well done you guessed the number was",
user_number)
          print("It took you", guesses, "tries")
  
  
  input("Press the enter key to exit.")

  

  
  

This is a classic game. 

The first issue I see is the while exit condition. I prefer to use:

max_guess = 7  
  # I believe this game can be won in 7 guesses if the correct
  strategy is used.
  guess = 0
  initial_guess = random.randrange(1, 100)
  while guess < max_guess:
      do stuff
      guess += 1
  
Also, I would model how you would play this game efficiently
against a person. Then write the "do stuff" to replicate that. Hint:
you do not need to generate random guesses within the while loop.

-- 
Jay Lozier
jsloz...@gmail.com
  

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] while loop

2014-03-28 Thread Jay Lozier


On 03/29/2014 01:18 AM, Scott W Dunning wrote:

On Mar 28, 2014, at 9:54 PM, Scott W Dunning  wrote:


Hello, I’m working on some practice exercises from my homework and I’m having 
some issues figuring out what is wanted.

We’re working with the while loop and this is what the question states;

Write a function print_n that prints a string n times using iteration.

"""Print the string `s`, `n` times.


This is also in the exercises and I’m not sure what it means and why it’s there.

assert isinstance(s, str)
assert isinstance(n, int)


Any help is greatly appreciated!

Scott

This is what I have so far but I’m not really sure it’s what the excersise is 
asking for?

n = 5
def print_n(s, n):
while n > 0:
print s * n

print_n("hello", 10)


Scott,

Are required to use a while loop?

Two ways to solve this, while loop and for in range loop

while loop
n = 5
s = 'some string'

def while_print(s, n):
index = o
while index < n:
print(index, s)
index += 1

def alternative_print(s, n):
for index in range(0, n):
print(index, s)

The while loop requires that a counter variable or some loop exit 
condition so you do not end up in an endless loop. This is a common 
problem with while loops in programming, not just Python. So, if there 
is alternative method of looping available, good programming practice is 
to avoid a while loop in any language. The for loop version 
automatically iterates over the range from 0 to n-1 (5 times). I 
included the index variable in the print to show the increase of the index.


The results for both:
0 some string
1 some string
2 some string
3 some string
4 some string

--
Jay Lozier
jsloz...@gmail.com

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Convert os.random output to a string

2014-03-06 Thread Jay Lozier

Alan

I am planning to store the passwords encrypted. This part is allow a 
user to generate and view the generated password.


Ben got me pointed to a snippet I can use. I was trying to do something 
the hard way.


Jay
On 03/06/2014 07:34 PM, Alan Gauld wrote:

On 06/03/14 23:32, Jay Lozier wrote:


I am try to generate random password strings of an arbitrary user
selected length. I read to generate a random string of a user supplied
length I can use os.urandom(n).


So far so good...

> I want to convert the output to a human readable string.

Define human readable?


I would like to store the string for later processing.


Depending on the application there may be laws/rules/guidance 
prohibiting the storage of passwords. Best practice only ever

stores the encrypted form not the original password (or more
properly nowadays pass-phrase since phrases are more secure
than words.)


Also, I would like to limit the characters to the US keyboard, so I
might be using the wrong function.


Even in the US not everyone uses a "US keyboard" especially nowadays 
with various tablets/phablets/phones in use. but if you stick to the 
printable subset of the old ASCII set you should be close enough...

But that probably means building your own random generator based
on the subrange of characters.


I am probably missing something very obvious.


Maybe, or you could be asking for more than the library gives?



--
Jay Lozier
jsloz...@gmail.com

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Convert os.random output to a string

2014-03-06 Thread Jay Lozier

Hi,

My first question

I am try to generate random password strings of an arbitrary user 
selected length. I read to generate a random string of a user supplied 
length I can use os.urandom(n). I want to convert the output to a human 
readable string. I would like to store the string for later processing.


Also, I would like to limit the characters to the US keyboard, so I 
might be using the wrong function.


The following is the output from my terminal - Python 3.3.4 on Manjaro 
Linux shows the generation of a random :


Python 3.3.4 (default, Feb 11 2014, 15:56:08)
[GCC 4.8.2 20140206 (prerelease)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from os import urandom
>>> a = urandom(16)
>>> type(a)

>>> a_str = a.decode()
Traceback (most recent call last):
  File "", line 1, in 
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb1 in position 0: 
invalid start byte

>>>

I am probably missing something very obvious.

Thanks in advance!

--
Jay Lozier
jsloz...@gmail.com

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Beginner - understanding randint arguments

2014-02-15 Thread Jay Lozier


On 02/15/2014 11:25 AM, Marc Eymard wrote:

Hello Tutor,

I need to generate a random integer between 0 and 100.

The range is supposed to be adjusted by my two variables:
low_range and high_range.

The logic of using the variables as part of the function arguments is 
to manage to get a smaller range each time the function is called 
_excluding_ the possible repeat of the return value of randint.


Here is what happens in my script:

>>> import random
>>> low_range = -1
>>> high_range = 101
>>> random.randint(low_range + 1, high_range - 1)
56
>>> low_range
-1
>>> high_range
101*
*


I was rather expecting:

 >>> low_range

0

>>> high_range

100


Can somebody explain why both low_range and high_range are still 
returning their initial values ?


Thanks,
Marc*
*


The variables low_range and high_range are not modified. The arguments 
to random.randint do not change the initial values of the variables, 
only the actual values passed.


--
Jay Lozier
jsloz...@gmail.com

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python 3.3 on OpenSUSE 12.3

2013-10-24 Thread Jay Lozier
On Thu, 2013-10-24 at 21:57 +0200, Rafael Knuth wrote: 
> Hej,
> I can't get Python 3.3 up and running (it's properly installed but I
> can't launch it), and I was wondering if anyone using OpenSUSE 12.3
> had similar issues. SUSE community folks weren't really able to help
> me, so I was wondering I give it a try here.
> Thanks,
> Rafael

Rafael,

I have both Python 2.7.3 and 3.3.0 installed on openSUSE 12.3. To use
3.3 I enter python3.3 at the prompt. If I enter python it defaults to
2.7.3

In the shebang #!/usr/bin/env python3.3

-- 
Jay Lozier
jsloz...@gmail.com

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Won't run. Syntax Error.

2013-09-08 Thread Jay Lozier
-Original Message-
From: Kimberly Mansfield 
To: tutor@python.org
Subject: [Tutor] Won't run. Syntax Error.
Date: Sun, 8 Sep 2013 14:43:54 -0500

This is the first homework assignment. Driving me crazy - struggling
with it for two entire days. I want to drop this class now. 


I think it is all entered correctly, but it won't run and teacher will
not accept it if it won't run. Says "syntax error" and highlights one of
the numbers in the top line that was there when I first opened it,
before I typed anything. Specifically, this:
Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32
bit (Intel)] on win32   

The middle 3 (in red) is highlighted. There is no arrow pointing to it
or anything else.  We are supposed to write something to help a pizza
parlor owner figure out how many pepperoni sticks he will need for the
month. The teacher gave us an IPO chart with these definitions and we
are supposed to write the code for it in Python. I used floats
throughout because this is the umpteenth time I have rewritten this
thing, and was thinking maybe it was because I used integers as well as
floats before, and thought maybe the problem was because I used both. 
I will post it below in case you need to see the whole thing. 

Obviously, I have no programming background and this is supposed to be a
beginner's class. 

Please help. I am running out of hair to yank out of my head and my dogs
are afraid of me now. 
Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32
bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> Pizzas = float (input ("Number of Pizzas "))
Number of Pizzas 100
>>> Length = float (input ("Length of Pizzas "))
Length of Pizzas 11
>>> Width = float (input ("Width of Pizzas "))
Width of Pizzas 11
>>> Thickness = float (input ("Thickness of Pepperoni Slices "))
Thickness of Pepperoni Slices .1
>>> Diameter = float (input ("Diameter of Pepperoni Slices "))
Diameter of Pepperoni Slices 1
>>> Edge = float (input ("Crust Edge of Pizzas "))
Crust Edge of Pizzas .5
>>> StickLength = float (input ("Length of Pepperoni Sticks "))
Length of Pepperoni Sticks 10
>>> UsefulLength = Length - 2 * Edge
>>> SlicesLength = UsefulLength / Diameter
>>> UsefulWidth = Width - 2 * Edge
>>> SlicesWidth = UsefulWidth / Diameter
>>> Slices = SlicesWidth * SlicesLength
>>> TotalSlices = Slices * Pizzas
>>> HypoLength = TotalSlices * Thickness
>>> PepperoniSticks = HypoLength / StickLength
>>> print (StickLength)
10.0
>>> print ("You will need", PepperoniSticks, "pepperoni sticks this
month.")
You will need 100.0 pepperoni sticks this month. 


Kimberly,

Your output indicates the code runs correctly as written. There are no
error messages.

I was able to run the code without any errors. I copied and pasted the
code into a text editor (Notepad on Windows or idle3) and removed the
extraneous prompts, echoed output, and spaces.

When saving the file the extension should be *.py.as in pizza.py 
-- 
Jay Lozier
jsloz...@gmail.com

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How did this decimal error pop up?

2013-04-16 Thread Jay Lozier

On 04/16/2013 01:43 PM, Jim Mooney wrote:
I was doing a simple training prog to figure change, and wanted to 
avoid computer inaccuracy by using only two-decimal input and not 
using division or mod where it would cause error. Yet, on a simple 
subtraction I got a decimal error instead of a two decimal result, as 
per below. What gives?


cost = float(input('How much did the item cost?: '))
paid = float(input('How much did the customer give you?: '))
change = paid - cost

*#using 22.89 as cost and 248.76 as paid*

twenties = int(change / 20)
if twenties != 0:
  twentiesAmount = 20 * twenties
  change = change - twentiesAmount
*#change is 5.8745, not 5.87 - how did I get this decimal 
error when simply subtracting an integer from what should be a

  #two-decimal amount?
*  print(twenties, ' twenties')
  print(change)

#and so forth for the rest of the change

--
*Jim Mooney
* 
This is a common problem with decimal numbers that is discussed in 
various numerical methods texts and is independent of the programming 
language. The two numerical texts I have from the 1980's discuss this 
problem using FORTRAN and Pascal ( I am fairly certain they are out of 
print). It caused by binary representation of decimal numbers at times 
will introduce errors in decimal numbers. Many decimal numbers can not 
be exactly represented by a binary number with some binary 
representations being a little higher and some a little lower than the 
actual number. There are recommend algorithms and data encoding 
techniques to use to minimize these problems.


Integers always have an exact binary representation so if it one can 
change the problem to one that uses integers instead of floats then the 
rounding problem disappears. Many financial calculations can be 
converted from dollars to cents to avoid decimals. Unfortunately, many 
science and engineering calculations will need to address the decimal to 
binary to decimal representation errors.


It can be a nasty problem if one does not address it properly an even 
larger error could occur. Often it is suitable error because one does 
not spot that an intermediate calculation is incorrectly implemented.


--
Jay Lozier
jsloz...@gmail.com

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] concatenating files

2009-02-27 Thread Jay Deiman

Bala subramanian wrote:

Hai,

I have file1.dat,file2.dat...file 300.dat  in one directory. I want to 
concatenate all the files in a single file  (total.dat) with a string 
"END" separating the file contents.

my total.dat should be
file1.dat contents
END
file2.dat contents
END


file300.dat.

now i have another 400 such *.dat files in another directory whose 
contents i hve to append to "total.dat", how can i do this task. i need 
to do something like, updating the file total.dat without overwritting it.


Thanks,
Bala


This should about do it:

-

#!/usr/bin/env python

import sys , os , glob

startDir = ''
totalFile = '/path/to/total.dat'

if len(sys.argv) > 1 and os.path.isdir(sys.argv[1]):
startDir = sys.argv[1]
else:
print 'Usage: %s ' % os.path.basename(sys.argv[0])
sys.exit(1)

tfh = open(totalFile , 'a')
for f in glob.glob(os.path.join(startDir , '*.dat')):
tfh.write('%s contents\n' % f)
tfh.write(open(f).read())
tfh.write('\nEND\n')
tfh.close()

-

All you have to do is set "totalFile" to your main output file and then 
call the script as "scriptname.py /path/to/datfile/directory".


--
Jay Deiman

\033:wq!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] passig parameter with CGI...

2009-02-26 Thread Jay Deiman

Spencer Parker wrote:
I am looking for a little instruction on how one would process a set of 
parameters being sent to it through CGI.  I have a script that sends 
info to another script that lives on another server.  The second script 
would then process the information that is passed to it through a 
parameters list in a URL.  It would then trigger the script to do some 
things via XMLRPC.  I have the portion that connects to the XMLRPC 
server, but not the 1st part.  I can send it a list of command line 
parameters, but the spec has changed.  We want to do it with just curl 
and send it parameters with a URL string.  Not really looking for direct 
code...just some ideas on how this is done for the most part.  I looked 
around, but nothing really fit what I wanted...mostly form 
processing...thanks!


I assume the receiving script is going to be a cgi or something like
that.  It sounds like all you want to do here is construct a GET request
to send to a web server.

=
import urllib

options = {'optone': '1' , 'opttwo': '2' , 'optthree': '3'}
url = 'http://www.example.com/path/to/script.cgi?%s' % \
urllib.urlencode(options)
u = urllib.urlopen(url)
# Here you can read the response if needs be
response = u.read()
u.close()
=

That's about it.

--
Jay Deiman

\033:wq!

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


Re: [Tutor] cgi script to start another process in background

2009-02-26 Thread Jay Deiman

Ravi Kondamuru wrote:

Hi,

I am trying to write a python cgi script, that invokes another process 
and exists.

Using the subprocess documentation on NO_WAIT, I am not having much success:

pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
==>
pid = Popen(["/bin/mycmd", "myarg"]).pid

The script seems to wait for the new process to exit before returning to 
the user.


I tried doing the double-fork approach discussed here:
http://code.activestate.com/recipes/66012/


Are you on some kind of Unix box here?  The fork approach should
definitely work for you.  An even simpler example, which should still
work for you, is here:


import os , time , sys

print 'hello before the fork'

if os.fork():
print 'parent exiting'
sys.exit()

print 'hello from child: %d' % os.getpid()
time.sleep(30)
os._exit(0)


You should be able to verify that you have that process still running
after the main process exits.

--
Jay Deiman

\033:wq!

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


Re: [Tutor] url parsing

2009-02-15 Thread Jay Jesus Amorin
Thanks this is much more simple and is what i need.

On Sun, Feb 15, 2009 at 9:29 PM, Lie Ryan  wrote:

> On Sun, 15 Feb 2009 14:22:09 +0100, Andre Engels wrote:
> > What is 'new' in your solution? Apart from that, the following looks
> > simpler:
> >
>  url = "http://this/is/my/url/to/parse"; parts = url.split('/')
>  sol = '/'.join(parts[:-1])
>  sol
> > 'http://this/is/my/url/to'
>
> do you want something even more simpler?
>
> >>> url ="http://this/is/my/url/to/parse";
> >>> url.rsplit('/', 1)[0]
> 'http://this/is/my/url/to'
>
> ___
> 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] url parsing

2009-02-15 Thread Jay Jesus Amorin
Hi,

Can you please help my how to parse.

url = http://this/is/my/url/to/parse

how do i parse url to print "http://this/is/my/url/to";

i want to remove the last part of my url with is "parse". I would like to
remove the last string of my url.

i have try split, but i think it wont work as i dont know how long my url
would be in my real application.

Thanks,


Newbie,

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


Re: [Tutor] string fomatting

2009-01-31 Thread Jay Jesus Amorin
Thanks bob.

I want to search any characters in test after
https://www.localhost.org/<https://www.localhost.org/testmodule/dev/trunk/admin/sql/mytest.sql>and
the search will end after it finds another /

and when i print it will display *testmodule*.

Newbie,

Jay



On Sun, Feb 1, 2009 at 2:29 AM, bob gailer  wrote:

> Jay Jesus Amorin wrote:
>
>> Hi,
>>
>> I'm a newbie trying to learn python. Kindly help me on string formatting.
>>
>> test =
>> https://www.localhost.org/testmodule/dev/trunk/admin/sql/mytest.sql
>>
>> what will i use to print this output?
>>
>> 1, https://www.localhost.org/
>>
>> 2. testmodule
>>
>> 3. /dev/trunk/admin/sql/mytest.sql
>>
>>
>>  Oh now I get it. I thought that you had posted code at that site. Now I
> think you want to do something  to the string
>
> " https://www.localhost.org/testmodule/dev/trunk/admin/sql/mytest.sql";
>
> Too bad you did not put it in quotes!
>
> It is not clear as to how "string formating" applies to this question.
>
> The obvious answer is:
>
> print("1, https://www.localhost.org/"";
> print()
> print("2. testmodule")
> print()
> print("3. /dev/trunk/admin/sql/mytest.sql")
>
> If that is not what you are looking for please explain.
>
>
> --
> Bob Gailer
> Chapel Hill NC
> 919-636-4239
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] string fomatting

2009-01-31 Thread Jay Jesus Amorin
Hi,

I'm a newbie trying to learn python. Kindly help me on string formatting.

test = https://www.localhost.org/testmodule/dev/trunk/admin/sql/mytest.sql

what will i use to print this output?

1, https://www.localhost.org/

2. testmodule

3. /dev/trunk/admin/sql/mytest.sql



Thanks,


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


Re: [Tutor] rrdtool examples.

2008-12-08 Thread Jay Deiman
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Jeremiah Jester wrote:
> Is anyone on here using the python-rrdtool module for graphing and
> analysis? If so, do you have some sample scripts you could show me.
> There doesn't seem to be a lot out there as far as real world python
> examples.
> 
> Thanks,
> JJ

Actually, I was just playing around with the rrdtool library for python
last week.  It turns out that you basically just use the command line
options as options for the different method calls (like create()).  All
you really have to do is check out the man pages for rrdtool to have all
the documentation you need for the rrdtool python module.  You literally
pass in the command line opts just as they would appear on the command
line.  Here is a quick little script that I whipped up for playing purposes:
- 

#!/usr/bin/env python

import rrdtool , time , random

stime = int(time.time()) - 5 * 86400
dpoints = 1000
etime = stime + (dpoints * 300)
fname = 'test.rrd'
gfname = 'test.png'

rrdtool.create('test.rrd' ,
'--start' , str(stime) ,
'DS:speed:COUNTER:600:U:U' ,
'RRA:AVERAGE:0.5:1:576' ,
'RRA:AVERAGE:0.5:6:336'
)

ctime = stime
cmiles = 0
for i in xrange(dpoints):
bump = random.randint(1 , 20)
cmiles += bump
ctime += 300
rrdtool.update(fname , '%d:%d' % (ctime , cmiles))

rrdtool.graph(gfname ,
'--start' , str(etime - (24 * 3600)) ,
'--end' , str(etime) ,
'--vertical-label' , 'Speed m/h' ,
'--imgformat' , 'PNG' ,
'--title' , 'Speeds' ,
'--lower-limit' , '0' ,
'DEF:myspeed=%s:speed:AVERAGE' % fname ,
'CDEF:mph=myspeed,3600,*' ,
'VDEF:msmax=mph,MAXIMUM' ,
'VDEF:msavg=mph,AVERAGE' ,
'VDEF:msmin=mph,MINIMUM' ,
'VDEF:mspct=mph,95,PERCENT' ,
'LINE1:mph#FF:My Speed' ,
r'GPRINT:msmax:Max\: %6.1lf mph' ,
r'GPRINT:msavg:Avg\: %6.1lf mph' ,
r'GPRINT:msmin:Min\: %6.1lf mph\l' ,
r'GPRINT:mspct:95th Perc\: %6.1lf mph\l'
)

- 

That, coupled with the rrdtool man pages (which are very good, complete
with examples) should be enough to get you started.

- --
Jay Deiman

\033:wq!
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.9 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iEYEARECAAYFAkk9YNwACgkQQ0lr+ZVKSBiWTQCgoBuzQVeRHBlrJ7GONQAL0RFT
qOwAn3cnbZot0q1qGf6mOFHS8QgQc53o
=h7CZ
-END PGP SIGNATURE-
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Learning Python from books

2008-06-19 Thread jay
Me personally, both "Learning Python" and "Core Python Programming".  I am
by no means an expert, but both of these books are excellent and were quite
helpful.

jay

On Thu, Jun 19, 2008 at 1:56 PM, Zameer Manji <[EMAIL PROTECTED]> wrote:

> -BEGIN PGP SIGNED MESSAGE-
> Hash: SHA512
>
> Has anyone here attempted to learn Python from books ? I recently
> purchased "Learning Python" 3rd Edition (9780596513986) and if anyone
> here is a good bottom-up learner than it is the perfect book. The author
> goes over each feature in python, explaining it's syntax, usage and the
> "pythonic" way of using them in programs. It has really helped me
> understand some of the more powerful tools in python and I am sure it
> will make an excellent reference book in the future. With that said, has
> anyone else attempted to learn python from books and if so which one ?
> -BEGIN PGP SIGNATURE-
> Version: GnuPG v1.4.7 (MingW32)
>
> iQEcBAEBCgAGBQJIWqvxAAoJEA759sZQuQ1BS+kIAK+6TWqesUQjEQygwsMI3seU
> ZWUkd4wlextCOXIH6mse4TMHdAU3+NHDo1V4QwSYxNTEjwpWFr1Kg2BE0zyMyxPD
> gs8Kaov6/DGQgyFFt5DRcKvkQ0M5St7I/PuP+n/eelMUK1culvXx3oycKBqh8D21
> R/g0SQ0M9pUDLuBEygbgjFw1WVsf/h8/zCc38qHQ+QOQvrVaEciV3I5JLyp3+u8g
> JyjzxjHSRHd4Ik4cnaeKa2OyFn5JaPXxPmrmPiE3WEWnJxLWucXAP/CEm7e9aamQ
> Fv4SYuVmOIGpbAqySgEpQH2yRsd+0qaNKSJq4hqjQ1/z2Bx6hM5LTqJAVjfZMW4=
> =9xVw
> -END PGP SIGNATURE-
> ___
> 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] Getting started with Python

2008-05-16 Thread jay
Your right, typo :-)

On Fri, May 16, 2008 at 10:57 AM, Hansen, Mike <[EMAIL PROTECTED]>
wrote:

>  Isn't it
>
> import file
>
> not
>
> import file.py
>
> or has that changed in recent versions?
>
> Mike
>
>  --
> *From:* [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] *On
> Behalf Of *jay
> *Sent:* Friday, May 16, 2008 9:44 AM
> *To:* tutor@python.org
> *Subject:* Re: [Tutor] Getting started with Python
>
> Have you tried this ?
>
> import sys
> sys.path.append('/directory1/directory2')
> import file.py
>
> j
>
> On Fri, May 16, 2008 at 10:20 AM, Moishy Gluck <[EMAIL PROTECTED]>
> wrote:
>
>>
>>
>> On Fri, May 16, 2008 at 11:20 AM, Moishy Gluck <[EMAIL PROTECTED]>
>> wrote:
>>
>>> You need to place a "__init__.py" file in a directory you want to
>>> reference in an import statement.
>>>
>>> I don't believe the content of the file is important but you can place
>>> code in the file that will affect how files are imported.
>>>
>>> The import syntax is a such.
>>>
>>> import directory1.directory2.file.py
>>>
>>> Place "__init__.py" in both "directory1" and "directory2"
>>>
>>> Good luck simon.
>>>
>>>
>>> On Fri, May 16, 2008 at 8:16 AM, ppaarrkk <[EMAIL PROTECTED]> wrote:
>>>
>>>>
>>>> I can't.
>>>>
>>>>
>>>> >>> import file.py
>>>>
>>>>
>>>> is all very well if the interpreter knows where file.py is.
>>>>
>>>>
>>>> I want to do this :
>>>>
>>>> >>> import /directory1/directory2/file.py
>>>>
>>>>
>>>> Is this not possible ?
>>>>
>>>> --
>>>> View this message in context:
>>>> http://www.nabble.com/Getting-started-with-Python-tp17273337p17273337.html
>>>> Sent from the Python - tutor mailing list archive at Nabble.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
>>
>>
>
> ___
> 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] Getting started with Python

2008-05-16 Thread jay
Have you tried this ?

import sys
sys.path.append('/directory1/directory2')
import file.py

j

On Fri, May 16, 2008 at 10:20 AM, Moishy Gluck <[EMAIL PROTECTED]>
wrote:

>
>
> On Fri, May 16, 2008 at 11:20 AM, Moishy Gluck <[EMAIL PROTECTED]>
> wrote:
>
>> You need to place a "__init__.py" file in a directory you want to
>> reference in an import statement.
>>
>> I don't believe the content of the file is important but you can place
>> code in the file that will affect how files are imported.
>>
>> The import syntax is a such.
>>
>> import directory1.directory2.file.py
>>
>> Place "__init__.py" in both "directory1" and "directory2"
>>
>> Good luck simon.
>>
>>
>> On Fri, May 16, 2008 at 8:16 AM, ppaarrkk <[EMAIL PROTECTED]> wrote:
>>
>>>
>>> I can't.
>>>
>>>
>>> >>> import file.py
>>>
>>>
>>> is all very well if the interpreter knows where file.py is.
>>>
>>>
>>> I want to do this :
>>>
>>> >>> import /directory1/directory2/file.py
>>>
>>>
>>> Is this not possible ?
>>>
>>> --
>>> View this message in context:
>>> http://www.nabble.com/Getting-started-with-Python-tp17273337p17273337.html
>>> Sent from the Python - tutor mailing list archive at Nabble.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
>
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Regular expressions...

2008-05-02 Thread jay
dir = '/xen/domains2/machinename/disk.img'
a = dir.split('/')[3]

is what I would use...

On Fri, May 2, 2008 at 12:38 PM, Spencer Parker <[EMAIL PROTECTED]>
wrote:

> Well...it gives me the entire path...I am not running this script from the
> actual directory...I am running it from a secure user directory that only
> has certain access rights.  During the os.path.dirname gives me the entire
> directory path...I just need to last part of it is all. out of
> '/xen/domains2/machinename/disk.img all I need is 'machinename'
>
> On Fri, May 2, 2008 at 10:23 AM, Kent Johnson <[EMAIL PROTECTED]> wrote:
>
> > On Fri, May 2, 2008 at 12:08 PM, Spencer Parker <[EMAIL PROTECTED]>
> > wrote:
> > > I need to use a regular expression to get a couple of items for my
> > python
> > > script.  So far the script is running an 'ls' command to get a few
> > items
> > > that I need
> > >
> > > I run an 'ls -sk /xen/domains2/machinename/disk.img'
> > >
> > > Output
> > >
> > > 2454112 /xen/domains2/machinename/disk.img
> >
> > Look at os.path.getsize(). You don't need to use ls to get this
> > information.
> >
> > > What I need to get is just the size numbers using regular expressions.
> >
> > You could just use str.split() but getsize() is better.
> >
> > > I also need to get the 'machinename'
> > > portion of the path as well to stick into the database.
> >
> > Don't you already know this? Where does the ls command come from?
> > Anyway look at os.path.split() and os.path.dirname().
> >
> > Kent
> >
>
>
>
> --
> Spencer Parker
> ___
>
> "if you can't go to heaven, may you at least die in Ireland."
>
> ___
> ___
> 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] Setting the PC Clock to Correct Time

2008-04-19 Thread jay
Wayne,

Is this a Linux box?  If so, you might consider setting up NTP to sync to an
outside time source.  We do that here and it works quite well, even
accounting for drifting.  If this is a Windows machine, I believe those are
already synced with the PDC, if joined to a Domain, but I might be wrong.

Jason

On Sat, Apr 19, 2008 at 10:45 AM, Wayne Watson <[EMAIL PROTECTED]>
wrote:

> I have a Python program that runs 24/7, but is activated around dusk and
> de-activated from its task around dawn. My clock drifts about 4 sec/day.
> Is there some function that will fetch the correct time from the
> internet and reset the clock? I'd like to reset the clock each time the
> program is activated at dusk.
>
> --
>   Wayne Watson (Watson Adventures, Prop., Nevada City, CA)
>
> (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
>  Obz Site:  39° 15' 7" N, 121° 2' 32" W, 2700 feet
>
>   "Philosophy is questions that may never be
>answered. Religion is answers that may never
>be questioned" -- Anon
>
>Web Page: 
>
> ___
> 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] MySQLdb for Python 2.5? (Debian related) (was: csv.reader: bad argument type)

2008-01-23 Thread jay
I run MySQLdb with Python 2.5.1, but I had to build it manually.  It was not
part of any prebuilt package on my RedHat box.  You should be able to do the
same.

J

On Jan 23, 2008 10:01 AM, <[EMAIL PROTECTED]> wrote:

> I decided to install Python2.5 on the server machine to save me the time
> for low-level debugging >;) but it doesn't find the MySQLdb module...
>
> I searched through aptitude - the only thing I find is MySQLdb for Py2.4
> ... What's happening here?
>
> I have to say that the client PC (on which my script runs fine with 2.5)
> has Ubuntu installed - can it be that the MySQLdb module is behind in
> Debian?
>
> Sorry for going off topic - if you guys don't want that here can move
> the problem to the Debian list - but maybe someone here knows about the
> status of the packages...?
>
> - Paul
> ___
> 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] ssh script

2008-01-23 Thread jay
Have you looked into Paramiko?

http://www.lag.net/paramiko/

Its a port of the ssh2 protocol for python.  It might be easier to do this
using that that subprocess calls.  Paramiko is quite nice, I use it a lot at
work.  Just a suggestion

J

On Jan 23, 2008 3:42 AM, washakie <[EMAIL PROTECTED]> wrote:

>
> Hello, I'm trying to write a script which will allow me to create a
> reverse
> tunnel from a remote machine using SSH -R
>
> I know the reverse tunnel script works on it's own run from the shell, but
> I
> don't want to leave it open always... does anyone have any ideas on how to
> make this work? There seems to be something wrong with the subprocess call
> such that it just hangs on the remote side...
>
> #!/usr/bin/python
>
> import os, time, subprocess
> REMOTE_HOME='../'  #mounted drive to REMOTE_HOME from LOCAL_MACHINE
>
> cmd = 'while true; do ssh -R 8022:localhost:22 [EMAIL PROTECTED] ;
> sleep
> 60; done'
> while 1:
>while os.path.exists(os.path.join(REMOTE_HOME,'mySecretFile'):
>proc=subprocess.call(cmd,shell='True')
>
>if proc: os.kill(proc.pid)
>
>if os.path.exists(os.path.join(REMOTE_HOME,'KillScript'):
>break
>
> --
> View this message in context:
> http://www.nabble.com/ssh-script-tp15038129p15038129.html
> Sent from the Python - tutor mailing list archive at Nabble.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] Reading Input Data

2008-01-15 Thread jay
Python has a cvs module that will make this slightly more elegant

http://docs.python.org/lib/module-csv.html

j

On Jan 15, 2008 2:26 PM, lechtlr <[EMAIL PROTECTED]> wrote:

> I want to read an input file (file.csv) that has two columns. I want to
> read 2nd column and assign variables that are strings and floats. Currently,
> I use the following split() function to read from the input file and create
> a list, and then assign each element to a variable.
>
> I am wondering there is any other easier (and elegant) way of doing this ?
>
> data = []
> for line in open("file.csv"):
>  columns = line.split(',')
>  data.append([columns[1]])
>
> This script returns, say:
> data = [ ['20.0'], ['0.34'], ,[ 'a:0.20, b:0.30, c:0.50'
> ]]
>
> Then, I assign to a set of variables, say:
>
> x1 = float(data[0][0]) ; x2 = float(data[1][0]);.;xn =
> data[-1][0]
>
>
> Thanks,
> Lex
>
>
>
>
>
>
> --
> Never miss a thing. Make Yahoo your 
> homepage.
>
> ___
> 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 a way to get my own ip address

2008-01-02 Thread jay
Well that is what I normally use, but I always have my hostname setup
properly.  In your case, that socket call won't work.  You could try this
link I found on google

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/439094

jay

On Jan 2, 2008 9:00 AM, shawn bright <[EMAIL PROTECTED]> wrote:

> It returns this
> ('hostname', [], ['127.0.1.1'])
> i am running this on a linux system
> thanks
>
>
> On Jan 2, 2008 8:50 AM, jay < [EMAIL PROTECTED]> wrote:
>
> > Well that will return the reverse lookup of the current hostname
> > assigned to your system.  Is this a Windows or Linux/Unix system?  What does
> > this return?
> >
> > print socket.gethostname()
> > print socket.gethostbyaddr(socket.gethostname ())
> >
> > j
> >
> >
> > On Jan 2, 2008 8:45 AM, shawn bright <[EMAIL PROTECTED] > wrote:
> >
> > > Thanks, Jay,
> > > in IDLE, this gave me 127.0.0.1
> > > is there a way to get my assigned ip instead of the localhost one?
> > > thanks
> > >
> > >
> > > On Jan 2, 2008 8:31 AM, jay < [EMAIL PROTECTED]> wrote:
> > >
> > > > You could perhaps use this method
> > > >
> > > > import socket
> > > > myIP = socket.gethostbyaddr(socket.gethostname())[2]
> > > >
> > > > Jay
> > > >
> > > > On Jan 2, 2008 8:25 AM, shawn bright < [EMAIL PROTECTED]> wrote:
> > > >
> > > > > Greetings,
> > > > >
> > > > > i am looking for an easy way to get my own ip address as a string
> > > > > from python.
> > > > > I am using Ubuntu Linux if that makes any difference.
> > > > > thanks !
> > > > >
> > > > > shawn
> > > > >
> > > > > ___
> > > > > 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
> >
> >
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] need a way to get my own ip address

2008-01-02 Thread jay
Well that will return the reverse lookup of the current hostname assigned to
your system.  Is this a Windows or Linux/Unix system?  What does this
return?

print socket.gethostname()
print socket.gethostbyaddr(socket.gethostname())

j

On Jan 2, 2008 8:45 AM, shawn bright <[EMAIL PROTECTED]> wrote:

> Thanks, Jay,
> in IDLE, this gave me 127.0.0.1
> is there a way to get my assigned ip instead of the localhost one?
> thanks
>
>
> On Jan 2, 2008 8:31 AM, jay < [EMAIL PROTECTED]> wrote:
>
> > You could perhaps use this method
> >
> > import socket
> > myIP = socket.gethostbyaddr(socket.gethostname())[2]
> >
> > Jay
> >
> > On Jan 2, 2008 8:25 AM, shawn bright < [EMAIL PROTECTED]> wrote:
> >
> > > Greetings,
> > >
> > > i am looking for an easy way to get my own ip address as a string from
> > > python.
> > > I am using Ubuntu Linux if that makes any difference.
> > > thanks !
> > >
> > > shawn
> > >
> > > ___
> > > 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] need a way to get my own ip address

2008-01-02 Thread jay
You could perhaps use this method

import socket
myIP = socket.gethostbyaddr(socket.gethostname())[2]

Jay

On Jan 2, 2008 8:25 AM, shawn bright <[EMAIL PROTECTED]> wrote:

> Greetings,
>
> i am looking for an easy way to get my own ip address as a string from
> python.
> I am using Ubuntu Linux if that makes any difference.
> thanks !
>
> shawn
>
> ___
> 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] Q2: logging not working as expected

2007-11-16 Thread jay
Dave,

Fix your typo here

> [loggers]
> keys=root,hdk1,hkd2

Should be hkd1 I believe, otherwise the config file is rejected by the
logging module.

> args=(('localhost', handlers.SYSLOG_UDP_PORT), 
> handlers.SysLogHandler.LOG_USER)

LOG_USER is not a defined priority by default in syslog, unless it is
something you have custom defined.  I would suggest using one of the
LOCAL[1-6] levels instead.


> logging.config.fileConfig("logging.conf")
> logger = logging.getLogger('hkd1')
> logger.info('Test Messages')

Finally, call using the qualified name 'hkd1'.


It works for me after that...

Although I agree with others, simplification does wonders for debugging.

Jay


On Nov 16, 2007 3:09 PM, dave selby <[EMAIL PROTECTED]> wrote:
> I am trying to use the python logging module. At first glance it looks
> pretty complicated but having Ggooled a lot I have come up with a
> trial script of  ...
>
> logging.config.fileConfig("logging.conf")
> logger = logging.getLogger()
> logger.critical("Test Message")
>
> Where 'loggin.conf' contains ...
>
> [loggers]
> keys=root,hdk1,hkd2
>
> [handlers]
> keys=SysLog,hand02
>
> [formatters]
> keys=SysLog
>
> [logger_root]
> level=NOTSET
> handlers=SysLog
>
> [logger_hkd1]
> level=DEBUG
> propagate=1
> qualname=hkd1
> handlers=SysLog
> channel=hkd1
> parent=(root)
>
> [logger_hkd2]
> level=DEBUG
> propagate=1
> qualname=hkd2
> handlers=hand02
> channel=hkd2
> parent=(root)
>
> [handler_hand02]
> class=FileHandler
> level=DEBUG
> formatter=SysLog
> args=('python.log', 'w')
>
> [handler_SysLog]
> class=handlers.SysLogHandler
> level=DEBUG
> formatter=SysLog
> args=(('localhost', handlers.SYSLOG_UDP_PORT), 
> handlers.SysLogHandler.LOG_USER)
>
> [formatter_SysLog]
> format=%(filename)s[%(process)d]: %(levelname)s: %(message)s
>
> I was trying to get logging to report to Syslog, that failed so I
> changed it to write to a file 'python.log' .  When I execute my test
> script 'python.log' appears but contains no messages and no error
> messages are generated.
>
> Anybody any ideas as to what I am doing wrong ?
>
> Cheers
>
> Dave
>
> --
>
> Please avoid sending me Word or PowerPoint attachments.
> See http://www.gnu.org/philosophy/no-word-attachments.html
> ___
> 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] New Introductory Book

2007-11-06 Thread jay
I agree as well.  Its not like there is a flood of these books coming
out, or emails slamming the list announcing them.

Jay

On Nov 6, 2007 1:38 PM, Kent Johnson <[EMAIL PROTECTED]> wrote:
> Rikard Bosnjakovic wrote:
> > On 06/11/2007, Michael H. Goldwasser <[EMAIL PROTECTED]> wrote:
> >
> >>We are pleased to announce the release of a new Python book.
> >
> > [...yadayada...]
> >
> > I thought this list was supposed to be clean from commercial advertisements.
>
> I don't think there is a specific rule about that. I'm happy to have
> on-topic announcements which I think this is. IIRC I announced the new
> edition of Learning Python and Wesley Chun announced the new edition of
> his book, Core Python.
>
> Kent
> ___
> 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] Turning multiple Popen calls into a function

2007-11-01 Thread jay
Eric and Eric :-)

Thanks both for the suggestions!  I learned from each!
I believe the small function will work for me.  Its simple since I don't
have to track each pipe I open with a variable.  I had no idea I could do
that nifty if/then for the stdin, that makes it so easy. :-)

Thanks again!

Jay

On 11/1/07, Eric Brunson <[EMAIL PROTECTED]> wrote:
>
> jay wrote:
> > Hello,
> >
> > If I have multiple Popen calls I need to make, how can I turn these
> > into a function?
>
> Since you're only interested in the output of the last command on the
> pipeline, I don't see a reason to keep track of them all.  I'd do
> something like this:
>
> def pipeline( *commandlist ):
> last = None
> for command in commandlist:
> last = Popen( command,
>   stdin=last.stdout if last else None,
>   stdout=PIPE )
>
> return last.communicate()[0]
>
> print pipeline( ("ls", "-la", "/etc"),
> ("grep", "hosts"),
> ("awk", "{print $1}") )
>
> returns:
> lrwxrwxrwx
>
>
>
> Hope that helps,
> e.
>
> > from subprocess import Popen, PIPE
> >
> > p1 = Popen(['ls', '-l', '-a', '/etc'],stdout=PIPE)
> > p2 = Popen(['grep', 'hosts'], stdin=p1.stdout, stdout=PIPE)
> > p3 = Popen(['awk', '{print $1}'], stdin=p2.stdout, stdout=PIPE)
> > output = p3.communicate()[0]
> >
> > p1 = Popen(['ps', '-ef'], stdout=PIPE)
> > p2 = Popen(['grep', '-v', '2348'], stdin=p1.stdout, stdout=PIPE)
> > output = p2.communicate()[0]
> >
> > I would be sending an arbitrary number of PIPES with each function call.
> >
> > I'm a little stumped as to how to handle the variables.  If I have an
> > arbitrary number of PIPES, how do I declare my variables (p1, p2, p3,
> > etc...) ahead of time in the function??
> >
> > Thanks for any suggestions!
> >
> > Jay
> > 
> >
> > ___
> > 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] Turning multiple Popen calls into a function

2007-11-01 Thread jay
Hello,

If I have multiple Popen calls I need to make, how can I turn these into a
function?

from subprocess import Popen, PIPE

p1 = Popen(['ls', '-l', '-a', '/etc'],stdout=PIPE)
p2 = Popen(['grep', 'hosts'], stdin=p1.stdout, stdout=PIPE)
p3 = Popen(['awk', '{print $1}'], stdin=p2.stdout, stdout=PIPE)
output = p3.communicate()[0]

p1 = Popen(['ps', '-ef'], stdout=PIPE)
p2 = Popen(['grep', '-v', '2348'], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]

I would be sending an arbitrary number of PIPES with each function call.

I'm a little stumped as to how to handle the variables.  If I have an
arbitrary number of PIPES, how do I declare my variables (p1, p2, p3,
etc...) ahead of time in the function??

Thanks for any suggestions!

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


Re: [Tutor] Extending logging module

2007-08-09 Thread jay
Nice!  I will have to test this

On 8/9/07, Kent Johnson <[EMAIL PROTECTED]> wrote:
>
> jay wrote:
> > I have a working solution for this, based largely on what Kent posted.
> > Thought I would post it for others in case your either curious, or need
> > to do this in the future.  There are probably other ways to do this.
> >
> > It works quite nicely, though its a lot of repeated
> > code if you have to define several new levels.
>
> Here is a *completely untested off-the-top-of-my-head* rewrite for
> logging.addLevelName() that does this for you and saves having to repeat
> the function definitions. Maybe this could be used to create the
> standard logging functions too!
>
> def addLevelName(level, levelName):
>  """
>  Associate 'levelName' with 'level'.
>
>  This is used when converting levels to text during message
> formatting.
>  """
>  import logging
>  _acquireLock()
>  try:#unlikely to cause an exception, but you never know...
>  _levelNames[level] = levelName
>  _levelNames[levelName] = level
>
>  lowerName = levelName.lower()
>
>  # define a new Logger function for the new level
>  # this is like existing info, critical, debug...etc
>  def Logger_func(self, msg, *args, **kwargs):
>  if self.manager.disable >= level:
>  return
>  if level >= self.getEffectiveLevel():
>  self._log(level, msg, args, **kwargs)
>
>  # Add the new function to the Logger class
>  setattr(logging.Logger, lowerName, Logger_func)
>
>  # define a new root level logging function
>  # this is like existing info, critical, debug...etc
>  def root_func(msg, *args, **kwargs):
>  if len(root.handlers) == 0:
>  basicConfig()
>  Logger_func(root, (msg,)+args, kwargs)
>
>  # make the root level function known
>  setattr(logging, lowerName, root_func)
>
>  finally:
>  _releaseLock()
>
>
> Kent
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Extending logging module

2007-08-09 Thread jay
I have a working solution for this, based largely on what Kent posted.
Thought I would post it for others in case your either curious, or need to
do this in the future.  There are probably other ways to do this.

To add a new level NOTICE for logging to syslog

# Change the default levels to include NOTICE in
# the proper order of priority
logging.FATAL = logging.CRITICAL = 60
logging.ERROR = 50
logging.WARN = logging.WARNING = 40
logging.NOTICE = 30

# insert the levels with all the redefined values
# anything below NOTICE we don't have to add back in, its
# not getting redefined above with a new value
logging.addLevelName(logging.NOTICE, 'NOTICE')
logging.addLevelName(logging.WARNING, 'WARNING')
logging.addLevelName(logging.WARN, 'WARN')
logging.addLevelName(logging.ERROR, 'ERROR')
logging.addLevelName(logging.FATAL, 'FATAL')
logging.addLevelName(logging.CRITICAL, 'CRITICAL')

# define a new logger function for notice
# this is exactly like existing info, critical, debug...etc
def Logger_notice(self, msg, *args, **kwargs):
"""
Log 'msg % args' with severity 'NOTICE'.

To pass exception information, use the keyword argument exc_info
with
a true value, e.g.

logger.notice("Houston, we have a %s", "major disaster", exc_info=1)
"""
if self.manager.disable >= logging.NOTICE:
return
if logging.NOTICE >= self.getEffectiveLevel():
apply(self._log, (logging.NOTICE, msg, args), kwargs)

# make the notice function known in the system Logger class
logging.Logger.notice = Logger_notice

# define a new root level notice function
# this is exactly like existing info, critical, debug...etc
def root_notice(msg, *args, **kwargs):
"""
Log a message with severity 'NOTICE' on the root logger.
"""
if len(root.handlers) == 0:
basicConfig()
apply(root.notice, (msg,)+args, kwargs)

# make the notice root level function known
logging.notice = root_notice

# add NOTICE to the priority map of all the levels
logging.handlers.SysLogHandler.priority_map['NOTICE'] = 'notice'


>From there you can create your new logger and do a myLog.notice('test notice
message').  It works quite nicely, though its a lot of repeated code if you
have to define several new levels.

Thanks for your suggestion Kent.  Will wait and see if I get a different
response from comp.lang.python.

Jay



On 8/9/07, jay <[EMAIL PROTECTED]> wrote:
>
> Kent,
>
> Thanks for the suggestion.  If will look more into your suggestions, and
> also shoot a post over to comp.lang.python.
>
> Jay
>
> On 8/9/07, Kent Johnson <[EMAIL PROTECTED]> wrote:
> >
> > jay wrote:
> > > Hello,
> > >
> > > I've been using the python logging module a lot lately, and I've come
> > > across an instance where I need some new levels.  Specifically, python
> > > does not include ALERT and NOTICE in the default set of logging
> > levels.
> > > I am wondering how trivial it would be to extend the logging module to
> >
> > > include these 2 levels that are standard with syslog?
> > >
> > > My first test was just to use the addLevelName method to add the two
> > new
> > > levels, but syslog ignores them and logs at the next highest priority,
> >
> > > no matter what I use.
> > >
> > > Looking further into the code and as a test, I changed the following
> > to
> > > see if this would even work
> > >
> > > lib/python2.5/logging/__init__.py
> > >   -> class Logger
> > >   -> add new notice and alert root level functions
> > >   -> new _levelNames for notice and alert
> > >   -> new default level names for notice and alert
> >
> > You could do all this by patching the logging module at runtime:
> > import logging
> > logging.ALERT = 60
> > logging.addLevelName(logging.ALERT, 'ALERT')
> >
> > def Logger_alert(self, msg, *args, **kwargs):
> >   ...
> >
> > logging.Logger.alert = Logger_alert
> >
> > def alert(msg, *args, **kwargs):
> >...
> >
> > logging.alert = alert
> >
> > It's a little ugly but since you are just extending the module with new
> > constants and functions it seems pretty safe and clean to me. It would
> > be cool if addLevelName() did all this patching for you, it wouldn't be
> > hard to do...maybe you want to

Re: [Tutor] Extending logging module

2007-08-09 Thread jay
Kent,

Thanks for the suggestion.  If will look more into your suggestions, and
also shoot a post over to comp.lang.python.

Jay

On 8/9/07, Kent Johnson <[EMAIL PROTECTED]> wrote:
>
> jay wrote:
> > Hello,
> >
> > I've been using the python logging module a lot lately, and I've come
> > across an instance where I need some new levels.  Specifically, python
> > does not include ALERT and NOTICE in the default set of logging levels.
> > I am wondering how trivial it would be to extend the logging module to
> > include these 2 levels that are standard with syslog?
> >
> > My first test was just to use the addLevelName method to add the two new
> > levels, but syslog ignores them and logs at the next highest priority,
> > no matter what I use.
> >
> > Looking further into the code and as a test, I changed the following to
> > see if this would even work
> >
> > lib/python2.5/logging/__init__.py
> >   -> class Logger
> >   -> add new notice and alert root level functions
> >   -> new _levelNames for notice and alert
> >   -> new default level names for notice and alert
>
> You could do all this by patching the logging module at runtime:
> import logging
> logging.ALERT = 60
> logging.addLevelName(logging.ALERT, 'ALERT')
>
> def Logger_alert(self, msg, *args, **kwargs):
>   ...
>
> logging.Logger.alert = Logger_alert
>
> def alert(msg, *args, **kwargs):
>...
>
> logging.alert = alert
>
> It's a little ugly but since you are just extending the module with new
> constants and functions it seems pretty safe and clean to me. It would
> be cool if addLevelName() did all this patching for you, it wouldn't be
> hard to do...maybe you want to propose a patch...
>
> > lib/python2.5/logging/handlers.py
> >   -> class SysLogHandler priority_map was changed to include notice and
> > alert
>
> You can do this by subclassing SysLogHandler:
>
> class FixedSysLogHandler(SysLogHandler):
>priority_map = { ... }
>
> then configure logging to use FixedSysLogHandler instead of SysLogHandler.
>
>
> You might want to post about this on comp.lang.python , I think the
> author of the logging module will see it there.
>
> Kent
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Extending logging module

2007-08-09 Thread jay
Hello,

I've been using the python logging module a lot lately, and I've come across
an instance where I need some new levels.  Specifically, python does not
include ALERT and NOTICE in the default set of logging levels.  I am
wondering how trivial it would be to extend the logging module to include
these 2 levels that are standard with syslog?

My first test was just to use the addLevelName method to add the two new
levels, but syslog ignores them and logs at the next highest priority, no
matter what I use.

Looking further into the code and as a test, I changed the following to see
if this would even work

lib/python2.5/logging/__init__.py
  -> class Logger
  -> add new notice and alert root level functions
  -> new _levelNames for notice and alert
  -> new default level names for notice and alert

lib/python2.5/logging/handlers.py
  -> class SysLogHandler priority_map was changed to include notice and
alert

It actually worked, but this is not the way I would like to handle the
problem.  I would prefer to extend the classes instead.  However, I'm not
too familiar with that, and I had to change things in so many places, I'm
wondering if its even possible?  I don't like changing the standard
libraries, what happens if I have to upgrade python?  My changes get
overwritten.

Can anyone offer some help or suggestions?  Thanks

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


Re: [Tutor] Finding the caller

2007-07-26 Thread jay
Thanks Kent and Andreas

That is exactly what I needed!  Very nice indeed...

jay


On 7/26/07, Kent Johnson <[EMAIL PROTECTED]> wrote:
>
> jay wrote:
> > Hello all,
> >
> > If I import a module, which has a bunch of simple functions in it, is
> > there an easy way to find the direct caller from inside one of those
> > functions?  I'm looking to know which script has imported and thus
> > called the library function.  Thanks!
>
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66062
>
> Kent
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Finding the caller

2007-07-26 Thread jay
Hello all,

If I import a module, which has a bunch of simple functions in it, is there
an easy way to find the direct caller from inside one of those functions?
I'm looking to know which script has imported and thus called the library
function.  Thanks!

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


Re: [Tutor] Logging module

2007-07-25 Thread jay

Thanks for the reply Kent.

I found the problem.  It was rather simple actually. I didn't have remote
logging enabled for syslog.  Even though I was logging to localhost, for
some reason, it wouldn't work until I gave syslogd a -r at startup.  Thanks

jay

On 7/25/07, Kent Johnson <[EMAIL PROTECTED]> wrote:


jay wrote:
> Hello,
>
> I'm trying to setup simple Syslog logging in python using the logging
> module.  I would like to use a config file, but so far haven't been able
> to get the correct configuration.  Actually, I don't get any warnings or
> errors, program runs fine, but nothing is logged anywhere.  I have my
> syslog LOCAL6 setup to go to /var/log/scripts.log, and that worked fine
> during testing of the syslog module.  But logging gives me more
> flexibility, I'd rather use that.
>
> Anyone with some experience using this module?  The documentation, at
> least to me, is a bit confusing, and I haven't found a good example on
> the web yet.

I haven't used logging config files, but I don't see anything obviously
wrong here. A couple of ideas to try:
- make sure logging.conf can be found by
   print os.path.exists('logging.conf')
- turn on console logging in the config file and see if that works
- try to configure the syslog handler in code instead of in a file, then
translate the successful configuration to a file.

Kent

>
> ---main.py---
> #!/usr/bin/env python
>
> import logging, logging.config
>
> logging.config.fileConfig('logging.conf')
>
> log = logging.getLogger()
> log.info('here we go, testing logger')
> --- end main.py ---
>
> --- logging.conf ---
> [formatters]
> keys: detailed,simple
>
> [handlers]
> keys: console,syslog
>
> [loggers]
> keys: root
>
> [formatter_simple]
> format: %(name)s:%(levelname)s:  %(message)s
>
> [formatter_detailed]
> format: %(name)s:%(levelname)s %(module)s:%(lineno)d:  %(message)s
>
> [handler_console]
> class: StreamHandler
> args: []
> formatter: simple
>
> [handler_syslog]
> class: handlers.SysLogHandler
> args: [('localhost', handlers.SYSLOG_UDP_PORT),
> handlers.SysLogHandler.LOG_LOCAL6 ]
> formatter: detailed
>
> [logger_root]
> level: INFO
> handlers: syslog
>
>  end logging.conf ---
>
> Thanks for any help!
>
> jay
>
>
> 
>
> ___
> 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] Logging module

2007-07-24 Thread jay

Hello,

I'm trying to setup simple Syslog logging in python using the logging
module.  I would like to use a config file, but so far haven't been able to
get the correct configuration.  Actually, I don't get any warnings or
errors, program runs fine, but nothing is logged anywhere.  I have my syslog
LOCAL6 setup to go to /var/log/scripts.log, and that worked fine during
testing of the syslog module.  But logging gives me more flexibility, I'd
rather use that.

Anyone with some experience using this module?  The documentation, at least
to me, is a bit confusing, and I haven't found a good example on the web
yet.

---main.py---
#!/usr/bin/env python

import logging, logging.config

logging.config.fileConfig('logging.conf')

log = logging.getLogger()
log.info('here we go, testing logger')
--- end main.py ---

--- logging.conf ---
[formatters]
keys: detailed,simple

[handlers]
keys: console,syslog

[loggers]
keys: root

[formatter_simple]
format: %(name)s:%(levelname)s:  %(message)s

[formatter_detailed]
format: %(name)s:%(levelname)s %(module)s:%(lineno)d:  %(message)s

[handler_console]
class: StreamHandler
args: []
formatter: simple

[handler_syslog]
class: handlers.SysLogHandler
args: [('localhost', handlers.SYSLOG_UDP_PORT),
handlers.SysLogHandler.LOG_LOCAL6 ]
formatter: detailed

[logger_root]
level: INFO
handlers: syslog

 end logging.conf ---

Thanks for any help!

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


Re: [Tutor] Tutor Digest, Vol 38, Issue 10

2007-04-06 Thread Jay Mutter III
>
>
> "Jay Mutter III" <[EMAIL PROTECTED]> wrote
>
>
>> Whether I attempt to just strip the string or attempt to
>>
>> if line.endswith('No.\r'):
>> line = line.rstrip()
>>
>> It doesn't work.
>
> Can you try printing the string repr just before the test.
> Or even the last 6 characters:
>
> print repr(line[-6:])
> if line.endswith('No: \n')
>line = line.strip()
>

Alan using your suggestion with the code aove here is the print out:

jay-mutter-iiis-computer:~/documents/ToBePrinted jlm1$ python test.py
'andal\r'
'  No.\r'
' Dor-\r'
'  14;\r'
'315 ;\r'
'  No.\r'
'utton\r'
'H'

Which appears to me to have 2 lines ending with No. where

  the LF should be removed and the next line would be on the same line

Again thanks for the help/suggestions

> See if that helps narrow down the cause...
>
>> This is an imac running python 2.3.5 under OS-X 10.4.9
>
> Shouldn't make any odds.
>
> Weird,
>
> Alan G.

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


Re: [Tutor] Tutor Digest, Vol 38, Issue 2

2007-04-05 Thread Jay Mutter III
>
>
> Message: 3
> Date: Sun, 1 Apr 2007 16:42:56 +0100
> From: "Alan Gauld" <[EMAIL PROTECTED]>
> Subject: Re: [Tutor] Tutor Digest, Vol 38, Issue 1
> To: tutor@python.org
> Message-ID: <[EMAIL PROTECTED]>
> Content-Type: text/plain; format=flowed; charset="iso-8859-1";
>   reply-type=original
>
>
> "Rikard Bosnjakovic" <[EMAIL PROTECTED]> wrote
>
>>>>> s1 = "some line\n"
>>>>> s2 = "some line"
>>>>> s1.endswith("line"), s2.endswith("line")
>> (False, True)
>>
>> Just skip the if and simply rstrip the string.
>

see below

> Or add \n to the endswith() test string if you really only
> want to strip the newline in those cases
>
> Alan G.
>
>
>
> --
>
> Message: 4
> Date: Sun, 1 Apr 2007 16:46:05 +0100
> From: "Alan Gauld" <[EMAIL PROTECTED]>
> Subject: Re: [Tutor] Tutor Digest, Vol 38, Issue 1
> To: tutor@python.org
> Message-ID: <[EMAIL PROTECTED]>
> Content-Type: text/plain; format=flowed; charset="iso-8859-1";
>   reply-type=original
>
> "Jay Mutter III" <[EMAIL PROTECTED]> wrote
>
>> inp = open('test.txt','r')
>> s = inp.readlines()
>> for line in s:
>> if line.endswith('No.'):
>> line = line.rstrip()
>> print line
>
> BTW,
> You do know that you can shorten that considerably?
> With:
>
> for line in open('test.txt'):
>if line.endswith('No.\n'):
>   line = line.rstrip()
>print line
>

Whether I attempt to just strip the string or attempt to

if line.endswith('No.\r'):
 line = line.rstrip()

It doesn't work.
Note - I tried \n, \r and \n\r although text wrangler claims that it  
does have unix line endings
When I used tr to do a few things \n or \r worked fine
I tried sed and it didn't work but from the command line in sed using  
ctrl-v and ctrl-j to insert the  line feed it worked
although i then could not figure out how to do the same in a script.
It is as if the python interpreter doesn't recognize the escaped n  
(or r) as a line feed.
This is an imac running python 2.3.5 under OS-X 10.4.9

Thanks again

> -- 
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
>
>
>
> --
>
> Message: 5
> Date: 01 Apr 2007 12:17:00 -0400
> From: "Greg Perry" <[EMAIL PROTECTED]>
> Subject: [Tutor] Communication between classes
> To: 
> Message-ID: <[EMAIL PROTECTED]>
>
> Hi again,
>
> I am still in the process of learning OOP concepts and reasons why  
> classes should be used instead of functions etc.
>
> One thing that is not apparent to me is the best way for classes to  
> communicate with each other.  For example, I have created an Args  
> class that sets a variety of internal variables (__filename,  
> __outputdir etc) by parsing the argv array from th command line.   
> What would be the preferred mechanism for returning or passing  
> along those variables to another class?  Maybe by a function method  
> that returns all of those variables?
>
>
>
>
>
> --
>
> Message: 6
> Date: Sun, 01 Apr 2007 20:46:21 +0200
> From: Andrei <[EMAIL PROTECTED]>
> Subject: Re: [Tutor] Communication between classes
> To: tutor@python.org
> Message-ID: <[EMAIL PROTECTED]>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
> Hi Greg,
>
> Greg Perry wrote:
>> I am still in the process of learning OOP concepts and
>> reasons why classes should be used instead of functions etc.
>>
>> One thing that is not apparent to me is the best way for
>> classes to communicate with each other.  For example,
>
> Good question. Unfortunately there's no general rule that you can  
> apply
> and end up with an undisputably perfect solution.
>
> Classes should communicate on a need-to-know basis. Take for example a
> RSS feed reader application. You may have a class representing a feed
> and a class representing a post. The feed will know what posts it
> contains, but the post probably won't know what feed it comes from.  
> The
> interface would display a list of feeds (without knowing their
> contents), a list of posts within a feed (this needs to know both feed
> and feed contents) and the contents of a single post (knows only about
> an individual post).
>
>> I have created an Args class that sets a variety of internal
>> variables (__filename, __outputd

Re: [Tutor] Tutor Digest, Vol 38, Issue 1

2007-04-01 Thread Jay Mutter III
Alan thanks for the response;


> Message: 8
> Date: Sun, 1 Apr 2007 08:54:02 +0100
> From: "Alan Gauld" <[EMAIL PROTECTED]>
> Subject: Re: [Tutor] Another parsing question
> To: tutor@python.org
> Message-ID: <[EMAIL PROTECTED]>
> Content-Type: text/plain; format=flowed; charset="iso-8859-1";
>   reply-type=original
>
>
> "Jay Mutter III" <[EMAIL PROTECTED]> wrote
>
>> for line in s:
>> jay = patno.findall(line)
>> jay2 = "".join(jay[0])
>> print jay2
>>
>> and it prints fine up until line 111 which is a line that had
>> previously returned [ ] since a number didn't exist on that line and
>> then exits with
>
>> IndexError: list index out of range
>
> Either try/catch the exception or add an
> if not line: continue  # or return a default string
>
>> And as long as i am writing, how can I delete a return at the end of
>> a line if the line ends in a certain pattern?
>>
>> For instance, if line ends with the abbreviation  No.
>
> if line.endswith(string): line = line.rstrip()
>

For some reason this never works for me;
i am using an intel imac with OS X 10.4.9 which has python 2.3.5

inp = open('test.txt','r')
s = inp.readlines()
for line in s:
 if line.endswith('No.'):
 line = line.rstrip()
 print line
and it never ever removes the line feed.  (These are unix \r  
according to Text wrangler)
I am beginning to think that it is a problem with readlines.

But then i thought well why not

inp = open('test.txt','r')
s = inp.readlines()
for line in s:
 if line.endswith('No.'):
 line += s.next()
 print line,

however that doesn't work either which leads me to believe that it is  
me and my interpretation of the above.

Thanks

Jay



>> I want to join the current line with next line.
>> Are lists immutable or can they be changed?
>
> lists can be changed, tuples cannot.
>
> HTH,
>
> -- 
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
>
>
>
>
> --
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
> End of Tutor Digest, Vol 38, Issue 1
> 

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


Re: [Tutor] Another parsing question

2007-03-31 Thread Jay Mutter III
Kent;
Again thanks for the help.
i am not sure if this is what you menat but i put

for line in s:
 jay = patno.findall(line)
 jay2 = "".join(jay[0])
 print jay2

and it prints fine up until line 111 which is a line that had  
previously returned [ ] since a number didn't exist on that line and   
then exits with

Traceback (most recent call last):
   File "patentno2.py", line 12, in ?
 jay2 = "".join(jay[0])
IndexError: list index out of range


And as long as i am writing, how can I delete a return at the end of  
a line if the line ends in a certain pattern?

For instance, if line ends with the abbreviation  No.
I want to join the current line with next line.
Are lists immutable or can they be changed?

Thanks again

jay

On Mar 31, 2007, at 2:27 PM, Kent Johnson wrote:

> Jay Mutter III wrote:
>> I have the following that I am using to extract "numbers' from a file
>> ...
>> which yields the following
>> [('1', '337', '912')]
> > ...
>> So what do i have above ? A list of tuples?
>
> Yes, each line is a list containing one tuple containing three  
> string values.
>
>> How do I  send the output to a file?
>
> When you print, the values are automatically converted to strings  
> by calling str() on them. When you use p2.write(), this conversion  
> is not automatic, you have to do it yourself via
>   p2.write(str(jay))
>
> You can also tell the print statement to output to a file like this:
>   print >>p2, jay
>
>> Is there a way to get the output as
>> 1337912  instead of   [('1', '337', '912')]  ?
>
> In [4]: jay=[('1', '337', '912')]
>
> jay[0] is the tuple alone:
> In [6]: jay[0]
> Out[6]: ('1', '337', '912')
>
> Join the elements together using an empty string as the separator:
> In [5]: ''.join(jay[0])
> Out[5]: '1337912'
> In [7]:
>
> Kent

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


Re: [Tutor] Another parsing question

2007-03-31 Thread Jay Mutter III
Ok after a minute of thought I did solve my second question by simply  
changing my RE to

(r'(\d{1}[\s,.]+\d{3}[\s,.]+\d{3})')

but still haven't gotten he first one.


On Mar 31, 2007, at 1:39 PM, Jay Mutter III wrote:

> I have the following that I am using to extract "numbers' from a file
>
>
> prompt1 = raw_input('What is the file from which you would like a  
> list of patent numbers?  ')
> p1 = open(prompt1,'rU')
> s = p1.readlines()
> prompt2 = raw_input('What is the name of the file to which you  
> would like to save the list of patent numbers?  ')
> p2 = open(prompt2,'aU')
> patno = re.compile(r'(\d{1})[\s,.]+(\d{3})[\s,.]+(\d{3})')
> for line in s:
> jay = patno.findall(line)
> print jay
>
> which yields the following
>
> [('1', '337', '912')]
> [('1', '354', '756')]
> [('1', '360', '297')]
> [('1', '328', '232')]
> [('1', '330', '123')]
> [('1', '362', '944')]
> [('1', '350', '461')]
> [('1', '355', '991')]
> [('1', '349', '385')]
> [('1', '350', '521')]
> [('1', '336', '542')]
> [('1', '354', '922')]
> [('1', '338', '268')]
> [('1', '353', '682')]
> [('1', '343', '241')]
> [('1', '359', '852')]
> [('1', '342', '483')]
> [('1', '347', '068')]
> [('1', '331', '450')]
>
> if i try to write to a file instead of print to the screen using
> p2.write(jay)
> i get the message
>
> Traceback (most recent call last):
>   File "patentno.py", line 12, in ?
> p2.write(jay)
> TypeError: argument 1 must be string or read-only character buffer,  
> not list
>
> I f I try writelines i get
>
> Traceback (most recent call last):
>   File "patentno.py", line 12, in ?
> p2.writelines(jay)
> TypeError: writelines() argument must be a sequence of strings
> jay-mutter-iiis-computer:~/documents/programming/python/patents jlm1$
>
>
> So what do i have above ? A list of tuples?
>
> How do I  send the output to a file?
> Is there a way to get the output as
>
> 1337912  instead of   [('1', '337', '912')]  ?
>
> And as always thanks in advance for the help.
>
> jay Mutter
>

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


[Tutor] Another parsing question

2007-03-31 Thread Jay Mutter III
I have the following that I am using to extract "numbers' from a file


prompt1 = raw_input('What is the file from which you would like a  
list of patent numbers?  ')
p1 = open(prompt1,'rU')
s = p1.readlines()
prompt2 = raw_input('What is the name of the file to which you would  
like to save the list of patent numbers?  ')
p2 = open(prompt2,'aU')
patno = re.compile(r'(\d{1})[\s,.]+(\d{3})[\s,.]+(\d{3})')
for line in s:
 jay = patno.findall(line)
 print jay

which yields the following

[('1', '337', '912')]
[('1', '354', '756')]
[('1', '360', '297')]
[('1', '328', '232')]
[('1', '330', '123')]
[('1', '362', '944')]
[('1', '350', '461')]
[('1', '355', '991')]
[('1', '349', '385')]
[('1', '350', '521')]
[('1', '336', '542')]
[('1', '354', '922')]
[('1', '338', '268')]
[('1', '353', '682')]
[('1', '343', '241')]
[('1', '359', '852')]
[('1', '342', '483')]
[('1', '347', '068')]
[('1', '331', '450')]

if i try to write to a file instead of print to the screen using
p2.write(jay)
i get the message

Traceback (most recent call last):
   File "patentno.py", line 12, in ?
 p2.write(jay)
TypeError: argument 1 must be string or read-only character buffer,  
not list

I f I try writelines i get

Traceback (most recent call last):
   File "patentno.py", line 12, in ?
 p2.writelines(jay)
TypeError: writelines() argument must be a sequence of strings
jay-mutter-iiis-computer:~/documents/programming/python/patents jlm1$


So what do i have above ? A list of tuples?

How do I  send the output to a file?
Is there a way to get the output as

1337912  instead of   [('1', '337', '912')]  ?

And as always thanks in advance for the help.

jay Mutter

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


Re: [Tutor] Tutor Digest, Vol 37, Issue 63

2007-03-25 Thread Jay Mutter III
>
> Message: 1
> Date: Sat, 24 Mar 2007 16:41:22 -0700 (PDT)
> From: Jaggo <[EMAIL PROTECTED]>
> Subject: Re: [Tutor] Tutor Digest, Vol 37, Issue 62
> To: tutor@python.org
> Message-ID: <[EMAIL PROTECTED]>
> Content-Type: text/plain; charset="iso-8859-1"
>
> Message: 2
> Date: Sat, 24 Mar 2007 19:25:10 -0400
> From: Jay Mutter III
> Subject: [Tutor] parsing text
> [...]
> 1.) when i do readlines and create a list and then print the list it
> adds a blank line between every line of text
> [...]
> ideas?
>
> Thanks again
>
> jay
> Well,
> regarding your first question:
> "print string" automatically breaks a line at the end of string.  
> Use "print string," instead [note that trailin' , .]
>

yes, thank you for that


> [I'm not sure about your n. 2, that's why no answer is included.
>
>
> -
> TV dinner still cooling?
> Check out "Tonight's Picks" on Yahoo! TV.
> -- next part --
> An HTML attachment was scrubbed...
> URL: http://mail.python.org/pipermail/tutor/attachments/ 
> 20070324/2d731ac8/attachment-0001.htm
>
> --
>
> Message: 2
> Date: Sun, 25 Mar 2007 00:00:29 -
> From: "Alan Gauld" <[EMAIL PROTECTED]>
> Subject: Re: [Tutor] parsing text
> To: tutor@python.org
> Message-ID: <[EMAIL PROTECTED]>
> Content-Type: text/plain; format=flowed; charset="iso-8859-1";
>   reply-type=original
>
> "Jay Mutter III" <[EMAIL PROTECTED]> wrote
>
>> i have the following text:
>>
>> Barnett, John B., assignor of one-half to R. N. Tutt, Kansas City,
>> Mo.Automatic display-sign.No. 1,330 411-Apr. 13 ; v. 273 ;
>> p.
>> 193.
>> Barnett,  John  II..  Tettenhall,  England. Seat  of
>> motorcars.No. 1.353,708; Sept. 21 ; v. 278; p. 487. Barnett,
>> Otto
>> R.(See Scott, John M., assignor.)
>>
>> 1.) when i do readlines and create a list and then print the list it
>> adds a blank line between every line of text
>
> I suspect that's because you are reading a newline character
> from the file and print adds a newline of its own. You need to
> use rstrip() to take out the newline from the file.
>
>> 2.)in the second line after p.487 there is the beginning of a new
>> line of data only it isn't on a newline.
>
> I'm not quite sure what you mean here.
> It would be helpful if you can show us the problematic output
> as well as the input. Also to send us the actual code fragments
> that are causing the damage.

Yes after i received the reply i realized that i was not very clear.
i have a text file of inventors which should have one inventor on  
each line in alphabetical order but of course the lines
do not break at the end of 'p. xxx.'  (where p.xxx is the relevant  
page number)

I read the data in as a string figuring that I could then replace p.  
xxx with a carriage return, somehow write the data out to a text file
and the problem would be solved. Not quite so simple given my limited  
skill set.
The following is what I put in (interactively) and what I got out.

 >>> ss = open('inp.txt')
 >>> s = ss.read()
 >>> s.replace('p. ','\n')
'Barnett, John B., assignor of one-half to R. N. Tutt, Kansas City,  
Mo. Automatic display-sign.\xc2\xa0 \xc2\xa0 No. 1,330 411-Apr. 13 ;  
v. 273 ;\xc2\xa0\n\n193. Barnett,\xc2\xa0 John\xc2\xa0 II..\xc2\xa0  
Tettenhall,\xc2\xa0 England. \xc2\xa0 \xc2\xa0 Seat\xc2\xa0 of 
\nmotorcars.\xc2\xa0 \xc2\xa0 No. 1.353,708; Sept. 21 ; v. 278;  
\n487. Barnett,\xc2\xa0\nOtto R.\xc2\xa0 \xc2\xa0 (See Scott, John  
M., assignor.)'
 >>>

I though about treating it as a list of lines, stripping carriage  
returns on the basis of some criteria but i have never gotten rstrip  
to work



>
>> i tried string.replace(s,'p.','\n') in an attempt to put a CR in but
>> it just put the characters\n in the string.
>
> Dont use the string module functions. Use the string methods,
> so it becomes:
>
> s.replace('p.', '\n')
>
> However that doesn't explain why you are getting the literal
> characters! Can you send us the actual code you are using?
> And the output showing the error?
>
> HTH,
>
> Alan G.
>
>
>
>
> --
>
> Message: 3
> Date: Sat, 24 Mar 2007 19:32:36 -0500
> From: "Cecilia Alm" <[EMAIL PROTECTED]>
> Subject: [Tutor] No need to seed random?
> To: tutor@python.org
> Message-ID:
>   <[EMAIL PROTECTED]>
> Content-Type: tex

[Tutor] parsing text

2007-03-24 Thread Jay Mutter III
Kent thanks for this as I was clearly confused with regards to string  
and list of strings.
I am, however, still having difficulty with how to solve a problem  
involving a related issue.


i have the following text:

Barnett, John B., assignor of one-half to R. N. Tutt, Kansas City,  
Mo.Automatic display-sign.No. 1,330 411-Apr. 13 ; v. 273 ; p.  
193.
Barnett,  John  II..  Tettenhall,  England. Seat  of   
motorcars.No. 1.353,708; Sept. 21 ; v. 278; p. 487. Barnett, Otto  
R.(See Scott, John M., assignor.)

Barnett. Otto R. (See Sponenburg, Hiram H., assignor)
Barnett, William A., Lincoln. Nebr.Attachment for garment- 
turning   machines. No.   1,342,937;   June   8 ?   v 270 ; p. 313."
Barnhart, Clarence D., Brooklyn, assignor to W. S. Rockwell Company,  
New York. N. Y.Conveyer for furnaces No. 1.333.371 ; Mar. 9 ; v.  
272 ; p. 278.
Barnhart, Clarence v., Waynesboro, Pa., assignor to J. K. Hoffman and  
W. M. Raeclitel.  Hagerstowu, Md. Seed-planter.No. 1,357.43S:  
Nov. 2; v. 280: p. 45.

Barnhart, John E.(See Haves, J. P.. and Barnhart )
Barnhart,-Mollie E.(See Freeman. Alpheus J., assignor) Barnhill,  
E. B., and J. Stone, Indianapolis, Ind.Auto-tire 477513


1.) when i do readlines and create a list and then print the list it  
adds a blank line between every line of text
2.)in the second line after p.487 there is the beginning of a new  
line of data only it isn't on a newline.
i tried string.replace(s,'p.','\n') in an attempt to put a CR in but  
it just put the characters\n in the string.


ideas?

Thanks again

jay



Jay Mutter III wrote:
> Thanks for the response
> Actually the number of lines this returns is the same number of lines
> given when i put it in a text editor (TextWrangler).
> Luke had mentioned the same thing earlier but when I do change  
read to

> readlines  i get the following
>
>
> Traceback (most recent call last):
>   File "extract_companies.py", line 17, in ?
> count = len(text.splitlines())
> AttributeError: 'list' object has no attribute 'splitlines'

I think maybe you are confused about the difference between "all the
text of a file in a single string" and "all the lines of a file in a
list of strings."

When you open() a file and read() the contents, you get all the text of
a file in a single string. len() will give you the length of the string
(the total file size) and iterating over the string gives you one
character at at time.

Here is an example of a string:
In [1]: s = 'This is text'
In [2]: len(s)
Out[2]: 12
In [3]: for i in s:
...: print i
...:
...:
T
h
i
s

i
s

t
e
x
t

On the other hand, if you open() the file and then readlines() from the
file, the result is a list of strings, each of with is the contents of
one line of the file, up to and including the newline. len() of the list
is the number of lines in the list, and iterating the list gives each
line in turn.

Here is an example of a list of strings:
In [4]: l = [ 'line1', 'line2' ]
In [5]: len(l)
Out[5]: 2
In [6]: for i in l:
...: print i
...:
...:
line1
line2

Notice that s and l are *used* exactly the same way with len() and for,
but the results are different.

As a further wrinkle, there are two easy ways to get all the lines in a
file and they give slightly different results.

open(...).readlines() returns a list of lines in the file and each line
includes the final newline if it was in the file. (The last line will
not include a newline if the last line of the file did not.)

open(...).read().splitlines() also gives a list of lines in the file,
but the newlines are not included.

HTH,
Kent



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


[Tutor] Parsing text file with Python

2007-03-23 Thread Jay Mutter III
Script i have to date is below and
Thanks to your help i can see some daylight  but I still have a few  
questions

1.)  Are there better ways to write this?
2.) As it writes out the one group to the new file for companies it  
is as if it leaves blank lines behind for if I don't have the elif len 
(line) . 1 the
   inventor's file has blank lines in it.
3.) I reopened the inventor's file to get a count of lines but is  
there a better way to do this?

Thanks



in_filename = raw_input('What is the COMPLETE name of the file you  
would like to process?')
in_file = open(in_filename, 'rU')
text = in_file.readlines()
count = len(text)
print "There are ", count, 'lines to process in this file'
out_filename1 = raw_input('What is the COMPLETE name of the file in  
which you would like to save Companies?')
companies = open(out_filename1, 'aU')
out_filename2 = raw_input('What is the COMPLETE name of the file in  
which you would like to save Inventors?')
patentdata = open(out_filename2, 'aU')
for line in text:
 if line.endswith(')\n'):
 companies.write(line)
 elif line.endswith(') \n'):
 companies.write(line)
  elif len(line) > 1:
 patentdata.write(line)
in_file.close()
companies.close()
patentdata.close()
in_filename2 = raw_input('What was the name of the inventor\'s  
file ?')
in_file2 = open(in_filename2, 'rU')
text2 = in_file2.readlines()
count = len(text2)
print "There are - well until we clean up more - approximately ",  
count, 'inventor\s in this file'
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why is it...

2007-03-23 Thread Jay Mutter III

Got it - it needs the blank line to signal that code block has ended.
Thanks

On Mar 22, 2007, at 3:05 PM, Jason Massey wrote:


In the interpreter this doesn't work:

>>> f = open(r"c:\python24\image.dat")
>>> line = f.readline()
>>> while line:
... line = f.readline()
... f.close()
Traceback (  File "", line 3
f.close()
^
SyntaxError: invalid syntax

But this does:

>>> f = open(r"c:\python24\image.dat")
>>> line = f.readline()
>>> while line:
... line = f.readline()
...
>>> f.close()
>>>

Note the differing placement of the f.close() statement, it's not  
part of the while.



On 3/22/07, Kent Johnson <[EMAIL PROTECTED]> wrote:
Jay Mutter III wrote:
> Why is it that when I run the following interactively
>
> f = open('Patents-1920.txt')
> line = f.readline()
> while line:
>  print line,
>  line = f.readline()
> f.close()
>
> I get an error message
>
> File "", line 4
>  f.close()
>  ^
> SyntaxError: invalid syntax
>
> but if i run it in a script there is no error?

Can you copy/paste the actual console transcript?

BTW a better way to write this is
f = open(...)
for line in f:
 print line,
f.close()

Kent

>
> Thanks
>
> Jay
>
> ___
> 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] Another string question

2007-03-23 Thread Jay Mutter III

Andre;

Thanks again for the assistance.

I have corrected the splitlines error and it works ( well that part  
of anyway) correctly now.


On Mar 23, 2007, at 5:30 AM, Andre Engels wrote:


2007/3/22, Jay Mutter III <[EMAIL PROTECTED]>:
I wanted the following to check each line and if it ends in a right
parentheses then write the entire line to one file and if not then
write the line to anther.
It wrote all of the ) to one file and the rest of the line (ie minus
the ) to the other file.

The line:
 print "There are ", count, 'lines to process in this file'
should give you a hint - don't you think this number was rather high?

The problem is that if you do "for line in text" with text being a  
string, it will not loop over the _lines_  in the string, but over  
the _characters_ in the string.


The easiest solution would be to replace
 text = in_file.read()
by
 text = in_file.readlines()

in_filename = raw_input('What is the COMPLETE name of the file you
would like to process?')
in_file = open(in_filename, 'rU')
text = in_file.read()
count = len(text.splitlines())
print "There are ", count, 'lines to process in this file'
out_filename1 = raw_input('What is the COMPLETE name of the file in
which you would like to save Companies?')
companies = open(out_filename1, 'aU')
out_filename2 = raw_input('What is the COMPLETE name of the file in
which you would like to save Inventors?')
patentdata = open(out_filename2, 'aU')
for line in text:
 if line[-1] in ')':
     companies.write(line)
 else:
 patentdata.write(line)
in_file.close()
companies.close()
patentdata.close()

Thanks

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



--
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels


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


Re: [Tutor] Should I use python for parsing text?

2007-03-23 Thread Jay Mutter III
First thanks for all of the help
I am actually starting to see the light.

On Mar 22, 2007, at 7:51 AM, Kent Johnson wrote:

> Jay Mutter III wrote:
>> Kent;
>> Thanks for the reply on tutor-python.
>> My data file which is just a .txt file created under WinXP by an  
>> OCR program contains lines like:
>> A.-C. Manufacturing Company. (See Sebastian, A. A.,
>> and Capes, assignors.)
>> A. G. A. Railway Light & Signal Co. (See Meden, Elof
>> H„ assignor.)
>> A-N Company, The. (See Alexander and Nasb, as-
>> signors.;
>> AN Company, The. (See Nash, It. J., and Alexander, as-
>> signors.)
>> I use an intel imac running OS x10.4.9 and when I used python to  
>> append one file to another I got a file that opened in OS X's
>> TexEdit program with characters that looked liked Japanese/Chinese  
>> characters.
>> When i pasted them into my mail client (OS X's mail) they were  
>> then just a sequence of question marks so I am not sure what  
>> happened.
>> Any thoughts???
>
> For some reason, after you run the Python program, TexEdit thinks  
> the file is not ascii data; it seems to think it is utf-8 or a  
> Chinese encoding. Your original email was utf-8 which points in  
> that direction but is not conclusive.
>
> If you zip up and send me the original file and the cleandata.txt  
> file *exactly as it is produced* by the Python program - not edited  
> in any way - I will take a look and see if I can guess what is  
> going on.
>>

You are correct that it was utf-8
Multiple people were scanning pages and converting to text, some  
saved as ascii and some saved as unicode
The sample used above was utf-8 so after your comment i checked all,  
put everything as ascii, combined all pieces into one file and  
normalized the line endings to unix style


>> And i tried  using the following on the above data:
>> in_filename = raw_input('What is the COMPLETE name of the file you  
>> want to open:')
>> in_file = open(in_filename, 'r')
>
> It wouldn't hurt to use universal newlines here since you are  
> working cross-platform:
>   open(in_filename, 'Ur')
>

corrected this

>> text = in_file.readlines()
>> num_lines = text.count('\n')
>
> Here 'text' is a list of lines, so text.count('\n') is counting the  
> number of blank lines (lines containing only a newline) in your  
> file. You should use
>   num_lines = len(text)
>

changed


>> print 'There are', num_lines, 'lines in the file', in_filename
>> output = open("cleandata.txt","a")# file for writing data to  
>> after stripping newline character
>
> I agree with Luke, use 'w' for now to make sure the file has only  
> the output of this program. Maybe something already in the file is  
> making it look like utf-8...
>
>> # read file, copying each line to new file
>> for line in text:
>> if len(line) > 1 and line[-2] in ';,-':
>> line = line.rstrip()
>> output.write(line)
>> else: output.write(line)
>> print "Data written to cleandata.txt."
>> # close the files
>> in_file.close()
>> output.close()
>> As written above it tells me that there are 0 lines which is  
>> surprising because if I run the first part by itself it tells  
>> there are 1982 lines ( actually 1983 so i am figuring EOF)
>> It copies/writes the data to the cleandata file but it does not  
>> strip out CR and put data on one line ( a sample of what i am  
>> trying to get is next)
>> A.-C. Manufacturing Company. (See Sebastian, A. A., and Capes,  
>> assignors.)
>> My apologies if i have intruded.
>
> Please reply on-list in the future.
>
> Kent

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


Re: [Tutor] Another string question

2007-03-23 Thread Jay Mutter III


On Mar 23, 2007, at 5:30 AM, Andre Engels wrote:


2007/3/22, Jay Mutter III <[EMAIL PROTECTED]>:
I wanted the following to check each line and if it ends in a right
parentheses then write the entire line to one file and if not then
write the line to anther.
It wrote all of the ) to one file and the rest of the line (ie minus
the ) to the other file.

The line:
 print "There are ", count, 'lines to process in this file'
should give you a hint - don't you think this number was rather high?

The problem is that if you do "for line in text" with text being a  
string, it will not loop over the _lines_  in the string, but over  
the _characters_ in the string.


The easiest solution would be to replace
 text = in_file.read()
by
 text = in_file.readlines()



Thanks for the response
Actually the number of lines this returns is the same number of lines  
given when i put it in a text editor (TextWrangler).
Luke had mentioned the same thing earlier but when I do change read  
to readlines  i get the following



Traceback (most recent call last):
  File "extract_companies.py", line 17, in ?
count = len(text.splitlines())
AttributeError: 'list' object has no attribute 'splitlines'




in_filename = raw_input('What is the COMPLETE name of the file you
would like to process?')
in_file = open(in_filename, 'rU')
text = in_file.read()
count = len(text.splitlines())
print "There are ", count, 'lines to process in this file'
out_filename1 = raw_input('What is the COMPLETE name of the file in
which you would like to save Companies?')
companies = open(out_filename1, 'aU')
out_filename2 = raw_input('What is the COMPLETE name of the file in
which you would like to save Inventors?')
patentdata = open(out_filename2, 'aU')
for line in text:
 if line[-1] in ')':
 companies.write(line)
 else:
 patentdata.write(line)
in_file.close()
companies.close()
patentdata.close()

Thanks

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



--
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels


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


[Tutor] Another string question

2007-03-22 Thread Jay Mutter III
I wanted the following to check each line and if it ends in a right  
parentheses then write the entire line to one file and if not then  
write the line to anther.
It wrote all of the ) to one file and the rest of the line (ie minus  
the ) to the other file.


in_filename = raw_input('What is the COMPLETE name of the file you  
would like to process?')
in_file = open(in_filename, 'rU')
text = in_file.read()
count = len(text.splitlines())
print "There are ", count, 'lines to process in this file'
out_filename1 = raw_input('What is the COMPLETE name of the file in  
which you would like to save Companies?')
companies = open(out_filename1, 'aU')
out_filename2 = raw_input('What is the COMPLETE name of the file in  
which you would like to save Inventors?')
patentdata = open(out_filename2, 'aU')
for line in text:
 if line[-1] in ')':
 companies.write(line)
 else:
     patentdata.write(line)
in_file.close()
companies.close()
patentdata.close()

Thanks

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


[Tutor] Why is it...

2007-03-22 Thread Jay Mutter III
Why is it that when I run the following interactively

f = open('Patents-1920.txt')
line = f.readline()
while line:
 print line,
 line = f.readline()
f.close()

I get an error message

File "", line 4
 f.close()
 ^
SyntaxError: invalid syntax

but if i run it in a script there is no error?

Thanks

Jay

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


[Tutor] Should I use python for parsing text

2007-03-20 Thread Jay Mutter III

"Jay Mutter III"  wrote

> See example  next:
> A.-C. Manufacturing Company. (See Sebastian, A. A.,
> and Capes, assignors.)
>...
>Aaron, Solomon E., Boston, Mass. Pliers. No. 1,329,155 ;
>Jan. 27 ; v. 270 ; p. 554.
>
> For instance, I would like to go to end of line and if last
> character  is a comma or semicolon or hyphen then
> remove the CR.

It would look something like:

output = open('example.fixed','w')
for line in file('example.txt'):
if line[-1] in ',;-':# check last character
  line = line.strip() # lose the C/R
  output.write(line)# write to output
else: output.write(line)  # append the next line complete with C/R
output.close()




Working from the above suggestion ( and thank you very much - i did  
enjoy your online tutorial)

I came up with the following:

import os
import sys
import re
import string

# The next 5 lines are so I have an idea of how many lines i started  
with in the file.


in_filename = raw_input('What is the COMPLETE name of the file you  
want to open:')

in_file = open(in_filename, 'r')
text = in_file.read()
num_lines = text.count('\n')
print 'There are', num_lines, 'lines in the file', in_filename

output = open("cleandata.txt","a")# file for writing data to  
after stripping newline character


# read file, copying each line to new file
for line in text:
if line[:-1] in '-':
line = line.rstrip()
output.write(line)
else: output.write(line)

print "Data written to cleandata.txt."

# close the files
in_file.close()
output.close()

The above ran with no erros, gave me the number of lines in my  
orginal file but then when i opened the cleandata.txt file

I got:

A.-C.䴀愀渀甀昀愀挀琀甀爀椀渀最Company.⠀匀攀攀 
Sebastian,䄀⸀A.,and䌀愀瀀攀猀Ⰰassignors.)A.䜀⸀A.刀 
愀椀氀眀愀礀Light☀Signal䌀漀⸀(See䴀攀搀攀渀 
ⰀElofHassignor.)A-N䌀漀洀瀀愀渀礀ⰀThe.⠀匀攀攀 
Alexander愀渀搀Nasb,愀猀ⴀ猀椀最渀漀爀猀⸀㬀䄀一 
Company,吀栀攀⸀(See一愀猀栀ⰀIt.䨀⸀Ⰰand䄀氀攀砀 
愀渀搀攀爀Ⰰas-


So what did I do to cause all of the strange characters
Plus since this goes on it is as if it removed all \n and not just  
the ones after a hyphen which I was using as my test case.


Thanks again.

Jay



> Then move line by line through the file and delete everything
> after a  numerical sequence

Slightly more tricky because you need to use a regular expression.
But if you know regex then only slightly.

>  I am wondering if Python would be a good tool

Absolutely, its one of the areas where Python excels.

> find information on how to accomplish this

You could check  my tutorial on the three topics:

Handling text
Handling files
Regular Expressions.

Also the standard python documentation for the general tutorial
(assuming you've done basic programming in some other language
before) plus the re module

> using something like the unix tool awk or something else??

awk or sed could both be used, but Python is more generally
useful so unless you already know awk I'd take the time to
learn the basics of Python (a few hours maybe) and use that.

--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Should I use python for parsing text

2007-03-11 Thread Jay Mutter III
I am using an intel iMac with OS -X 10.4.8.
It has Python 2.3.5.

My issue is that I have a lot of text ( about 500 pages at the  
moment) that I need to parse so that I can eliminate  info I don't  
need, break the remainder into fields and put in a database/spreadsheet.
See example  next:

A.-C. Manufacturing Company. (See Sebastian, A. A.,
and Capes, assignors.)
A. G. A. Railway Light & Signal Co. (See Meden, Elof
H„ assignor.)
A-N Company, The. (See Alexander and Nasb, as-
signors.;
AN Company, The. (See Nash, It. J., and Alexander, as-
signors.)
A/S. Arendal Smelteverk.(See Kaaten, Einar, assignor.)
A/S. Bjorgums Gevaei'kompani. (See Bjorguni, Nils, as-
signor.)
A/S  Mekano. (Sec   Schepeler,   Herman  A.,  assignor.)
A/S Myrens Verkstad.(See Klling, Jens W. A., assignor.)
A/S Stordo Kisgruber. (See Nielsen, C., and Ilelleland,
assignors.)
A-Z Company, The.'See llanmer, Laurence G., assignor.)
Aagaard, Carl L., Rockford, 111. Hand scraping tool. No.
1,345,058 ; July 6; v. 276 ; p. 05.
Aalborg, Christian, Wllkinsburg, Pa., assignor to Wcst-
inghouse Electric and Manufacturing Company. Trol-
ley.No. 1,334,943 ; Mar. 30 ; v. 272 ; p. 741.
Aaron, Solomon E., Boston, Mass. Pliers. No. 1,329,155 ;
Jan. 27 ; v. 270 ; p. 554.

For instance, I would like to go to end of line and if last character  
is a comma or semicolon or hyphen then remove the CR.
Then move line by line through the file and delete everything after a  
numerical sequence

  I am wondering if Python would be a good tool and if so where can I  
find information on how to accomplish this or would I be better off  
using something like the unix tool awk or something else??

Thanks

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


Re: [Tutor] hand-holding for web development

2005-10-24 Thread Jay Loden
Sorry, didn't see your reply until now...

the directory section can go either in your main apache config file (in my 
case, /etc/httpd/conf/httpd.conf ) OR in a separate file in the conf.d 
directory. In my case, I have a python.conf file in /etc/httpd/conf.d/ that 
contains the following: 

LoadModule python_module modules/mod_python.so


AddHandler  mod_python .htm
PythonHandler parse
#  PythonDebug On


As for Django, I don't even know what that is, let alone how to interface to 
it, so you'd have to look elsewhere for help on that. I imagine there's 
someplace online you can get Django help such a specific mailing list.

-Jay

On Tuesday 18 October 2005 04:23 pm, nitin chandra wrote:
> Thanks Jay
>
> i guess the  can be added only in one of the conf
> file. Which one should i add in?
>
> Thaks you. could you please guide how to interface Django with
> mod_python, for effectively using in web site development?
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] hand-holding for web development

2005-10-17 Thread Jay Loden
You need an Apache config section to tell it what to use mod_python on and 
how. For example, in httpd.conf or a separate file in your conf.d directory 
for apache: 


   AddHandler  mod_python .py
   PythonHandler test
   PythonDebug On


tells Apache to use mod_python on all .py files in my /var/www/html directory 
(which is also the document root on my server). 

Once that's loaded you should be able to run whatever your python code through 
a handler. For example, saving this as test.py: 

#
#mod_python super basic test script
#
from mod_python import apache

def handler(req):
   req.content_type = "text/html"
   req_file = basename(req.uri)
   if req.header_only:
  return apache.OK

   else:
  req.write("mod_python is working")
  return apache.OK

# end of script

This should print "mod_python is working" to the browser if you visit 
http://yoursite.com/test.py 

Remember that you need to restart/reload apache after any config change. The 
basic gist is that any .py file you load in the /var/www/html runs the script 
"test.py" (PythonHandler test) and executes the "handler()" function within 
the script. NOTE: this can be very non-intuitive, becuase running 
http://yoursite.com/test.py has exactly the same result as 
http;//yoursite.com/foo.py - because they're both simply running the handler 
script, test.py, for ALL .py files in the directory. That means that your 
PythonHandler script needs to dispatch other scripts or load special pages in 
order to get different code to run. Also note that there are some pre-written 
Handler scripts that come with mod_python that can often do most of your work 
for you.

You'll probably want a good tutorial on using mod_python to make sense of all 
this, because it's not really intuitive and it works differently than 
traditional cgi programming. Take a look at: 
http://modpython.org/live/current/doc-html/ 
to get you started, it's a lot more detailed and will probably answer your 
questions better. 

-Jay

On Thursday 13 October 2005 3:49 pm, nitin chandra wrote:
> Hi!...
> i am new to Python and i want to develop a website with forms; data
> submitted through forms will be stored in PostgreSQL.
> I am working on derivant of FC3, OpenLX.
> I have Apache 2.0.54 version installed, which is pre-configured with
> mod_python.
> how do i load and view my .py/.html web page (file) on the browser.
> i need the initial hand holding/guidance of how to start, configure , and
> develop modules.
>  thank in advance.
>  Nitin Chandra
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Mod_python greedy url matching

2005-10-04 Thread Jay Loden
I'm having trouble with Apache and Mod_python - mod_python is set to 
use /var/www/html and pass all *.htm files on to the handler I wrote. 
Unfortunately, mod_python does a greedy match, 
so /var/www/html/subdirectory/file.htm still gets passed to the handler!  Is 
there some way to limit the handler to the directory and NOT include 
subdirectories?

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


Re: [Tutor] Python equiv to PHP "include" ?

2005-09-29 Thread Jay Loden
Alan, thanks for your responses, they're quite helpful. I suspect the real 
problem I'm having is simply trying to switch modes of thinking to CGI style 
or mod_python style instead of the PHP style embedded code. 

The whole point of this exercise for me was to decide which language I prefer 
for web development and evaluate Python for web work. So far, I've found PHP 
much easier to work with and less "clunky" in terms of what I'm trying to do 
- but I believe that's very much a function of my thinking being rooted in 
the PHP style. 

If Im understanding this right...the Pythonic/CGI method for something like 
this is to import a template module of some kind, then call methods from that 
template to display the template, with other Python code in the middle that 
takes care of form processing? 

The solution I have now feels smoother, since all I do is put content 
into .htm files, then pull them into a template that's basically an html 
sandwich. This gives me capability to stick a  section into the .htm 
file itself - for example a form with some dynamic content/variables - and 
then from a user perspective, all they see is a normal html page.  

>From a server side, it's seeing one big PHP script that includes both template 
code and form code, but without me needing to write any templating code into 
the form itself - instead I just call the form into the template.  With 
Python, it seems like this kind of approach is impossible, and it also means 
that my form would probably have to have some kind of special extension, like 
"form.py" (so the handler knows what to do with it) instead of just being 
located at "form.htm" - am I following this all correctly? 

Does anyone know of any soup-to-nuts CGI programming examples online for 
Python that might make this clearer so I can bug the list less and just read 
some example code?

-Jay

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


[Tutor] Python equiv to PHP "include" ?

2005-09-29 Thread Jay Loden
I've not been able to find an answer to this conundrum anywhere: 

My current website is done in PHP with a setup something like this: 

::PHP TEMPLATE CODE::

include('file.htm')

::PHP TEMPLATE CODE::

This way, I can have PHP embedded in my htm files and it will be processed as 
part of the script. For example, I can have a form that's written in HTML and 
processed in PHP, then simply 'include("form.htm")' and I have a form with 
processing that's ALSO wrapped in my site template. 

I can't figure out how one would approach this in Python (i'm using 
mod_python). There's no equivalent to the "include" function from PHP. I 
can't use import because then Python would try to parse the HTML from the 
imported file. I've looked at stuff like cheetah and PSP, but neither of 
those actually answers the question, which is how can I include dynamic 
content including PHP code directly into an existing script. Even if I 
started using PSP, I still can't "include" a PSP page into the middle of 
another PSP page.

I'm definitely willing to consider any other solution for how I can make a 
form that processes its input but maintains my template code wrapped around 
it, so feel free to point out a "Pythonic" method. I just don't want to 
duplicate the template code, and I can't find a nice neat solution like what 
I've got in PHP.

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


Re: [Tutor] Invoking bash from within a python program

2005-09-02 Thread Jay Loden
Watch yourself on this one, slocate can often return some unexpected results 
for file searches, and the last thing you want to do is delete something 
important while trying to remove the latest game you installed. 

Also, if you're installing from source you can often run "make uninstall" to 
remove the installed files. 

And finally, the Vinay's suggestion of a simple one liner shell script is much 
simpler and probably as fast or faster than anything you come up with in 
Python.

Just figured I'd lend some words of warning to you as someone who's made 
similar mistakes in the past ;)

-Jay

On Sunday 14 August 2005 6:33 am, joe_schmoe wrote:
> The basic idea I was toying around with is to create a delete/uninstall
> program that would take the output of slocate and iterate through that
> deleting all of the files associated with the program
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] while loops

2005-08-08 Thread Jay Loden
> coin = random.randrange(2)

That's the problem there...you've got coin assigned outside the while loop, so 
it is assigned 0 or 1 once, before the loop, and then you're running 100 
checks on the same value. 

If you move 
> coin = random.randrange(2)

to inside the while loop before the if statement, you'll get the result you 
want. 

-Jay


On Monday 08 August 2005 5:41 pm, Will Harris wrote:
> I am working my way through "python programming for the absolute beginner"
> and one of the challenges is to create a program that will flip a coin 100
> times and tell you how many of each it did. Now I have it flipping the
> coin, but when I try to do this 100 times I end up with it running through
> 100 times, but always the same result comes back. It will either be 100
> heads, or 100 tails. I have tried if statements and while loops and both
> seem to give me all or nothing. I am just looking for a hint at the
> direction to look of adjust to get the code below working not really the
> solution. Thanks in advanced for any tips.
>
> #!/usr/bin/python
> import random
>
> coin = random.randrange(2)
>
> count = 0
> head_count = 0
> tail_count = 0
>
> while (count != 100):
> if coin == 0:
> print "You got Heads!"
> head_count = head_count + 1
> count = count + 1
> else:
> print "You got Tails!"
> tail_count = tail_count + 1
> count = count + 1
>
> print "Out of", count, "you flipped", head_count, "heads and ", tail_count,
> "tails"
>
> ___
> 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] Zope/Python web devel

2005-08-03 Thread Jay Loden
I've been considering some web projects recently, but I have some concerns 
about selecting the tools I plan to use. I like Python, and I was immediately 
thinking of using Zope to build on.

However, I am concerned about performance, resource usage, and scalability. 
Does anyone here have any experience with Zope or any other application 
frameworks like CherryPy used in a large/enterprise environment? Is Zope 
overly memory hungry or slow? If performance is a key point, am I better off 
growing my own solution from the ground up?

Second, and more specific to Python itself - does anyone here have first hand 
knowledge of how Python compares with other solutions for server side web 
development? I'm specifically interested in comparisons to PHP, but Ruby, 
Perl, Java, C/C++ and Lisp, etc. observations would be welcome. Basically, 
I'm trying to get a feel for what kind of performance and resource usage I'd 
see out of Python versus other options. I realize this is heavily dependent 
on what exactly I end up doing, but just as a general observation, I'd like 
to know what others have experienced. I know that some large web applications 
are built on Python (Yahoo Mail, Google), but there's certainly less being 
done in Python on the web than in Perl or PHP. I just want to make sure this 
isn't because of Python disadvantages as opposed to simple market share.

All responses are welcome. If anyone has links to some benchmarking studies 
comparing the two for web development I'd be grateful for those as well.

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


Re: [Tutor] How do I add an argument too...

2005-08-03 Thread Jay Loden
I think it was just a typo for "the python distro" that came out as "the 
epython distro"...

On Thursday 21 July 2005 9:15 pm, Danny Yoo wrote:
> On Thu, 21 Jul 2005, Joseph Quigley wrote:
> > optparse.. Can I download that as a module or do I have to download
> > epython?
>
> Hi Joseph,
>
> optparse derives from a hird-party library called Optik, so in a pinch,
> you can probably just use Optik:
>
> http://optik.sourceforge.net/
>
> It's also possible to port optparse back to older versions of Python,
> although that may take more work.
>
> Good luck!
>
> ___
> 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] Deleting an entry from a dictionary

2005-08-03 Thread Jay Loden
I don't believe it does...some time ago I asked about this when I was creating 
a list and I wanted the opposite of list.append() - if you search "prepend to 
a list" you should find the responses I was sent. 

The only solutions Python offers that I'm aware of are to either use 
list.insert() at the zero index, or use list.reverse() with list.append() to 
flip the list around, add an item, then reverse it back to the original order 
with one new item at the beginning. 

-Jay

On Wednesday 03 August 2005 2:21 pm, Smith, Jeff wrote:
> Ummm...that doesn't do what I asked.
>
> pop is a linguistic idiom for
>
> (val, mylist) = (mylist[-1], mylist[0:-1])
>
> shift is the standard idiom for
>
> (val, mylist) = (mylist[0], mylist[1:])
>
> but Python doesn't appear to offer this.
>
> Jeff
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] getopt matching incorrect options

2005-07-11 Thread Jay Loden
I have an app that takes a command line argument of -l or --list.  It uses the 
getopt module to parse the arguments, and I just noticed that for some 
reason, getopt is matching "--lis" or "--li" etc to "--list". (Code pasted in 
below)

Is this normal behavior, and if so, is there any way to avoid this? I just 
want it to match "--list" to "--list", not "--l" and "--li" and "--lis" etc. 

-Jay


## Code chunk below ##

 try:
options,args = getopt.getopt(sys.argv[1:], "Rf:shvl", ["list", 
"full-restart=", "full-restart-all", "status-all", "help", "version"])

 except getopt.GetoptError:
# print help information and exit:
usage()
sys.exit(2)

if opt in ("-l", "--list"):
listServices(svcs)
sys.exit()
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] getopt matching incorrect options

2005-07-11 Thread Jay Loden
I have an app that takes a command line argument of -l or --list.  It uses the 
getopt module to parse the arguments, and I just noticed that for some reason, 
getopt is matching "--lis" or "--li" etc to "--list". (Code pasted in below)

Is this normal behavior, and if so, is there any way to avoid this? I just want 
it to match "--list" to "--list", not "--l" and "--li" and "--lis" etc. 

-Jay


## Code chunk below ##

 try:
options,args = getopt.getopt(sys.argv[1:], "Rf:shvl", ["list", 
"full-restart=", "full-restart-all", "status-all", "help", "version"])

 except getopt.GetoptError:
# print help information and exit:
usage()
sys.exit(2)

if opt in ("-l", "--list"):
listServices(svcs)
sys.exit()
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python and Web Pages?

2005-04-23 Thread Jay Loden
I use both Python and PHP on my website to do a variety of tasks.  Some things 
PHP can do much easier than Python, but if you're doing simple things like 
form handling, Python will do nicely.  

If you're comfortable with Python, use it.  I find Python much easier to work 
with than PHP for a lot of things, but PHP works better with dynamic content 
within html, so I use each one where it's easiest. However, if you're not 
familiar with PHP, then I definitely wouldn't go out and learn PHP for this; 
just stick with Python because you'll get it done faster when you're 
comfortable.

-Jay

On Saturday 23 April 2005 05:09 pm, Paul Tader wrote:
> I have a couple programs/scripts that I want to write that need to be
> web-based.  Can Python (and a little HTML) accomplish this?  Or are
> other languages like PHP, or Perl better suited?
>
>
> A little more detail:
>
> One project is to make a web page that users login to with a name and
> password, choose from a list of "canned" directory structure (ie. how
> many subdirectories, top-level name, maybe permissions, etc), hit a "GO"
> button and then the directories are made.
>
> Another example is a web-based form that users interface with a mySQL
> database.  Simple additions/changes/deletions.  Basic stuff.
>
>
> Thanks,
> Paul
>
>
>
> ___
> 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] Installation Routines (Joseph Quigley)

2005-04-21 Thread Jay Loden
Rpm does in fact have dependency resolution, and rpm-based distributions use a 
package manager that can download the dependencies and install them for you - 
urpmi on mandrake, yum or apt4rpm on Fedora and Redhat, Yast on Suse

I've used all of these, they are all rpm based, and they all install 
dependencies. If you use the raw "rpm" command, even that will tell you 
"missing dependecy foo".

That being said, apt-get on debian is still my favorite (for sheer number of 
available packages), but urpmi on mandrake or Yast on Suse are quite 
excellent.

-Jay

On Wednesday 20 April 2005 04:17 pm, Max Noel wrote:
emerge and apt-get come to mind. rpm is inferior (no dependency
> resolution) but still does a good job, and I hear autopackage isn't
> bad.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to display an image using python

2005-04-14 Thread Jay Loden
If you don't mind using an external program, you could use the 'display' 
command from ImageMagick. 

-Jay

On Thursday 14 April 2005 07:59 pm, Ertl, John wrote:
> All,
>
> I have asked this question before, but one more time most have commented
> about manipulation but displaying the image has become the big issue.  I
> want to display png and gif images on a Linux machine using python.  I am
> using PyNGL to make the images and PIL to manipulate them but I cannot load
> xv on the machines and PIL uses xv to display.  I have looked at
> PythonMagick but I could not even get past installing it.  It does not have
> a setup.py and uses boost.  I am hoping for a more straightforward Python
> way.
>
> Thanks,
>
> John Ertl
> ___
> 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] Cell Bio Newbie Here

2005-04-11 Thread Jay Loden
Ok, it's a logic error in the while loop.  Starting at the beginning: you 
can't compare the value of "password" until the user inputs the value, which 
is why it's requiring you to put password = "foobar" at the top.  Otherwise, 
password has no value, and as far as the interpreter is concerned, it doesn't 
exist yet. 

The rest of it is a logic error because your while loop is executing as long 
as "unicorn" != "foobar" and therefore it's continuously looping.  Each time 
it loops, it asks for the password again, and sets a LOCAL variable called 
password to the new raw_input.  Then, when you get to the third time, it does 
the "if current_count in." Great.  But after my third mistake, it just loops in "That must have
> been complicated."
>
> I'd like for someone to tell me "why" i screwed up.  Not to just fix it.

> #first of all, why does this have to be here?
> password="foobar"
>
> count=3
> current_count=0
>
> while password !="unicorn":
>  if current_count  password=raw_input("Password:")
>  current_count=current_count+1
>  else:
>  print "That must have been complicated"
>
>
> print "Welcome in"
> Best,
>
> Gary
>
>
>
> Gary Laevsky, Ph.D.
> Keck Facility Manager, CenSSIS
> Northeastern University
> 302 Stearns
> 360 Huntington Ave.
> Boston, MA 02115
> voice(617) 373 - 2589
> fax(617) 373 - 7783
>
> http://www.censsis.neu.edu
>
> http://www.ece.neu.edu/groups/osl
>
> http://www.keck3dfm.neu.edu
>
> ___
> 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] Re: random import errors

2005-04-05 Thread Jay Loden
Only one version installed, and I could copy it over from elsewhere, but I 
wouldn't be inclined to do so since it works right now. 

-Jay

On Tuesday 05 April 2005 10:22 pm, Lee Harr wrote:
> >I have a python script that runs on my webserver every fifteen minutes. 
> > It has run for several months with absolutely no problems.  Suddenly,
> > yesterday
> >morning I got an email from cron with an import error for sre_constants
> >(see
> >below)
> >
> >
> >   File "/usr/lib/python2.2/sre_compile.py", line 15, in ?
> > from sre_constants import *
> >ImportError: No module named sre_constants
>
> Do you have more than one version of python installed?
> Can you copy sre_constants.py from another system?
>
> _
> Express yourself instantly with MSN Messenger! Download today it's FREE!
> http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/
>
> ___
> 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] random import errors?

2005-04-01 Thread Jay Loden
I have a python script that runs on my webserver every fifteen minutes.  It 
has run for several months with absolutely no problems.  Suddenly, yesterday 
morning I got an email from cron with an import error for sre_constants (see 
below)

I logged in with ssh, manually ran the script and got the same error.  started 
a Python interpreter shell, did "import sre_constants" and got no error.  
Exited, then ran the script again...and got an error importing 'string'.  I 
manually started up Python interpreter again and imported string, again with 
no error.  Then I exited and ran the script, and it ran fine with no errors. 

I got another such email from cron at 2:30am today ... anyone have any idea 
what would cause such a seemingly random problem after months of working 
fine? 

(sample traceback is below)
-Jay

'import site' failed; use -v for traceback
Traceback (most recent call last):
  File "/usr/local/bin/last_update", line 7, in ?
    import os, glob, time
  File "/usr/lib/python2.2/glob.py", line 4, in ?
    import fnmatch
  File "/usr/lib/python2.2/fnmatch.py", line 13, in ?
    import re
  File "/usr/lib/python2.2/re.py", line 27, in ?
    from sre import *
  File "/usr/lib/python2.2/sre.py", line 97, in ?
    import sre_compile
  File "/usr/lib/python2.2/sre_compile.py", line 15, in ?
    from sre_constants import *
ImportError: No module named sre_constants
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Prepend to a list?

2005-03-19 Thread Jay Loden
How can I prepend something to a list? I thought that I could do
list.prepend()  since you can do list.append() but apparently not.  Any way to 
add something to a list at the beginning, or do I just have to make a new 
list? 

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


Re: [Tutor] Newbie simple question

2005-02-25 Thread Jay Loden
You want readlines() not readline() and it should work something like this:

remailfile = open("remail2.txt", r)
remails = remailfile.readlines()

for line in remails:
  #do something

-Jay

On Friday 25 February 2005 05:14 pm, Valone, Toren W. wrote:
> I need to know how to read the next line while in the "for line in" loop.
> Readline does not read the next line (I watched it in debug) I think it has
> something to do with the for line loop but I have not found any
> documentation in the doc's or tutor for any functions for line..
>
> Thanks, please forgive the sloppy code.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] sys.argv[1: ] help

2005-02-25 Thread Jay Loden
Should be: 

import sys

def main():
  '''prints out the first command line argument'''
  print sys.argv[1]

main()

On Friday 25 February 2005 04:35 pm, Richard gelling wrote:
> Hi,
>
> I am reading ' Learning Python second edition' by Mark Lutz and David
> Ascher, and  I trying the code examples as  I go along. However I am
> having a problem with the following, which I don't seem to be able to
> resolve :-
>
> # test.py
> import sys
>
> print sys[ 1: ]
>
> This I believe is supposed to print the 1st argument passed to the
> program. However if I try
>
> test.py fred
>
> All  I get at the command line is
>
> []
>
> If I try :-
>
> python test.py fred
>
> I get
>
> ['fred']
>
> as I believe you are supposed to. I can run other examples,I have typed
> in by just using the file name, but not this particular example. Could
> anyone shine any light on what I am missing or have not configured
> correctly. I am runnung Python 2.4 on a windows XP box.
>
> Thanks a lot
>
> Richard G.
> ___
> 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] files in a directory

2005-01-30 Thread Jay Loden
There's a few ways to accomplish this...the way that comes to mind is: 

##
import glob

files = glob.glob("/path/to/director/*.dml")  # assuming you want only .dml 

def spot(file):
  '''search for intensity spots and report them to an output file'''
  f1 = open('my_intensity_file.dml','r')
  int = f1.read().split('\n')

  my_vals  = intParser(int) 

  intParser return a list
  f2  = open('myvalues.txt','w') # you will want to change this to output mult 
  for line in my_vals:   # files, or to at least append instead of overwriting
  f2.write(line)
f2.write('\n')
  f2.close()

def main():
  for each in files:
spot(each)

main()

##

Basically, turn the parsing into a function, then create a list of files, and 
perform the parsing on each file.  glob() lets you grab a whole list of files 
matching the wildcard just like if you typed "ls *.dml" or whatever into a 
command prompt.  There wasn't too much info about specifically how you needed 
this to work, so this is a rough sketch of what you want. Hopefully it helps.

-Jay

On Sunday 30 January 2005 03:03 am, kumar s wrote:
> Hello.
>
> I wrote a parser to parse spot intensities. The input
> to this parser i am giving one single file
>
> f1 = open('my_intensity_file.dml','r')
> int = f1.read().split('\n')
>
> my_vals  = intParser(int)
>
> intParser return a list
> f2  = open('myvalues.txt','w')
> for line in my_vals:
>  f2.write(line)
>  f2.write('\n')
>
> f2.close()
>
>
> The problem with this approach is that, i have to give
> on file per a run. I have 50 files to pare and i want
> to do that in one GO.  I kepy those 50 files in one
> directory. Can any one suggest an approach to automate
> this process.
>
> I tried to use f1 = stdin(...) it did not work. i dont
> know , possible is that i am using incorrect syntax.
>
> Any suggestions.
>
> Thank you.
> K
>
>
>
>
>
>
>
> __
> Do you Yahoo!?
> All your favorites on one personal page – Try My Yahoo!
> http://my.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] New to Python

2005-01-26 Thread Jay Loden
I also recommend the book "Dive Into Python" - it gets awesome reviews, and 
the book is under Creative Commons license, so it's free to download and 
distribute. 

http://diveintopython.org 

I also have the book "Core Python Programming" which is pretty good, and has a 
nice way of leaping right into code so that if you have any prior knowledge, 
you can use it to learn faster. 

-Jay

On Wednesday 26 January 2005 09:09 pm, Jason White wrote:
> 
> Greetings all, I'm new to python and thought I'd pop in here for
> advice. I've done object oriented design and programmed in perl,
> java, c++, basic, etc. I haven't done a lot of development, mostly
> just glorified oject-oriented scripts. I'm curious about good
> tutorial websites and books to buy.
>  
> I also have a development question for anybody who might know.  The
> project I'm working on now to develop my python skills is a prgram to
> script control another windows program.  The program doesn't have a
> published API so I'll probably need to locate memory addresses data fields
> and button routines.  Am I in way over my head for a Python beginner
> or does anybody have any advice for where to start poking around in memory
> and which python classes I should use to do so? 
>  
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] read line x from a file

2005-01-21 Thread Jay Loden
One simple solution is to do: 

fle = open(file)
contents = file.readlines()
file.close()
print contents[x]  #or store this in a variable, whatever

-Jay

On Friday 21 January 2005 11:22, J. M. Strother wrote:
> I have  a text file containing 336 records.
> I can read and print out the whole file without any problem.
> What I want to do is read and print out one record only (chosen at
> random). So I need to get to record x, select it, and then print it (or
> store it in a variable).
> Can anyone tell me now to do this?
>
> I'm new to Python and programming, so sorry if this is very basic. Thanks.
>
> jon
> ___
> 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] glob or filter help

2005-01-21 Thread Jay Loden
I have the following code in my updates script (gets the five most recent 
updated files on my site)

def get_fles(exts, upd_dir):
 '''return list of all the files matching any extensions in list exts'''
 fle_list = [] 
 for each in exts:
  cmd = upd_dir + "*." + each
  ext_ls = glob.glob(cmd)
  fle_list = fle_list + ext_ls
 return filter(notlink, fle_list)

I wanted to just get one list, of all the .htm and .exe files in my upd_dir.  
I was trying to make a far more elegant solution that what's above, that 
could generate a list through a filter.  Is there a way to trim the code down 
to something that does ONE sort through the directory and picks up the .htm 
and .exe files? (note, it is not necessary for this to recurse through 
subdirectories in the upd_dir).  I have cmd defined above because calling
"glob.glob(upd_dir + "*." + each) returned the error "cannot concatenate 
string and list objects" - is this the only way around that, or is there a 
better way?

Also in the above code, "notlink" is just a function that returns True if 
"islink()" returns truethere has to be a better way to use this with 
filter(), how can i make filter use "if islink()!=true" as its condition?

The script is working now, (I know, I know, if it ain't broke, don't fix 
it...) but I want to be a better programmer so more elegant solutions are 
accepted gratefully. 
-Jay
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] need help planning website updates

2005-01-20 Thread Jay Loden
Adding it into the PHP that creates the html would create too much overhead 
since it loads each page individually upon request, and that would mean 
running the modified time check on every page load.  

But I was thinking about this after I sent the mail, and I think you have a 
point with just outputting the five last modified out of all files.  This was 
one of those times when your brain fails you and you think up an overly 
complicated solution to a simple problem. This way the script just has to run 
every 15 minutes or so and give me the five most recent files for use in the 
PHP. 

Thanks!

-Jay

On Thursday 20 January 2005 12:45, Kent Johnson wrote:
> It seems to me that if you want the five most recent changes, you don't
> have to keep a list of modified dates. Just get the modified date for all
> the files of interest and sort by date, then pick the top five.
>
> You could do this as part of your process to build the web site maybe?
>
> Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] need help planning website updates

2005-01-20 Thread Jay Loden
I have a sort of simple CMS system on my website made from a conglomeration of 
scripts.  On the left column, I want to add a feature that shows the last 
five items updated (only html & exe files in the /var/www/html/ for example) 
directory that I have updated, with each item as a link to the page. You can 
see what this is supposed to look like at http://jayloden.com (right now it's 
being done by hand)

I've been thinking of having a crontab run a Python script, which logs checks 
a file with something along the lines of: 

file.foo = 12:20-1/20/05

for each file, containing the date and time the file was last modified.  Then 
I would have the crontab script check the date in the file versus the dates 
on the current files, and if the current files have been updated, to add them 
to the html on the side of the page.  I have no trouble setting up the 
crontab, or editing the html template for my page (it's all created from php 
on the fly) but I wanted to know if I am going about this a semi-intelligent 
and/or efficient way, or if there is some incredibly better way that I could 
do this with Python.  For example, is there some other way to notify my 
script that a file has been modified, rather than run a crontab a couple 
times an hour.  Is there maybe a better way to store and check dates, etc. 

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