[Tutor] Checking the desktop environment

2008-06-20 Thread Timo
Hello all, in my program I need to know what desktop environment the
user is running. I figured this piece of code works, but apparently not
on every Linux distro. On Ubuntu it did the trick, but then I heard of
someone who runs SLiM that he get's an error with this.

if os.environ['DESKTOP_SESSION'].startswith('kde'):
print "Running KDE"


So, does anyone know a water-proof solution for desktop environment
checking?

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


Re: [Tutor] Learning Python from books

2008-06-20 Thread Kent Johnson
On Thu, Jun 19, 2008 at 2:56 PM, Zameer Manji <[EMAIL PROTECTED]> wrote:
> -BEGIN PGP SIGNED MESSAGE-
> Hash: SHA512
>
> Has anyone here attempted to learn Python from books ?

I learned Python from Learning Python and Python Cookbook initially.
Also lots of practice. Reading comp.lang.python is another good way to
learn.

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


[Tutor] Using Regex from Configuration File

2008-06-20 Thread Tyler Rutschman
Hello everyone,

I'm new to python and have set up a program to parse through reports. The
script has started very basic and I've been folding in additional features
as it moves along. What it does is takes a specified log file (exported from
splunk) and parses through it with a regex specific to the type of log.

It is invoked by: ./extract -f filename -c config

I've successfully set up ConfigParser to go through the config and apply the
proper configuration to the script, but I'm having trouble getting the regex
to work. It worked successfully when I declared it within the script.

 code 
def load_config():
configdict = ConfigParser()
configdict.read('report.conf')
conf=main()[0]
opt_name = configdict.get(conf,'name')
opt_regex = configdict.get(conf,'regex')
return opt_name,opt_regex
...
rawstr="r"+"\"\"\""+load_config()[1]+"\"\"\""
...
rxinput = re.compile(rawstr)
 code 

full code here http://codepad.org/pva1dE1i
configuration here http://codepad.org/VnXfQhBi

Any help would be appreciated.

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


Re: [Tutor] Using Regex from Configuration File

2008-06-20 Thread Kent Johnson
On Fri, Jun 20, 2008 at 10:04 AM, Tyler Rutschman <[EMAIL PROTECTED]> wrote:

> I've successfully set up ConfigParser to go through the config and apply the
> proper configuration to the script, but I'm having trouble getting the regex
> to work. It worked successfully when I declared it within the script.
>
>  code 
> def load_config():
> configdict = ConfigParser()
> configdict.read('report.conf')
> conf=main()[0]
> opt_name = configdict.get(conf,'name')
> opt_regex = configdict.get(conf,'regex')
> return opt_name,opt_regex
> ...
> rawstr="r"+"\"\"\""+load_config()[1]+"\"\"\""

Leave this out, just use the string from load_config() directly.

the r""" """ around the string are Python syntax, they should not be
part of the actual string.

Kent

> ...
> rxinput = re.compile(rawstr)
>  code 
>
> full code here http://codepad.org/pva1dE1i
> configuration here http://codepad.org/VnXfQhBi
>
> Any help would be appreciated.
>
> Thanks,
> Tyler
>
> ___
> 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] Help! Character conversion from a rtf file.

2008-06-20 Thread Chien Nguyen
Hi All,
I am a newbie to Python. I just did some readings on the web
and got some basic understanding about the language. I'd like
to learn the language by writing some simple programs rather than
keep reading books. My first program will convert certain uni-code characters
(let's say UTF-8) in an RTF file format based on a certain mapping
in another RTF file that is called a "RTF Control file". On each line
of the Control file, there are 2 tokens separate by a TAB or a space.
The first token contains the character that needs to be converted from,
and the second character contains the character that needs to be converted to.

The program will write to a new file that contains a new set of mapped 
characters.
If a character form the original file is not found in the Control file, then 
the program
just write the same character to the new file.
For an example: The RTF Control file may contain the following lines.

â í
ơ ă
ư ổ

The original RTF file may have something like
tâcmơm thư 

and will be converted to a new RTF file as follows.
tíc măm thổ

Before I start to go into the coding, I would like to get some advice from 
experienced users/mentors about a quick way to do it.

Thanks in advance!
-Chien Nguyen___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] How to set up dispatch function

2008-06-20 Thread Tyler Rutschman
Hello again everyone,

I'm trying to add another fold into my log reporting script. I would like to
set up a dispatch function to find the proper report format for the
indicated configuration. The function would need to recognize the
configuration and call a function that will parse the data and generate a
report. I've only made one type of report thus far but would like to get
this part ironed out before adding more. Any suggestions?

source code http://codepad.org/VyTAcuji

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


Re: [Tutor] Checking the desktop environment

2008-06-20 Thread Alan Gauld

"Timo" <[EMAIL PROTECTED]> wrote


Hello all, in my program I need to know what desktop environment the
user is running.


A few years ago I would have said that meant you had a broken
design since it was very bad practice for any program to depend
on the users environment. nfortunately recent developments in
Linux/X mean that the whole concept is broken that one more
environmentally wawre program probably is no big deal!

But there are caveats that mean you will probably never get
it right in every case. The best you cvan probably do is detect
if the environment is one of a fixed set  known to work with
your code.#

But bear in mind that the user can switch envirojnemts while
your code is running, or may even be runningmultiple
environments simultaneously on virtual windows etc.

Thats why the users environment should be left as as
something for the user and the programming environment
for the programmer.


I figured this piece of code works, but apparently not
on every Linux distro. On Ubuntu it did the trick, but then I heard 
of

someone who runs SLiM that he get's an error with this.

if os.environ['DESKTOP_SESSION'].startswith('kde'):
   print "Running KDE"


That would only find out if KDE was beiong used and only
if the user (or cofig scripts) has not modified the variable.


So, does anyone know a water-proof solution for desktop environment
checking?


I don't think such a thing can exist on a Unix/X system. An
approximation will be the best you can get.

Can you explain why you need to know?
In most situations there should be a generic way to do it.


Alan G. 



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


Re: [Tutor] How to set up dispatch function

2008-06-20 Thread Alan Gauld


"Tyler Rutschman" <[EMAIL PROTECTED]> wrote 


set up a dispatch function to find the proper report format for the
indicated configuration. 


Sounds like a job for a dictionary.

Just find the key and access the corresponding function.

Do you know how to do that? (Use a dictionary to strore functions?) 
or is it the derivation of the key thats the issue?


Alan G

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


[Tutor] Python and SOAP Web Services

2008-06-20 Thread Tse, William: #CIPO - OPIC
I am trying to use a SOAP Web Service with Python 2.5 and I'm following
the instructions in Chapter 12 of the "Diving into Python" tutorial.

It refers to three libraries that I'm having problems accessing or that
appear out of date : PyXML, fpconst and SOAPpy.
The tutorial also seems to be for Python 2.4 (which I've also tried
using unsuccessfully for web services).

Is there an updated manual or procedures that I can follow ?

Thanks,
Will

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


Re: [Tutor] Help! Character conversion from a rtf file.

2008-06-20 Thread Kent Johnson
On Fri, Jun 20, 2008 at 12:46 PM, Chien Nguyen <[EMAIL PROTECTED]> wrote:
> Hi All,
> I am a newbie to Python. I just did some readings on the web
> and got some basic understanding about the language. I'd like
> to learn the language by writing some simple programs rather than
> keep reading books. My first program will convert certain uni-code
> characters
> (let's say UTF-8) in an RTF file format based on a certain mapping
> in another RTF file that is called a "RTF Control file". On each line
> of the Control file, there are 2 tokens separate by a TAB or a space.

That doesn't sound like an RTF file, more like UTF-8 text.

> The first token contains the character that needs to be converted from,
> and the second character contains the character that needs to be converted
> to.
>
> The program will write to a new file that contains a new set of mapped
> characters.
> If a character form the original file is not found in the Control file, then
> the program
> just write the same character to the new file.

Hopefully your reading has shown you the way to read and write files.
Look at the codecs module for reading and writing UTF-8 files.

Once you have the file data loaded you can use the replace method of
the data to change the characters.

Something like this (*very rough*)

import codecs
data = codecs.open('data.rtf', 'r', 'utf-8').read()
replacements = codecs.open('replace.rtf', 'r', 'utf-8')

for line in replacements:
  line = line.strip()
  if line:
from, to = line.split()
data.replace(from, to)

f = codecs.open('newdata.rtf', 'w', 'utf-8')
f.write(data)
f.close()

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


Re: [Tutor] Help! Character conversion from a rtf file.

2008-06-20 Thread bob gailer

Chien Nguyen wrote:

Hi All,
I am a newbie to Python. I just did some readings on the web
and got some basic understanding about the language. I'd like
to learn the language by writing some simple programs rather than
keep reading books. My first program will convert certain uni-code 
characters

(let's say UTF-8) in an RTF file format based on a certain mapping
in another RTF file that is called a "RTF Control file". On each line
of the Control file, there are 2 tokens separate by a TAB or a space.
The first token contains the character that needs to be converted from,
and the second character contains the character that needs to be 
converted to.


The program will write to a new file that contains a new set of mapped 
characters.
If a character form the original file is not found in the Control 
file, then the program

just write the same character to the new file.
For an example: The RTF Control file may contain the following lines.

â í
ơ ă
ư ổ

The original RTF file may have something like
tâcmơm thư


and will be converted to a new RTF file as follows.
tíc măm thổ

Before I start to go into the coding, I would like to get some advice 
from

experienced users/mentors about a quick way to do it.


Quick - do you mean time to code, or execution time?

For each line in the control file add an item to a dictionary, with old 
value as key and new value as value.

For each line in the data file
 For each character in the line
   if in dictionary replace with corresponding value
 write line to output.

--
Bob Gailer
919-636-4239 Chapel Hill, NC

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


[Tutor] os.waitpid non spawned pid

2008-06-20 Thread John [H2O]

Hello, I would like to write a script that would have a command line option
of a pid# (known ahead of time). Then I want my script to wait to execute
until the pid is finished. How do I accomplish this?

I tried the following:
#!/usr/bin/env python

import os
import sys

def run_cmd(cmd):
   """RUN A BASH CMD"""
   import subprocess as sub
   p = sub.Popen( ['/bin/bash' , '-c' , cmd ],
 stdout = sub.PIPE , stderr = sub.STDOUT )
   output = p.stdout.read()
   return output

r=os.waitpid(sys.argv[1],0);

cmd = 'echo "Now %s has finished " ' %r

run_cmd(cmd)

But I get the following:

-bash-3.1$ ./waitpid.py 10132
Traceback (most recent call last):
  File "./waitpid.py", line 14, in ?
r=os.waitpid(int(sys.argv[1]),0);
OSError: [Errno 10] No child processes


-- 
View this message in context: 
http://www.nabble.com/os.waitpid-non-spawned-pid-tp18035187p18035187.html
Sent from the Python - tutor mailing list archive at Nabble.com.

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


Re: [Tutor] Checking the desktop environment

2008-06-20 Thread Timo
Thanks for your explanation. Apparently it's not possible to detect it
in all cases, but it would be nice to detect it for regular users, so
people who have a default install.

Well, my program needs a text-editor and a graphical box for
root-password. So it checks for the desktop environment so it could set
these things to gedit and gksudo for Gnome and kate and kdesu for KDE.

Timo



Alan Gauld schreef:
> "Timo" <[EMAIL PROTECTED]> wrote
>
>> Hello all, in my program I need to know what desktop environment the
>> user is running.
>
> A few years ago I would have said that meant you had a broken
> design since it was very bad practice for any program to depend
> on the users environment. nfortunately recent developments in
> Linux/X mean that the whole concept is broken that one more
> environmentally wawre program probably is no big deal!
>
> But there are caveats that mean you will probably never get
> it right in every case. The best you cvan probably do is detect
> if the environment is one of a fixed set  known to work with
> your code.#
>
> But bear in mind that the user can switch envirojnemts while
> your code is running, or may even be runningmultiple
> environments simultaneously on virtual windows etc.
>
> Thats why the users environment should be left as as
> something for the user and the programming environment
> for the programmer.
>
>> I figured this piece of code works, but apparently not
>> on every Linux distro. On Ubuntu it did the trick, but then I heard of
>> someone who runs SLiM that he get's an error with this.
>>
>> if os.environ['DESKTOP_SESSION'].startswith('kde'):
>>print "Running KDE"
>
> That would only find out if KDE was beiong used and only
> if the user (or cofig scripts) has not modified the variable.
>
>> So, does anyone know a water-proof solution for desktop environment
>> checking?
>
> I don't think such a thing can exist on a Unix/X system. An
> approximation will be the best you can get.
>
> Can you explain why you need to know?
> In most situations there should be a generic way to do it.
>
>
> Alan 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] Help! Character conversion from a rtf file.

2008-06-20 Thread wesley chun
> I'd like to learn the language by writing some simple programs rather than
> keep reading books. My first program will convert certain uni-code characters
> (let's say UTF-8) in an RTF file format based on a certain mapping
> in another RTF file that is called a "RTF Control file".
> :
> The program will write to a new file that contains a new set of mapped 
> characters.
> If a character form the original file is not found in the Control file, then 
> the program
> just write the same character to the new file.


hi chien,

and welcome to Python!  the Tutor list is here to help with any
learning questions you may have, but keep in mind that we cannot help
you with providing solutions to what we feel are education, high
school, college, or university course homework assignments, which is
what your problem sounds like.

the best advice i have for you at this time is to read in the
translation mapping into a Python dictionary, and then perform a
byte-to-byte traversal and conversion from the source file to the
destination file.

best of luck on your project!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
http://corepython.com

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


Re: [Tutor] Checking the desktop environment

2008-06-20 Thread W W
On Fri, Jun 20, 2008 at 1:48 PM, Timo <[EMAIL PROTECTED]> wrote:
> Thanks for your explanation. Apparently it's not possible to detect it
> in all cases, but it would be nice to detect it for regular users, so
> people who have a default install.
>
> Well, my program needs a text-editor and a graphical box for
> root-password. So it checks for the desktop environment so it could set
> these things to gedit and gksudo for Gnome and kate and kdesu for KDE.
>
> Timo

I would probably just ask the user which one they're running. It's
probably the easiest way.

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


[Tutor] File Stream Assignment?

2008-06-20 Thread FT

Hi!

I would like to know how a file can be open for a stream event?

I ask this question because of the SAPI 5 save a wave file and the only
way to do that is with a file stream. The file read is simple and uses the
isfilename flag, but the save file I can not find in all my searches, at
least for python.

Bruce

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


Re: [Tutor] Checking the desktop environment

2008-06-20 Thread Alan Gauld

"Timo" <[EMAIL PROTECTED]> wrote


Well, my program needs a text-editor


OK, That should be determined by checking the VISUAL environment
variable which is the standard Unix value that a user should set to
determine their preferred visual (ie full screen) text editor.
The EDITOR environrnent variable controls the default editor in text
mode., The standard defaults are vi and ed respectively. I used
to set xemacs and vi...


graphical box for root-password.


This is the sort of thing that I meant about modern Unices messing
things up. Why on earth should anyone need a user environment
specific su box. That should be a standard dialog controlled by the
app and the user environment controlling the GUI aspects. Too
many Windows programmers are working on Linux IMHO! ;-)

This is exactly why I dislike both Gnome and KDE. The only good
things about these is the provision of drag n drop protocols etc.
If only they had stuck to that.

these things to gedit and gksudo for Gnome and kate and kdesu for 
KDE.


But to do so would be to ignore the users preferences if they
have set their own choice in the "officially provided" variables.
You are thus allowing the environment to dictate to users what
tools they use rather than letting the user dictate the environment
in the true Unix style.

--
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] dollarize.py

2008-06-20 Thread Christopher Spears
I'm working on an exercise from Core Python Programming.  I need to create a 
function that takes a float value and returns the value as string rounded to 
obtain a financial amount.  Basically, the function does this:

dollarize(1234567.8901) returns-> $1,234,567,89

The function should allow for dollar signs, negative signs, and commas.  This 
is what I have so far:

def dollarize(amount):
negative_sign = 0
if amount[0] == '$':
amount = amount[1:]
elif amount[0] == '-':
negative_sign = 1
if amount[1] == '$':
amount = amount[2:]
else:
amount = amount[1:]
else:
pass
amount_list = amount.split(",")
final_amount = ""
for x in range(len(amount_list)):
final_amount = final_amount + amount_list[x]
dollar_float = float(final_amount)
dollar_rounded = round(dollar_float,2)
if negative_sign == 1:
dollar_string = "-$%.2f" % dollar_rounded
else:
dollar_string = "$%.2f" % dollar_rounded
return dollar_string


amount = raw_input("Enter an amount: ")
dollar_amount = dollarize(amount)
print dollar_amount   

I strip off the symbols, break the string apart, convert it to a float, and 
then round it.  I'm not sure how to add the commas back after the string has 
been converted to a rounded float value.  Any hints?


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


Re: [Tutor] Checking the desktop environment

2008-06-20 Thread Tiago Saboga
On Sat, Jun 21, 2008 at 01:00:36AM +0100, Alan Gauld wrote:
> "Timo" <[EMAIL PROTECTED]> wrote
>
>> graphical box for root-password.
>
> This is the sort of thing that I meant about modern Unices messing
> things up. Why on earth should anyone need a user environment
> specific su box. That should be a standard dialog controlled by the
> app and the user environment controlling the GUI aspects. Too
> many Windows programmers are working on Linux IMHO! ;-)

FWIW, Debian tries to address this mess with a su-to-root script which
tries to do the right thing, launching gksu, kdesu or simply su in a
new xterm. 

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


Re: [Tutor] os.waitpid non spawned pid

2008-06-20 Thread Martin Walsh
John [H2O] wrote:
> Hello, I would like to write a script that would have a command line option
> of a pid# (known ahead of time). Then I want my script to wait to execute
> until the pid is finished. How do I accomplish this?
> 
> I tried the following:
> #!/usr/bin/env python
> 
> import os
> import sys
> 
> def run_cmd(cmd):
>"""RUN A BASH CMD"""
>import subprocess as sub
>p = sub.Popen( ['/bin/bash' , '-c' , cmd ],
>  stdout = sub.PIPE , stderr = sub.STDOUT )
>output = p.stdout.read()
>return output
> 
> r=os.waitpid(sys.argv[1],0);

To approximate the behavior you're looking for, I've seen it suggested
that you can send signal number 0 to a non-child process until you get a
meaningful result. Never used this approach myself, but it might look
something like this:

import os, time
def waitncpid(pid):
while 1:
try:
os.kill(pid, 0)
time.sleep(1)
except OSError:
break

waitncpid(sys.argv[1])

Not sure what this would do on a windows machine. And, I suppose it is
possible that your process could end, and another start with the same
pid while sleeping between kill attempts, but this seems unlikely to me,
YMMV.

> 
> cmd = 'echo "Now %s has finished " ' %r
> 
> run_cmd(cmd)

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


Re: [Tutor] File Stream Assignment?

2008-06-20 Thread Kent Johnson
On Fri, Jun 20, 2008 at 5:47 PM, FT <[EMAIL PROTECTED]> wrote:

>I would like to know how a file can be open for a stream event?

What is a stream event?

>I ask this question because of the SAPI 5 save a wave file and the only
> way to do that is with a file stream. The file read is simple and uses the
> isfilename flag, but the save file I can not find in all my searches, at
> least for python.

I have no idea what you are talking about.

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


Re: [Tutor] dollarize.py

2008-06-20 Thread Martin Walsh
Christopher Spears wrote:
> I'm working on an exercise from Core Python Programming.  I need to create a 
> function that takes a float value and returns the value as string rounded to 
> obtain a financial amount.  Basically, the function does this:
> 
> dollarize(1234567.8901) returns-> $1,234,567,89


> 
> I strip off the symbols, break the string apart, convert it to a float, and 
> then round it.  I'm not sure how to add the commas back after the string has 
> been converted to a rounded float value.  Any hints?
> 

Quick and dirty attempt (and did I mention ugly?) ...

def addcommas(f):
  """
  This amounts to reversing everything left
  of the decimal, grouping by 3s, joining
  with commas, reversing and reassembling.
  """
  # assumes type(f) == float
  left, right = ('%0.2f' % f).split('.')
  rleft = [left[::-1][i:i+3] for i in range(0, len(left), 3)]
  return ','.join(rleft)[::-1] + '.' + right

I think you can also accomplish your broader goal with the locale module
(python2.5), though I don't know it very well.

import sys, locale
def dollarize(s):
s = ''.join([n for n in str(s) if n not in ('$', ',')])
if sys.platform == 'win32':
lcl = 'US'
else: # linux and mac?
lcl = 'en_US.UTF8'
locale.setlocale(locale.LC_MONETARY, lcl)
return locale.currency(float(s), 1, 1)

print dollarize(12345678.)
# $12,345,679.00
print dollarize('123456780.0999')
# $123,456,780.10
print dollarize('$12345670.')
# $12,345,671.00
print dollarize('$12,345,678.123')
# $12,345,678.12

HTH,
Marty

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