[Tutor] Writing to Windows 64-bit event log

2012-06-18 Thread Johan Geldenhuys
Hi there,



I've looked all over, but couldn't find any help as far as an API goes to
log to a 64-bit Windows7 machine event log.



My Python version is 2.7.1 and I am running the 32-bit Windows version on a
Windows 7 laptop.



Is there a way I can log entries to the Windows event log on my laptop from
my Python application?



Thanks

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


Re: [Tutor] urllib2 sslerror

2011-10-09 Thread Johan Geldenhuys
Hi,

The connection I am making is not going through a proxy, but directly to the
device over https.

 

Like I said in the original post, it works most of the time, but not always
and it I can't reproduce the error on-demand.

 

In this line:html_content = return_object.read(), will it read binary
data or is that only applicable when I write it to a file to write it as
binary?

 

Any help would be appreciated.

 

Thanks

 

Johan

 

From: nehal dattani [mailto:nehal.datt...@gmail.com] 
Sent: Friday, 7 October 2011 7:49 PM
To: Johan Geldenhuys
Subject: Re: [Tutor] urllib2 sslerror

 

Hi Johan,

If you are using http proxy, this may be helpful.

http://stackoverflow.com/questions/1030113/does-urllib2-in-python-2-6-1-supp
ort-proxy-via-https

Regards,
Nehal Dattani

On Fri, Oct 7, 2011 at 11:14 AM, Johan Geldenhuys 
wrote:

Hi everybody,

Almost weekend, hang in there.

I need some advice and hope somebody can help me.

I have the follow piece of code that I use to get some data from a https
webpage.

---
< some other stuff up here>
try:
   return_object = urllib2.urlopen(theurl)
   html_content = return_object.read()

   now = time.strftime("%Y%m%d%H%M%S")
   img_file = "%s_%s.jpg"% (location, now)
   f = open(img_file, 'wb')
   f.write(html_content)
   f.close()
   file = img_file
except Exception, e:
   print e


---

Sometimes I get the following error and I don't know why. It occurs very
randomly and is hard or nearly impossible to reproduce (maybe there is
somebody who knows how to create it).

---
Traceback (most recent call last):
 File "/var/ai-muse/jail/pkgdb/camimage/getimage.py", line 74, in run
   return_object = urllib2.urlopen(self.theurl)
 File "/usr/lib/python2.2/urllib2.py", line 138, in urlopen
 File "/usr/lib/python2.2/urllib2.py", line 322, in open
 File "/usr/lib/python2.2/urllib2.py", line 301, in _call_chain
 File "/usr/lib/python2.2/urllib2.py", line 792, in https_open
 File "/usr/lib/python2.2/urllib2.py", line 779, in do_open
 File "/usr/lib/python2.2/urllib2.py", line 342, in error
 File "/usr/lib/python2.2/urllib2.py", line 301, in _call_chain
 File "/usr/lib/python2.2/urllib2.py", line 611, in http_error_401
 File "/usr/lib/python2.2/urllib2.py", line 590, in http_error_auth_reqed
 File "/usr/lib/python2.2/urllib2.py", line 600, in retry_http_basic_auth
 File "/usr/lib/python2.2/urllib2.py", line 322, in open
 File "/usr/lib/python2.2/urllib2.py", line 301, in _call_chain
 File "/usr/lib/python2.2/urllib2.py", line 792, in https_open
 File "/usr/lib/python2.2/urllib2.py", line 774, in do_open
 File "/usr/lib/python2.2/httplib.py", line 752, in getreply
 File "/usr/lib/python2.2/httplib.py", line 593, in getresponse
 File "/usr/lib/python2.2/httplib.py", line 99, in __init__
 File "/usr/lib/python2.2/httplib.py", line 628, in makefile
sslerror: (5, 'EOF occurred in violation of protocol')



Any idea why it happens randomly and how I can check the cause?
I read on a Google search page that one guy had the same issue and traced it
back to some characters in the data he was receiving. Could that cause it?

Thanks in advance
 
Johan


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

 

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


[Tutor] urllib2 sslerror

2011-10-07 Thread Johan Geldenhuys
Hi everybody,

Almost weekend, hang in there.

I need some advice and hope somebody can help me.

I have the follow piece of code that I use to get some data from a https
webpage.

---
< some other stuff up here>
try:
return_object = urllib2.urlopen(theurl)
html_content = return_object.read()
  
now = time.strftime("%Y%m%d%H%M%S")
img_file = "%s_%s.jpg"% (location, now)
f = open(img_file, 'wb')
f.write(html_content)
f.close()
file = img_file
except Exception, e:
print e


---

Sometimes I get the following error and I don't know why. It occurs very
randomly and is hard or nearly impossible to reproduce (maybe there is
somebody who knows how to create it).

---
Traceback (most recent call last):
  File "/var/ai-muse/jail/pkgdb/camimage/getimage.py", line 74, in run
return_object = urllib2.urlopen(self.theurl)
  File "/usr/lib/python2.2/urllib2.py", line 138, in urlopen
  File "/usr/lib/python2.2/urllib2.py", line 322, in open
  File "/usr/lib/python2.2/urllib2.py", line 301, in _call_chain
  File "/usr/lib/python2.2/urllib2.py", line 792, in https_open
  File "/usr/lib/python2.2/urllib2.py", line 779, in do_open
  File "/usr/lib/python2.2/urllib2.py", line 342, in error
  File "/usr/lib/python2.2/urllib2.py", line 301, in _call_chain
  File "/usr/lib/python2.2/urllib2.py", line 611, in http_error_401
  File "/usr/lib/python2.2/urllib2.py", line 590, in http_error_auth_reqed
  File "/usr/lib/python2.2/urllib2.py", line 600, in retry_http_basic_auth
  File "/usr/lib/python2.2/urllib2.py", line 322, in open
  File "/usr/lib/python2.2/urllib2.py", line 301, in _call_chain
  File "/usr/lib/python2.2/urllib2.py", line 792, in https_open
  File "/usr/lib/python2.2/urllib2.py", line 774, in do_open
  File "/usr/lib/python2.2/httplib.py", line 752, in getreply
  File "/usr/lib/python2.2/httplib.py", line 593, in getresponse
  File "/usr/lib/python2.2/httplib.py", line 99, in __init__
  File "/usr/lib/python2.2/httplib.py", line 628, in makefile
sslerror: (5, 'EOF occurred in violation of protocol')



Any idea why it happens randomly and how I can check the cause?
I read on a Google search page that one guy had the same issue and traced it
back to some characters in the data he was receiving. Could that cause it?

Thanks in advance
  
Johan 


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


Re: [Tutor] urllib2 issue getting realm

2011-08-31 Thread Johan Geldenhuys
Thanks Sanders
Will give that a go

Johan
Sent from my iPhone 4

On 31/08/2011, at 23:03, Sander Sweers  wrote:

> On 31 August 2011 14:27, Johan Geldenhuys  wrote:
>> On 31/08/2011, at 22:09, Sander Sweers  wrote:
>>> On 31 August 2011 09:46, Johan Geldenhuys  wrote:
>>>> I am trying to use a very simple piece of code to get the realm from
>>>> different HTTPS URLs.
>>>> 
>>>> This realm is essential for successful authentication on the HTTPS session.
>>> 
>>> I think you got 2 things mixed up, http authentication and encrypted
>>> http (https). Just having a https url does not mean you need to
>>> authenticate. Take 'https://mail.google.com' as an example.
>>> 
>>>> If have to run this for a few different hosts and capture the realm.
>>>> For one host, it works perfectly, but when I try the same code to get the
>>>> next realm, it fails. I suspect that I need to close some type of
>>>> connections or something, but I can't put my finger on it.
>>> 
>>> 
>>>> For the next one:
>>>> 
>>>>>>> try:
>>>> ... req = urllib2.Request(URL % ips[1])
>>>> ... handle = urllib2.urlopen(req)
>>>> ... except IOError, e:
>>>> ... print `e`
>>>> ...
>>>>>>> 
>>>> 
>>>> See, no "e" printed which means that something worked. The exception didn't
>>>> happen and I don't know why...Anybody?
>>> 
>>> Yes, when you type the url into your browser. I suspect it does not
>>> ask you to authenticate via http authentication. Therefor no exception
>>> is raised and you never print the headers.
> 
> Top posting is evil ;-).
> 
>> Focusing on the code below, do you know why it would raise the exception for 
>> the first
>> IP and not for the second?
> 
> Run this and you should see which error is being raise. Do note we
> catch urllib2.HTTPError instead of IOError.
> 
> try:
>req = urllib2.Request(URL % ips[1])
>handle = urllib2.urlopen(req)
>print 'Success'
>print handle.getcode()
>print handle.headers
> except urllib2.HTTPError as e:
>print 'Exception caught'
>print e
>print e.getcode()
>print e.hdrs
> 
> Greets
> Sander
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] urllib2 issue getting realm

2011-08-31 Thread Johan Geldenhuys
Focusing on the code below, do you know why it would raise the exception for 
the first IP and not for the second?

Thank you
Johan
Sent from my iPhone 4

On 31/08/2011, at 22:09, Sander Sweers  wrote:

> On 31 August 2011 09:46, Johan Geldenhuys  wrote:
>> I am trying to use a very simple piece of code to get the realm from
>> different HTTPS URLs.
>> 
>> This realm is essential for successful authentication on the HTTPS session.
> 
> I think you got 2 things mixed up, http authentication and encrypted
> http (https). Just having a https url does not mean you need to
> authenticate. Take 'https://mail.google.com' as an example.
> 
>> If have to run this for a few different hosts and capture the realm.
>> For one host, it works perfectly, but when I try the same code to get the
>> next realm, it fails. I suspect that I need to close some type of
>> connections or something, but I can't put my finger on it.
> 
> 
>> For the next one:
>> 
>>>>> try:
>> ... req = urllib2.Request(URL % ips[1])
>> ... handle = urllib2.urlopen(req)
>> ... except IOError, e:
>> ... print `e`
>> ...
>>>>> 
>> 
>> See, no "e" printed which means that something worked. The exception didn't
>> happen and I don't know why...Anybody?
> 
> Yes, when you type the url into your browser. I suspect it does not
> ask you to authenticate via http authentication. Therefor no exception
> is raised and you never print the headers.
> 
> Greets
> Sander
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] urllib2 issue getting realm

2011-08-31 Thread Johan Geldenhuys
Hi everybody,

I am trying to use a very simple piece of code to get the realm from
different HTTPS URLs.

This realm is essential for successful authentication on the HTTPS session.

If have to run this for a few different hosts and capture the realm.
For one host, it works perfectly, but when I try the same code to get the
next realm, it fails. I suspect that I need to close some type of
connections or something, but I can't put my finger on it.

This what I try:

>>> ips = ['192.168.10.190', '192.168.10.191', '192.168.10.192',
'192.168.10.193']
>>> URL = "https://%s/axis-cgi/jpg/image.cgi?resolution=1280x800";
>>> import urllib2
>>> try:
... req = urllib2.Request(URL % ips[0])
... handle = urllib2.urlopen(req)
... except IOError, e:
... print `e`
... 
HTTPError()
>>> 
>>> e
HTTPError()
>>> authline = e.headers.get('www-authenticate', '')
>>> authline
'Digest realm="AXIS_00408CB71F14",
nonce="0002c497Y6450989253d0ea85587e89821031c60ab9768", stale=FALSE,
qop="auth", Basic realm="AXIS_00408CB71F14"'
>>>
>>> handle
  File "", line 1, in 
'''  : name 'handle' is not defined '''
>>> req

>>> req.host
'192.168.10.190'
>>>



At this point, I am happy. It worked. I expect the try to fail to get the
exception.

For the next one:

>>> try:
... req = urllib2.Request(URL % ips[1])
... handle = urllib2.urlopen(req)
... except IOError, e:
... print `e`
... 
>>>

See, no "e" printed which means that something worked. The exception didn't
happen and I don't know why...Anybody?

I tried doing this:

>>> del req
>>> del handle
>>> del e

But with the same result:

>>> try:
... req = urllib2.Request(URL % ips[1])
... handle = urllib2.urlopen(req)
... except IOError, e:
... print `e`
... 
>>> e
  File "", line 1, in 
'''  : name 'e' is not defined '''
>>> req

>>> handle
>




Regards 
  
Johan 



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


Re: [Tutor] Confirmation if command worked

2011-08-24 Thread Johan Geldenhuys
Hi Christian,

 

Thanks for that. I'll give it a shot and see if I can catch the error.

 

Lekker dag

 

 

Johan

 

From: Christian Witts [mailto:cwi...@compuscan.co.za] 
Sent: Thursday, 25 August 2011 4:25 PM
To: Johan Geldenhuys
Cc: tutor@python.org
Subject: Re: [Tutor] Confirmation if command worked

 

On 2011/08/25 07:51 AM, Johan Geldenhuys wrote: 

Hi all,
 
 
I have the following code that uses pexpect to execute a system command. My
problem is, I don't know how to identify if the command was successfully
executed.
The code works as it is to execute the SCP command, but it executes
regardless if the SCP session can actually connect to something.
 
Thanks
 
def doScp(files):


logger.log("Files to get: " + `files`)
fNames = ' '.join(files)

cmd = 'scp %s %s@%s:%s%s' % (fNames,
SCP_USERNAME,
SCP_HOST,
SCP_IMG_FILE_DIR,
SCP_IMG_FILE_PATH)

logger.log("Sending: " + cmd)

child = pexpect.spawn(cmd)

i = child.expect(['assword:', 'yes/no'], timeout=30)
if i == 0:
child.sendline(SCP_PASSWD)

elif i == 1:
child.sendline("yes")
child.expect("assword:", timeout=30)
child.sendline(SCP_PASSWD)

data = child.read()

if data != None:
success = True
else:
success = False
child.close()

logger.log("Files sent to SCP host")

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


Once you call child.close() the exit and signal status will be stored in
.exitstatus and .signalstatus, for a normal exit of the program .exitstatus
will store the return code from SCP as per [1] [2] [3] and .signalstatus
will be None.  If SCP was terminated with a signal then .exitstatus will be
None and .signalstatus will contain the signal value.  Info found in the
docs [4].

So the changes to your code will be:


data = child.read()
child.close()

if child.exitstatus and child.exitstatus == 0:
success = True
else:
success = False


I'll leave putting in handling of failed error codes and abnormal
termination to you.

[1] http://support.attachmate.com/techdocs/2116.html
[2] http://support.attachmate.com/techdocs/2487.html
[3] http://support.attachmate.com/techdocs/2285.html
[4] http://pexpect.sourceforge.net/pexpect.html

-- 

Christian Witts
Python Developer

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


[Tutor] Confirmation if command worked

2011-08-24 Thread Johan Geldenhuys
Hi all,


I have the following code that uses pexpect to execute a system command. My
problem is, I don't know how to identify if the command was successfully
executed.
The code works as it is to execute the SCP command, but it executes
regardless if the SCP session can actually connect to something.

Thanks

def doScp(files):


logger.log("Files to get: " + `files`)
fNames = ' '.join(files)

cmd = 'scp %s %s@%s:%s%s' % (fNames,
SCP_USERNAME,
SCP_HOST,
SCP_IMG_FILE_DIR,
SCP_IMG_FILE_PATH)

logger.log("Sending: " + cmd)

child = pexpect.spawn(cmd)

i = child.expect(['assword:', 'yes/no'], timeout=30)
if i == 0:
child.sendline(SCP_PASSWD)

elif i == 1:
child.sendline("yes")
child.expect("assword:", timeout=30)
child.sendline(SCP_PASSWD)

data = child.read()

if data != None:
success = True
else:
success = False
child.close()

logger.log("Files sent to SCP host")

return success





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


[Tutor] Resend: Using pexpect to SCP files

2011-07-19 Thread Johan Geldenhuys
Resend in text format

Hi there all,

I am using pexpect in a script to SCP files to a inux server.
Here is a snippet from the code:

def doScp(self, user, password, host, path, files):
    
    fNames = " ".join(files)
    self.logger.log('Running command for %s' % fNames)
    try:
    
    self.child = pexpect.spawn("scp %s %s@%s:%s"%(fNames, user, host,
path))
# The script times out here: 
    i = self.child.expect(['assword:', r"yes/no"], timeout=30)
    except:
    self.logger.logException()
    
    if i==0:
    self.logger.log('Sending password')
    self.child.sendline(password)
    elif i==1:
    self.logger.log('Sending yes and password')
    self.child.sendline("yes")
    self.child.expect("assword:", timeout=30)
    self.child.sendline(password)
    try:
    data = self.child.read()
    self.logger.log(`data`)
    except:
    self.logger.logException()
    
    self.child.expect(PROMPT)
    self.logger.log('Done with SCP')


This executes at the line " i = self.child.expect(['assword:', r"yes/no"],
timeout=30)". From what I can see using tcpdump on the linux side, the scp
traffic is going into the linux server, but it is not sending anything back.
Is there anything obvious wrong here and is there a way I can see the exact
command sent to out?

The reason I chose to use pexpect is that is a pure Python method for doing
interactive sessions for scp. 
Is there a different way of doing scp in a pure pythin self contained
module? Piramiko is not an option because I cannot install it on the device
I run my script on.

Thank for helping.

Johan


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


[Tutor] Using pexpect to SCP files

2011-07-19 Thread Johan Geldenhuys
Hi there all,

 

I am using pexpect in a script to SCP files to a inux server.

Here is a snippet from the code:

 

def doScp(self, user, password, host, path, files):



fNames = " ".join(files)

self.logger.log('Running command for %s' % fNames)

try:



self.child = pexpect.spawn("scp %s %s@%s:%s"%(fNames, user,
host, path)) 

i = self.child.expect(['assword:', r"yes/no"], timeout=30)

except:

self.logger.logException()



if i==0:

self.logger.log('Sending password')

self.child.sendline(password)

elif i==1:

self.logger.log('Sending yes and password')

self.child.sendline("yes")

self.child.expect("assword:", timeout=30)

self.child.sendline(password)

try:

data = self.child.read()

self.logger.log(`data`)

except:

self.logger.logException()



self.child.expect(PROMPT)

self.logger.log('Done with SCP')

 

 

This executes to the line in red and then times out. From what I can see
using tcpdump on the linux side, the scp traffic is going into the linux
server, but it is not sending anything back.

Is there anything obvious wrong here and is there a way I can see the exact
command sent to out?

 

The reason I chose to use pexpect is that is a pure Python method for doing
interactive sessions for scp. 

Is there a different way of doing scp in a pure pythin self contained
module? Piramiko is not an option because I cannot install it on the device
I run my script on.

 

Thank for helping.

 

Johan

 

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


Re: [Tutor] sftp get single file

2011-06-21 Thread Johan Geldenhuys
Hi all,
This topic is old, but I have a similar issue and I know everybody will say I 
should use piramiko, but it is not that simple.

The device I have to run my python scripts on is a simple, small, scaled down 
version of Suse linux and I can't install other packages like piramiko.
All the files I need to use that is not part of Python 2.7 must be included in 
my package.

With the above in mind, what can I use to open SFTP to a server and transfer a 
file?

Thanks

Johan


-Original Message-
From: tutor-bounces+johan=accesstel.com...@python.org 
[mailto:tutor-bounces+johan=accesstel.com...@python.org] On Behalf Of Sander 
Sweers
Sent: Saturday, 18 July 2009 1:43 AM
To: Matt Herzog
Cc: Python List
Subject: Re: [Tutor] sftp get single file

2009/7/17 Matt Herzog :
> Hello All.
>
> I need to use paramiko to sftp get a single file from a remote server.
> The remote file's base name will be today's date (%Y%m%d) dot tab.
> I need help joining the today with the .tab extension. Do I need globbing?
>
> example: 20090716.tab
>
> #!/usr/bin/env python
> import paramiko
> import glob
> import os
> import time
> hostname = 'sftp.booboo.com'
> port = 22
> username = 'booboo'
> password = '07N4219?'
> # glob_pattern='*.tab'
> today = time.strftime("%Y%m%d")
> remotepath = today.tab
> localpath = '/home/data/text'
>
> if __name__ == "__main__":
>t = paramiko.Transport((hostname, port))
>t.connect(username=username, password=password)
>sftp = paramiko.SFTPClient.from_transport(t)
>sftp.get(remotepath, localpath)
>t.close()
> --

You don't need glob if you know in advance what the filename is. Print
example below.

---
import time

today = time.localtime()
datestr = time.strftime("%Y%m%d",today)
ext = ".tab"

print datestr + ext
---

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

Checked by AVG - www.avg.com 
Version: 8.5.387 / Virus Database: 270.13.17/2242 - Release Date: 07/16/09 
18:00:00

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


Re: [Tutor] Saving data as jpg file

2011-06-12 Thread Johan Geldenhuys
Hi,

I tried using the "wb" to create and write the file. In a simple test I did
to open an existing jpg file I know is good, putting the data in my new file
and closing it, it worked.

I don't have access to the camera now, but will try it tomorrow.

Thanks

Johan


-Original Message-
From: tutor-bounces+johan=accesstel.com...@python.org
[mailto:tutor-bounces+johan=accesstel.com...@python.org] On Behalf Of Steven
D'Aprano
Sent: Sunday, 12 June 2011 10:14 AM
To: Tutor@python.org
Subject: Re: [Tutor] Saving data as jpg file

Johan Geldenhuys wrote:
> Hi,
> 
> I have a Axis IP camera that I can send a HTTP command to and the data
> returned is the jpg image.
> 
> When I get this data, I want to save it as a .jpg file, but I think my
> encoding is not correct, because the image is all distorted.

Are you sure that the data produced by the camera isn't already 
distorted? I would expect that anything you do wrong with the jpg file 
(such as the wrong encoding) will corrupt the file, not just distort it.

But I see that you are opening the output file in text mode, and you are 
on Windows:

img_file = "E:\work\img1.jpg"
f = open(img_file, 'w')


You need to open the file in binary mode, as you are writing binary data:

f = open(img_file, 'wb')

My guess is that this is your problem.


Also, using backslashes in pathnames is tricky. You are lucky that the 
above works correctly, but if you move the file, it might not continue 
to work. Python uses backslashes to escape special characters, e.g. \n 
means newline. Try using this as a file name, and you will see what I mean:

example = 'C:\temp\report.txt'

So you need to be *very* careful of using backslashes in pathnames. The 
best practice is to either:


* escape all the backslashes: img_file = "E:\\work\\img1.jpg"

* or use forward slashes: img_file = "E:/work/img1.jpg"


Windows will happily accept / instead of \ and you will save yourself a 
lot of grief in the future.


> I looked at using PIL, but the device I will install my script on can't be
> used to install other packages like this. I'll have to include the modules
> in my own folder.

If you can install modules in your own folder, you could put PIL in your 
folder and then install it.



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

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


[Tutor] Saving data as jpg file

2011-06-11 Thread Johan Geldenhuys
Hi,

I have a Axis IP camera that I can send a HTTP command to and the data
returned is the jpg image.

When I get this data, I want to save it as a .jpg file, but I think my
encoding is not correct, because the image is all distorted.

 

I looked at using PIL, but the device I will install my script on can't be
used to install other packages like this. I'll have to include the modules
in my own folder.

 

Here is my simple code that I started testing with.

 

 

"""

import urllib2

 

# Create an OpenerDirector with support for Basic HTTP Authentication...

auth_handler = urllib2.HTTPBasicAuthHandler()

auth_handler.add_password('.', '192.168.10.190', 'root', 'pass')

opener = urllib2.build_opener(auth_handler)

 

# ...and install it globally so it can be used with urlopen.

urllib2.install_opener(opener)

 

return_object =
urllib2.urlopen('http://192.168.10.190/axis-cgi/jpg/image.cgi?resolution=320
x240&squarepixel=1')

 

html_content = return_object.read()

img_file = "E:\work\img1.jpg"

f = open(img_file, 'w')

f.write(html_content)

f.close()

""" 

 

Any ideas what type of encoding I have to use if that is the problem?

 

Thanks

 

Johan

 

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


[Tutor] XML: changing value of elements and writing to a file

2009-07-16 Thread Johan Geldenhuys
Thanks Stefan (decided to continue with a new thread name),

I basically wants to create a loop that creates a tree, appends it to the
previous tree and write it all to one file...If that makes sense.

At the moment my tree is something like this:
"""

WhatEver

"""

Now I want to read a dictionary from somewhere and put new values in the
name and description. I know how to do that. Now I want to create a loop
that creates a new tree:
"""

HowDee

"""

Now I want to append these to the data I want to write to a single xml file.

"""

WhatEver


HowDee

"""

I was thinking of creating a new root element and appending each as a
subelement and then writing the root element to the file...

I just need some pointers on how to do that. 

Thanks

Johan



-Original Message-
From: tutor-bounces+johan=accesstel.com...@python.org
[mailto:tutor-bounces+johan=accesstel.com...@python.org] On Behalf Of Stefan
Behnel
Sent: Thursday, July 16, 2009 7:23 PM
To: tutor@python.org
Subject: Re: [Tutor] XML: changing value of elements

Hi,

a new question usually merits a new thread. Especially after a longer time,
replies to older threads tend to remain unread as people simply don't
scroll down far enough to notice them.

You were lucky. :)


Johan Geldenhuys wrote:
> I have another question about writing the xml tree to a file.
> 
> Now, I have parsed and changed my xml tree, but I want to create the same
> tree multiple times with different values and write it to one file.
> 
> 
> Let's use this code:
> 
>   import xml.etree.ElementTree as ET
>   doc = ET.parse('signal1.xml')
>   signal_node = doc.getroot()[0]
>   signal_node.set('name', 'Test_Name')
> 
> I have this in a function and it returns the signal_node everytime I call
> it, but with a different values. 
> 
> So, How do I take the returned xml and write that to one xml file?

I'm not sure what you mean here. Do you mean: "multiple XML trees into a
single file"? Or each in its own file?

BTW, you don't need to re-parse the tree if all you want is to modify it
and write it back out. You can either keep changing the tree and write it
out multiple times, or deep-copy it (or parts of it) and start over for
each step. Although I guess that parsing might be faster than deep-copying,
especially for ElementTree.

Stefan

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

Checked by AVG - www.avg.com 
Version: 8.5.387 / Virus Database: 270.13.16/2240 - Release Date: 07/15/09
17:58:00

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


Re: [Tutor] XML: changing value of elements

2009-07-15 Thread Johan Geldenhuys
I have another question about writing the xml tree to a file.

Now, I have parsed and changed my xml tree, but I want to create the same
tree multiple times with different values and write it to one file.


Let's use this code:

import xml.etree.ElementTree as ET
doc = ET.parse('signal1.xml')
signal_node = doc.getroot()[0]
signal_node.set('name', 'Test_Name')

I have this in a function and it returns the signal_node everytime I call
it, but with a different values. 

So, How do I take the returned xml and write that to one xml file?

Thanks

Johan

-Original Message-
From: tutor-bounces+johan=accesstel.com...@python.org
[mailto:tutor-bounces+johan=accesstel.com...@python.org] On Behalf Of Stefan
Behnel
Sent: Thursday, June 11, 2009 4:37 PM
To: tutor@python.org
Subject: Re: [Tutor] XML: changing value of elements

Hi,

it's funny how many times I see Python users go: "I have an XML problem, so
I'll use minidom." Because then they have two problems.


Johan Geldenhuys wrote:
> I have a rather complex XML file and I need to change some values inside
> this file.
> 
> So far I have been using minidom, but I can't find the thing I am looking
> for.
> 
> My code so far:
> """
> from xml.dom import minidom
> 
> xmlFile = 'signal1.xml'
> xmlDocument = minidom.parse(xmlFile)
> 
> SignalsNode = xmlDocument.firstChild
> signalNode = SignalsNode.childNodes[1]
> 
> signalNode.removeAttribute("name")
> signalNode.setAttribute("name", "Test_Name")
> signalNode.getAttribute("name")
> 
> descElem = signalNode.childNodes[1]

That is a lot of code just to say

import xml.etree.ElementTree as ET
doc = ET.parse('signal1.xml')
signal_node = doc.getroot()[0]
signal_node.set('name', 'Test_Name')


> I know how to manipulate the value of the attributes, but I can't seem to
> change the values of eg: "Description"

description = signal_node[0]
description.text = "New value"

> Snippet from my XML file:
> 
> """
> 
>  
> 
>   -  

What's that "" bit?


>   -  name="Model_X" type="Flyer">
> 
>   Some description 
> 
>Model_X  
> 
>
> 
>   - 
> 
>   normal 
> 
>   Model X 1 
> 
>   
> 
>   -  type="close">
> 
>   minor 
> 
>Model X 2 
> 
>   
> 
>   
> 
>   
> """

Stefan

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

No virus found in this incoming message.
Checked by AVG - http://www.avg.com 
Version: 8.0.138 / Virus Database: 270.12.93/2206 - Release Date: 6/27/2009
5:55 PM

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


Re: [Tutor] XML: changing value of elements

2009-06-11 Thread Johan Geldenhuys
Thanks for the reply. Have been waiting a few days.

When I started out, I still had Python 2.4 and etree is not available in
that version.

This part : 
must have snicked in wihen I copied the XML code. Sorry, but that is the
location of my original XML file.

I'll try your stuff and see how it goes.

Thanks
 
Johan 

-Original Message-
From: tutor-bounces+johan=accesstel.com...@python.org
[mailto:tutor-bounces+johan=accesstel.com...@python.org] On Behalf Of Stefan
Behnel
Sent: Thursday, 11 June 2009 16:37 PM
To: tutor@python.org
Subject: Re: [Tutor] XML: changing value of elements

Hi,

it's funny how many times I see Python users go: "I have an XML problem, so
I'll use minidom." Because then they have two problems.


Johan Geldenhuys wrote:
> I have a rather complex XML file and I need to change some values inside
> this file.
> 
> So far I have been using minidom, but I can't find the thing I am looking
> for.
> 
> My code so far:
> """
> from xml.dom import minidom
> 
> xmlFile = 'signal1.xml'
> xmlDocument = minidom.parse(xmlFile)
> 
> SignalsNode = xmlDocument.firstChild
> signalNode = SignalsNode.childNodes[1]
> 
> signalNode.removeAttribute("name")
> signalNode.setAttribute("name", "Test_Name")
> signalNode.getAttribute("name")
> 
> descElem = signalNode.childNodes[1]

That is a lot of code just to say

import xml.etree.ElementTree as ET
doc = ET.parse('signal1.xml')
signal_node = doc.getroot()[0]
signal_node.set('name', 'Test_Name')


> I know how to manipulate the value of the attributes, but I can't seem to
> change the values of eg: "Description"

description = signal_node[0]
description.text = "New value"

> Snippet from my XML file:
> 
> """
> 
>  
> 
>   -  

What's that "" bit?


>   -  name="Model_X" type="Flyer">
> 
>   Some description 
> 
>Model_X  
> 
>
> 
>   - 
> 
>   normal 
> 
>   Model X 1 
> 
>   
> 
>   -  type="close">
> 
>   minor 
> 
>Model X 2 
> 
>   
> 
>   
> 
>   
> """

Stefan

___
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] XML: changing value of elements

2009-06-09 Thread Johan Geldenhuys
Hi all,

 

I have a rather complex XML file and I need to change some values inside
this file.

So far I have been using minidom, but I can't find the thing I am looking
for.

 

My code so far:

 

"""

from xml.dom import minidom

 

xmlFile = 'signal1.xml'

xmlDocument = minidom.parse(xmlFile)

 

SignalsNode = xmlDocument.firstChild

signalNode = SignalsNode.childNodes[1]

 

signalNode.removeAttribute("name")

signalNode.setAttribute("name", "Test_Name")

signalNode.getAttribute("name")

 

descElem = signalNode.childNodes[1]

 

"""

 

I know how to manipulate the value of the attributes, but I can't seem to
change the values of eg: "Description"

 

 

Snippet from my XML file:

 

"""

 

  -  

  - 

  Some description 

   Model_X  

   

  - 

  normal 

  Model X 1 

  

  - 

  minor 

   Model X 2 

  

  

  

"""

 

Any suggestions on how to change some of the values of the elements?

 

Thanks

 

Johan

 

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


Re: [Tutor] No Blank Separator between Date and Time Valid?

2008-09-11 Thread Johan Geldenhuys
It all depends how you specify the format of the time you want, look at the
example. 

 

>>> time.strftime('%Y%M%D%H%M%S')

'200820092030'

>>> 

>>> 

>>> time.strftime('%Y%M%D %H%M%S')

'200820 092055'

>>> 

 

Notice in the second statement, I added the space separator between the %D
and %H.

 

This statement doesn’t fail and the exception doesn’t happen: date1 =
datetime(*(time.strptime(d1, formatin)[0:6]))



 

  _  

From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] On Behalf Of Wayne
Watson
Sent: Friday, 12 September 2008 2:56 AM
To: tutor@python.org
Subject: [Tutor] No Blank Separator between Date and Time Valid?

 

This program segment allows an invalid date to go undetected. See below.

from datetime import datetime
import time

def set_time_stamp(d1):
# /mm/dd hh:mm:ss in, vmmdd_hhmmss.27 out
formatin = '%Y/%m/%d %H:%M:%S'
d1 = d1.lstrip()
try:
date1 = datetime(*(time.strptime(d1, formatin)[0:6]))
except ValueError:
print; print "Invalid date input. Use /mm/dd hh:mm:ss."
return False
formatout = '%Y%m%d_%H%M%S'
dout = date1.strftime(formatout)
print "dout: ",dout
return 'v'+date1.strftime(formatout)+".27"

keyopt = 0
while keyopt == 0:
print
date_time = raw_input("Enter date and time: ")
if date_time == "end":
break
file_prefix = set_time_stamp(date_time)
print "prefix: ",file_prefix
if file_prefix == False:
continue
print "OK: ", file_prefix
#write_pair(file_prefix, date_time)

print; print "bye..."

Results:

Enter date and time: 2008/1/1 00:00:30 <- Valid input OK
dout:  20080101_30
prefix:  v20080101_30.27
OK:  v20080101_30.27

Enter date and time: 2008/1/100:00:30 <- Why is this valid. The fields
are not spearated.
dout:  20080110_30
prefix:  v20080110_30.27
OK:  v20080110_30.27

Enter date and time: 2008/1/1 x00:00:30  <- Invalid input caught

Invalid date input. Use /mm/dd hh:mm:ss.
prefix:  False

Enter date and time: end

bye ...

-- 



   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

  "If voting made any difference they wouldn't let us do it." 
-- Mark Twain

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


Re: [Tutor] Support for datetime module

2008-09-08 Thread Johan Geldenhuys
I managed to get a version of the datetime module in Python and used in my
package. It works fine.

Thanks
Johan

-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] On Behalf Of
Hansen, Mike
Sent: Tuesday, 9 September 2008 7:14 AM
To: tutor@python.org
Subject: Re: [Tutor] Support for datetime module

 

> -Original Message-
> From: [EMAIL PROTECTED] 
> [mailto:[EMAIL PROTECTED] On 
> Behalf Of Kent Johnson
> Sent: Saturday, September 06, 2008 7:08 AM
> To: [EMAIL PROTECTED]
> Cc: tutor@python.org
> Subject: Re: [Tutor] Support for datetime module
> 
> On Sat, Sep 6, 2008 at 2:42 AM, Johan Geldenhuys 
> <[EMAIL PROTECTED]> wrote:
> > Hi all,
> >
> > I have want to use the datetime module on a system with ver 
> 2.2.3 installed.
> > I know it's very old, but that's what I have to deal with 
> and can't upgrade.
> > So please don't suggest that.
> >
> > As you know datetime was available from version 2.3.
> >
> >
> >
> > I want to know where can I get the datetime module so that 
> I can include it
> > in my package that I use on my device?
> 
> datetime is implemented in C so getting the version from 2.3 to work
> on 2.2 might be difficult.
> 
> Apparently the version in the std lib is derived from a Python version
> that was part of Zope, this might be helpful if you can find the
> source it refers to:
> http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
> 
> Kent

This is probably moot since the OP solved the issue using other means, but I
thought datetime was based on mxdatetime. Even if it isn't, mxdatetime
supports Python 2.1 and newer. 

http://www.egenix.com/products/python/mxBase/mxDateTime/

Mike
___
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] Support for datetime module

2008-09-07 Thread Johan Geldenhuys
I can get the time up to the closest second with the time module, but not to
the millisecond.
When I use time.strftime, I don't know how many milliseconds are left over
to use them.



-Original Message-
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Kent
Johnson
Sent: Sunday, 7 September 2008 21:04 PM
To: [EMAIL PROTECTED]
Cc: tutor@python.org
Subject: Re: [Tutor] Support for datetime module

On Sun, Sep 7, 2008 at 6:17 AM, Johan Geldenhuys <[EMAIL PROTECTED]>
wrote:
> Thanks Kent,
>
> Let me explain what I need it for.
>
> I have a systemUpTime is seconds that I got from a SNMP agent.
>
> I want to work out when the system uptime began and want to put that in
ISO
> format time to the millisecond.
>
> So my idea is to take a timestamp in seconds when I get the systemUpTime.
I
> subtract the uptime from my timestamp and then format that into ISO
format.
> That should give me a fairly accurate UTC-like time of when the
systemUpTime
> began.
> Here is an example: "2008-09-04 22:29:43.221 Z"

I think you can do all that with functions in the time module.

Kent

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


Re: [Tutor] Support for datetime module

2008-09-07 Thread Johan Geldenhuys
Thanks Kent,

Let me explain what I need it for.

I have a systemUpTime is seconds that I got from a SNMP agent.

I want to work out when the system uptime began and want to put that in ISO
format time to the millisecond.

So my idea is to take a timestamp in seconds when I get the systemUpTime. I
subtract the uptime from my timestamp and then format that into ISO format.
That should give me a fairly accurate UTC-like time of when the systemUpTime
began.
Here is an example: "2008-09-04 22:29:43.221 Z"

Do you think it will be difficult to work this out with the datetime module?

Any suggestion would be greatly appreciated.

Thanks

Johan

-Original Message-
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Kent
Johnson
Sent: Saturday, 6 September 2008 23:08 PM
To: [EMAIL PROTECTED]
Cc: tutor@python.org
Subject: Re: [Tutor] Support for datetime module

On Sat, Sep 6, 2008 at 2:42 AM, Johan Geldenhuys <[EMAIL PROTECTED]>
wrote:
> Hi all,
>
> I have want to use the datetime module on a system with ver 2.2.3
installed.
> I know it's very old, but that's what I have to deal with and can't
upgrade.
> So please don't suggest that.
>
> As you know datetime was available from version 2.3.
>
>
>
> I want to know where can I get the datetime module so that I can include
it
> in my package that I use on my device?

datetime is implemented in C so getting the version from 2.3 to work
on 2.2 might be difficult.

Apparently the version in the std lib is derived from a Python version
that was part of Zope, this might be helpful if you can find the
source it refers to:
http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage

Kent

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


[Tutor] Support for datetime module

2008-09-06 Thread Johan Geldenhuys
Hi all,

 

I have want to use the datetime module on a system with ver 2.2.3 installed.
I know it's very old, but that's what I have to deal with and can't upgrade.
So please don't suggest that.

 

As you know datetime was available from version 2.3.

 

I want to know where can I get the datetime module so that I can include it
in my package that I use on my device? I looked on the Internet but can't
find it. 

 

So if anybody can give me a link to get the module, I'll be very thankful,

 

Regards

 

Johan

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


Re: [Tutor] convert hex number to decimal

2007-03-16 Thread Johan Geldenhuys

>>> ord('\x0D')
13 

Johan

-Original Message-
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf
Of Rikard Bosnjakovic
Sent: 16 March 2007 01:12 PM
To: Tutor@python.org
Subject: Re: [Tutor] convert hex number to decimal

On 3/16/07, ammar azif <[EMAIL PROTECTED]> wrote:

> Is there any built-in function to convert a hex number to a decimal
number?

>>> int("ff", 16)
255



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

--
No virus found in this incoming message.
Checked by AVG Free Edition.
Version: 7.5.446 / Virus Database: 268.18.10/720 - Release Date: 2007/03/12
07:19 PM
 

-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.446 / Virus Database: 268.18.10/720 - Release Date: 2007/03/12
07:19 PM
 

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


Re: [Tutor] Telnet and special characters

2007-02-28 Thread Johan Geldenhuys
 I have used special characters before in Telnet sessions, but always use
hex characters. i.e.: \x0B for ESC.

Maybe F-keys are some form of internal OS signals and are not send out on
the network connection. In that case, I'm not sure how to send it.

Johan

-Original Message-
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf
Of Luke Paireepinart
Sent: 27 February 2007 09:57 PM
To: Chris Hallman
Cc: tutor@python.org
Subject: Re: [Tutor] Telnet and special characters

Chris Hallman wrote:
>
> Is it possible to send a F1 "character" over a telnet connection? I've 
> searched but I can't find a solution. I've tried SendKeys 
>  and other methods, but I 
> can't get it to work.
>
> import telnetlib
>
> pswd = "***"
> host = "***"
> tn = telnetlib.Telnet(host)
> tn.read_until("password:", 7)
> tn.write(pswd + "\n")
> tn.write(chr(27)) # ESC
> tn.write (chr(78)) # Shift N
> tn.write(chr(25)) # Down arrow
You could have a special sequence of characters that wouldn't normally be
used, like \1\1\2\3\1\2\4, and if the server receives this, you can use
pyHook or something to generate a keypress on the other end.
It seems to me that the function keys would have a value too.
I don't have time to investigate the matter further currently, I'll try to
look into it later.
-Luke
>
>
> --
> --
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>   

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

--
No virus found in this incoming message.
Checked by AVG Free Edition.
Version: 7.5.441 / Virus Database: 268.18.3/698 - Release Date: 2007/02/23
04:39 AM
 

-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.446 / Virus Database: 268.18.4/703 - Release Date: 2007/02/26
02:56 PM
 

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


Re: [Tutor] Explanation of this lambda

2007-02-22 Thread Johan Geldenhuys
Thanks, Alan.

That makes it a lot easier to understand. I'll play around with other
examples to see what it is doing.

Johan 

-Original Message-
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf
Of Alan Gauld
Sent: 22 February 2007 11:46 AM
To: tutor@python.org
Subject: Re: [Tutor] Explanation of this lambda


"Johan Geldenhuys" <[EMAIL PROTECTED]> wrote

> Would somebody care to explain what is happening in this process?
>
> def intToBin(self, x, count=8):
>return "".join(map(lambda y:str((x>>y)&1), range(count-1, -1, 
> -1)))

"".join()   turns a list into a string
map() returns a list where each item is the result of applying the lambda to
the range()

lamda y: .  is a function to be applied

str() converts to a string

x>>y   shifts the bits of x right by y places  010 -> 001

& 1 bitwise ands with 1 which returns 1 if the last bit is one.

put the bits together and it should be clear.

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

-- 
No virus found in this incoming message.
Checked by AVG Free Edition.
Version: 7.5.441 / Virus Database: 268.18.3/696 - Release Date: 2007/02/21
03:19 PM
 

-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.441 / Virus Database: 268.18.3/696 - Release Date: 2007/02/21
03:19 PM
 

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


[Tutor] Explanation of this lambda

2007-02-21 Thread Johan Geldenhuys
Hi all,
 
I found this function that converts a integer into a 8 bit binary string. 
 
Would somebody care to explain what is happening in this process? 
 
def intToBin(self, x, count=8):
"""
Parameters: `x`: integer

Returns a 8 bit binary string of x
"""
return "".join(map(lambda y:str((x>>y)&1), range(count-1, -1, -1)))


 
Thanks
 
Johan

-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.441 / Virus Database: 268.18.3/694 - Release Date: 2007/02/20
01:44 PM
 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Struct the solution for Hex translation

2007-02-19 Thread Johan Geldenhuys
 Thanks, Dave.

On the struct module, How can I het the binary 1's and 0's of the Hex value?
Let say I want to get the 8 bit value of '\xe2', can I use struct to convert
that into binary code so that I get 8 binary bits as a string?

Thanks for helping with struct.

Johan

-Original Message-
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf
Of David Perlman
Sent: 19 February 2007 05:56 PM
To: tutor@python.org
Subject: Re: [Tutor] Struct the solution for Hex translation

You're way off base... :)

On Feb 19, 2007, at 9:25 AM, Johan Geldenhuys wrote:

>  Here is what I have:
>
>>>> data
> '\xa5\x16\x0b\x0b\x00\xd5\x01\x01\x01\x00\x00\xe3\x84(\x01\xc6\x00
> \x00\x17\x
> 01C\xc7'
>>>> data[0]
> '\xa5'
>>>> len(data[0])
> 1
>>>>
>
> You see that data[0] is only one byte and it doesn't see all four 
> characters.
>
> If I want to do this:
>
>>>> int(data[0], 16)
>   File "", line 1, in ?
> ''' exceptions.ValueError : invalid literal for int(): ¥ '''
>
>
> But I can do this:
>
>>>> int('a5', 16)
> 165
>>>>
>
> If I use data[0] as it is, I get errors. That why I want to know how I 
> can strip away the '\x'.

This is what you want to do:
 >>> import struct
 >>> struct.unpack('B',data[0])
(165,)

Once again, the \x doesn't really exist, any more than the quotation marks
do.  They're just ways of indicating on the screen what kind of data is
being displayed.

> Here is some other code to convert Hex to Binary:
>
> hex2bin = {
> "0" : "", "1" : "0001", "2" : "0010", "3" : "0011", "4" : "0100", 
> "5" : "0101", "6" : "0110", "7" : "0111", "8" : "1000", "9" : "1001", 
> "a" : "1010", "b" : "1011", "c" : "1100", "d" : "1101", "e" : "1110", 
> "f" : ""
> }
>
>>>> def hexBin(hexchars):
> ... s = ""
> for hexchar in hexchars:
> s += hex2bin[hexchar]
> return s.rstrip("\n")
> ...
>>>> hexBin('a5')
> '10100101'
>
> This however does not work if my argument is '\xa5'.
>
>>>> hexBin('\xa5')
>   File "", line 1, in ?
>   File "", line 5, in hexBin
> ''' exceptions.KeyError : '\xa5' '''
>>>>

This function is useless in this case because you don't actually have a
string of letters and numbers; you just have raw binary data.

--
-dave
After all, it is not *that* inexpressible.
-H.H. The Dalai Lama



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

--
No virus found in this incoming message.
Checked by AVG Free Edition.
Version: 7.5.441 / Virus Database: 268.18.2/692 - Release Date: 2007/02/18
04:35 PM
 

-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.441 / Virus Database: 268.18.2/692 - Release Date: 2007/02/18
04:35 PM
 

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


Re: [Tutor] Struct the solution for Hex translation

2007-02-19 Thread Johan Geldenhuys
 Here is what I have:

>>> data
'\xa5\x16\x0b\x0b\x00\xd5\x01\x01\x01\x00\x00\xe3\x84(\x01\xc6\x00\x00\x17\x
01C\xc7'
>>> data[0]
'\xa5'
>>> len(data[0])
1
>>>

You see that data[0] is only one byte and it doesn't see all four
characters.

If I want to do this:

>>> int(data[0], 16)
  File "", line 1, in ?
''' exceptions.ValueError : invalid literal for int(): ¥ '''


But I can do this:

>>> int('a5', 16)
165
>>>

If I use data[0] as it is, I get errors. That why I want to know how I can
strip away the '\x'.

Here is some other code to convert Hex to Binary:

hex2bin = {
"0" : "", "1" : "0001", "2" : "0010", "3" : "0011", 
"4" : "0100", "5" : "0101", "6" : "0110", "7" : "0111", 
"8" : "1000", "9" : "1001", "a" : "1010", "b" : "1011", 
"c" : "1100", "d" : "1101", "e" : "1110", "f" : ""
}

>>> def hexBin(hexchars):
... s = ""
for hexchar in hexchars:
s += hex2bin[hexchar]
return s.rstrip("\n")
... 
>>> hexBin('a5')
'10100101'

This however does not work if my argument is '\xa5'.

>>> hexBin('\xa5')
  File "", line 1, in ?
  File "", line 5, in hexBin
''' exceptions.KeyError : '\xa5' '''
>>> 

Thanks

Johan

-Original Message-
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf
Of Alan Gauld
Sent: 19 February 2007 05:04 PM
To: tutor@python.org
Subject: Re: [Tutor] Struct the solution for Hex translation


"Johan Geldenhuys" <[EMAIL PROTECTED]> wrote 

> The first two bytes of the data is a 16 bit value. Eg: "\xe2\x01'
> 
> I can the first byte into binary if I use 'e2', but I don't know how 
> to get the '\x' out of the first byte to use it in python.

Are you sure it is there?
Usually the \x is only part of the repr string, its not actually in the
data. What do you get is you do:

byte = data[0]  # get the first byte
print len(byte)   # should only be one byte
print byte # should get '\xe2' or whatever.

> My data has the '\x' and all I need is the 'e2'.

If you do have the \xe2  that implies you have 4 characters, ie 4 bytes, so
to get the real value use int(data[2:],16)

> Any advice of the usage of the struct module or how I can get rid of 
> the '\x' in my data?

I'm not sure where the struct module comes in? Are you using struct to read
the data? If so you should be able to use unpack the data into the format
you need by specifying a format string.

eg

struct.unpack('cc5s',data)

Should return two characters(bytes) and a 98 character 
string. Like so:

>>> struct.unpack('cc5s','\x12\x23abcde')
('\x12', '#', 'abcde')
>>>

Is that what you want?
Notice that the first value is actially a single byte of 
value 12 hex. The \x are only in the display.

The >>> prompt is a great place to experiment with struct
format strings etc.

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

-- 
No virus found in this incoming message.
Checked by AVG Free Edition.
Version: 7.5.441 / Virus Database: 268.18.2/692 - Release Date: 2007/02/18
04:35 PM
 

-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.441 / Virus Database: 268.18.2/692 - Release Date: 2007/02/18
04:35 PM
 

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


[Tutor] Struct the solution for Hex translation

2007-02-19 Thread Johan Geldenhuys
Hi all,
 
I read in some conversations that the struct module maybe helpful in
converting Hex values to binary or decimal. Maybe I understood it
incorrectly.
 
Here is my problem.
 
I have a 22 byte data packet on a tcp socket connection. My data field is
from the 6th byte to byte 20. 14 bytes in total.
The first two bytes of the data is a 16 bit value. Eg: "\xe2\x01'
 
I can the first byte into binary if I use 'e2', but I don't know how to get
the '\x' out of the first byte to use it in python. My data has the '\x' and
all I need is the 'e2'.
 
Any advice of the usage of the struct module or how I can get rid of the
'\x' in my data?
 
Hopefully I have given enough information.
 
Thanks
 
Johan

-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.441 / Virus Database: 268.18.2/692 - Release Date: 2007/02/18
04:35 PM
 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] control multiple FTP sessions using multiple ipconnectionsvia different com ports

2007-02-18 Thread Johan Geldenhuys
Will it be possible to disconnect one of the links during your test and
reconnect it and disconnect the other connection once the ftp test is
finished on the first connection? This way it will force the test script to
use the active route to the internet.
 
Not the most elegant way, but something to look at in the mean time.
 
Johan

   _  

From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf
Of ray sa
Sent: 18 February 2007 04:16 AM
To: Alan Gauld; tutor@python.org
Subject: Re: [Tutor] control multiple FTP sessions using multiple
ipconnectionsvia different com ports


Hi Alan et al
 
Many thanks for your time on this.
 
I was referring to the client end. 
 
An EDGE terminal is a phone that has the capability of connecting to the
internet. We use mobile phones to make a voice call that make use of a
circuit switched connection. By using a GPRS connection we can use the
mobile device to connect to the packet switched domain. You might have heard
about making data connection using your phone like GPRS, 3G etc. EDGE is
just faster than a GPRS connection and 3G is supposedly faster than GPRS and
EDGE. 
 
May be I can give you more information about what I am trying to do. So you
can understand what I am trying to achieve. Basically, I am trying to decide
whether I should change my ADSL fixed solution to a higher speed connection
using a mobile solution. Where I live the mobile operator is offering a
mobile solution which is cheaper than my fixed solution….and is faster than
my ADSL connection, please read on
 
I have my ADSL broadband connection to my service provider that I use to
connect to the internet. I have just bought a GPRS/EDGE/3G terminal and
wanted to benchmark the speed I am getting by using my mobile device as
opposed to my fixed connection.
 
My desktop machine is connected to my ADSL provider using a USB modem which
is assigned a particular COM port on my machine. Then I have connected my
mobile handset also using a USB connection connected to a different COM
port.
 
Now I have two ip addresses
 

1.  ADSL – COM port 4 with ip addres from my ADSL service provider 

2.  Mobile Handset – COM port 5 with another ip address from my mobile
provider

 
I have written a script that connects to a ftp server within my home country
and downloads a file. But this script uses one of the connections above.
There must be away to tell the script and control which connection to use.
So I can get to see real time which connection is faster. So I can run the
script pointing to one IP address and at the same time run another script
using the other connection. 
 
I think there must be a method that finds out which connection is connected
to which com port and then in my script I need to point towards that
connection so my script knows which channel to use when downloading the
file.
 
I hope this helps sorry for too much text couldn’t really find a simpler way
to explain this. 
 
Once again I really appreciate the help on this forum./Ray


Alan Gauld <[EMAIL PROTECTED]> wrote:


"ray sa" wrote 

> I have been successful to write an ftp script that logs 
> into a server and collects files. 

> ...I would like to run multiple ftp sessions using one laptop 
> with two different connections. 

Do you mean you want the server on the laptop accepting 
using two connections or do you mean that you want
the client on the laptop and have different sessions sending 
outgoing requests to the server via two different IP addresses?

If the former its easy, just set up two servers, one on each 
IP address. The port will nbe the same on both, ISTR its port 
21 for ftp?

If you want to specify which IP address you send the 
client request from, I'm afraid I have no idea how you specify 
that. I've only ever used multiple network cards at the server 
end!

> another connection using your EDGE terminal 

As a matter of interest what is an EDGE terminal? 
A new term for me...

> I would like to write a script that controls which ip 
> address to use or with com port to use. 

Until we know which end you mean its hard to hgive more 
specific advice.

Alan G.

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




   _  

No need to miss a message. HYPERLINK
"http://us.rd.yahoo.com/evt=43910/*http://mobile.yahoo.com/mail"Get email
on-the-go 
with Yahoo! Mail for Mobile. HYPERLINK
"http://us.rd.yahoo.com/evt=43910/*http://mobile.yahoo.com/mail"Get started.


--
No virus found in this incoming message.
Checked by AVG Free Edition.
Version: 7.5.441 / Virus Database: 268.17.39/685 - Release Date: 2007/02/13
10:01 PM



-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.441 / Virus Database: 268.18.2/692 - Release Date: 2007/02/18
04:35 PM
 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] control multiple FTP sessions using multiple ip connectionsvia different com ports

2007-02-17 Thread Johan Geldenhuys
Well, I'm not a great expert on this, but in the FTPlib, it makes use of
sockets.
 
Maybe Alan can comment if socket.getaddrinfo(host, port) can be manipulated
to change the outgoing interface.
 
Good topic.
 
Johan

   _  

From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf
Of ray sa
Sent: 16 February 2007 05:42 PM
To: tutor@python.org
Subject: [Tutor] control multiple FTP sessions using multiple ip
connectionsvia different com ports


Hi Kind people
 
I have been successful to write an ftp script that logs into a server and
collects files. What I would like to do but have no knowledge of is that I
would like to run multiple ftp sessions using one laptop with two different
connections. What I mean here is that you have a ethernet card connection to
the ip world and then you have another connection using your EDGE terminal
so in other words you have two ip address and I would like to write a script
that controls which ip address to use or with com port to use. I was hoping
someone could help to define how to force the ftp script to use the relevant
connections on one laptop. You help and guidance will be most appreciated.
 
Many thanks
 
Ray


   _  

HYPERLINK
"http://us.rd.yahoo.com/evt=49938/*http://tools.search.yahoo.com/toolbar/fea
tures/mail/"Never miss an email again!
Yahoo! Toolbar alerts you the instant new Mail arrives.HYPERLINK
"http://us.rd.yahoo.com/evt=49937/*http://tools.search.yahoo.com/toolbar/fea
tures/mail/" Check it out.


--
No virus found in this incoming message.
Checked by AVG Free Edition.
Version: 7.5.441 / Virus Database: 268.17.39/685 - Release Date: 2007/02/13
10:01 PM



-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.441 / Virus Database: 268.17.39/685 - Release Date: 2007/02/13
10:01 PM
 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Range of float value

2007-02-08 Thread Johan Geldenhuys
OK, this what I wanted:
 
I have a value: a = 48.41
 
My lowValue is: lowValue = 48.35
My highValue is : highvalue = 48.45
 
if a <= lowValue:
print 'value below limit'
 
if a >= highValue:
print value above limit'
 
I though that it could be possible to have a range between 48.35 and 48.45
that could have a step of 0.1
 
This works fine with normal intgers:
 
>>> def lookAtRange(a):
... if a in range(40, 110, 10):#Would like to have: if a in
range(48.35, 48.45, 0.1):
... print 'In limits'
... else:
... print 'Out of limits'
... 
>>> lookAtRange(40)
In limits
>>> lookAtRange(50)
In limits
>>> 
>>> lookAtRange(20)
Out of limits
>>> 
>>> lookAtRange(120)
Out of limits
>>> 
 
Johan
 

   _  

From: Andre Engels [mailto:[EMAIL PROTECTED] 
Sent: 08 February 2007 07:17 PM
To: [EMAIL PROTECTED]
Cc: tutor@python.org
Subject: Re: [Tutor] Range of float value


2007/2/8, Johan Geldenhuys mailto:[EMAIL PROTECTED]"[EMAIL PROTECTED]>: 

Hi all,
 
I have a value that ranges between 48.01 and 48.57. a Float value in other
words.
 
I want to look at changes in the value. If my normal range is between 48.35
and 48.45, how will I identify the value below 48.35 and above 48.45?
 
Something I tried was:
 
for a in range(48.35, 48.45):
print a
 
It gives me a value of 100.
 
Is it possible to get a range of a float value?


It depends. What would you like it to be? All numbers in that range? They're
uncountably infinite, so no way we could ever get that out of the computer.
All actual float values? Depends too much on the implementation of the
specific machine you're working on to be workable. 

Identifying values below 48.35 and above 48.45 is simply done by:
if value < 48.35 or value > 48.45 then...

No need to first create the range of values

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


--
No virus found in this incoming message.
Checked by AVG Free Edition.
Version: 7.5.432 / Virus Database: 268.17.30/674 - Release Date: 2007/02/07
03:33 PM



-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.432 / Virus Database: 268.17.30/674 - Release Date: 2007/02/07
03:33 PM
 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Range of float value

2007-02-08 Thread Johan Geldenhuys
Hi all,
 
I have a value that ranges between 48.01 and 48.57. a Float value in other
words.
 
I want to look at changes in the value. If my normal range is between 48.35
and 48.45, how will I identify the value below 48.35 and above 48.45?
 
Something I tried was:
 
for a in range(48.35, 48.45):
print a
 
It gives me a value of 100.
 
Is it possible to get a range of a float value?
 
Thanks
 
Johan

-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.432 / Virus Database: 268.17.30/674 - Release Date: 2007/02/07
03:33 PM
 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] CRC calculation with python

2007-02-06 Thread Johan Geldenhuys
Thanks for all the replies,

I got this code from a protocol spec that I must use for communications to a
RS232 interface and this the way they calculate the CRC for the data in the
packet.

I have never done any C programming and thought that somebody in this list
may be able to assist.

The idea that I get from the replies is that I should rather use a Python
module for calculating the CRC, thanks Dave for the suggestion. I'll rather
go and look at that than to use a translated C code snippet.

Every now and again I come across C code that is compared with Python code
and since I don't know C, I can't follow the comparison. I never use C in my
work, so for me to go and study the syntax and code layout is something I
wouldn't really use a lot.

Johan

 

-Original Message-
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf
Of Dave Kuhlman
Sent: 06 February 2007 07:28 PM
To: tutor@python.org
Subject: Re: [Tutor] CRC calculation with python

On Tue, Feb 06, 2007 at 12:10:36PM -0500, Chris Calloway wrote:
> First, you need to find the preprocessor define for CCITT_POLY. The 
> code is incomplete without it.
> 
> Second, where did this code come from? It defines an unused local 
> named cval, which will usually cause at least a compilation warning.
> 
> This looks like a snippet, not a complete CCITT CRC calculation.

Also, see the crcmod module:

http://crcmod.sourceforge.net/

But, the README that comes with crcmod recommends the md5 module in the
Python standard library.

Dave


--
Dave Kuhlman
http://www.rexx.com/~dkuhlman
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

--
No virus found in this incoming message.
Checked by AVG Free Edition.
Version: 7.5.432 / Virus Database: 268.17.25/669 - Release Date: 2007/02/04
09:58 PM
 

-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.432 / Virus Database: 268.17.25/669 - Release Date: 2007/02/04
09:58 PM
 

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


[Tutor] CRC calculation with python

2007-02-06 Thread Johan Geldenhuys
Hi all,
 
I'm not a C++ expert at all and I would like to find out if somebody can
explain to me how the statement below can be done in Python?
 
"""
_uint16 ComCRC16(_uint8 val, _uint16 crc)
{
_uint8 i;
_uint16 cval;
 
for (i=0;i<8;i++)
{
if (((crc & 0x0001)^(val & 0x0001))!= 0)   crc = (crc >> 1)^
CCITT_POLY;
else   crc >>= 1;
val >>= 1;
}
return crc
}
 
"""
 
Thanks
 
Johan

-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.432 / Virus Database: 268.17.25/669 - Release Date: 2007/02/04
09:58 PM
 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] The best way to implement a config file ???

2007-02-01 Thread Johan Geldenhuys
I've used two options in the past. The one is as Kent suggested, by using a
module that is imported by all others and share the values.
This doesn't allow for users to change the values, without changing the
code.

The second is to make use of a other file format. I used xml with all the
info in and extracted the values from there. It can be done with any type of
file, as long as you will know how to get the correct attributes for each
value.

HTH

Johan 

-Original Message-
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf
Of Kent Johnson
Sent: 01 February 2007 04:18 PM
To: Andreas Kostyrka
Cc: tutor@python.org
Subject: Re: [Tutor] The best way to implement a config file ???

Andreas Kostyrka wrote:
> * Magnus Wirström <[EMAIL PROTECTED]> [070201 14:38]:
>> Hi everyone
>>
>> I'm learning to program python with wxpython gui. I have a 
>> application i made with several modules and i want to implement a 
>> configfile that applies to all those modules. Is there an easy way to 
>> do this ?  Can anyone point me in the right direction ?
> 
> Depending upon your tastes:
> 
> ConfigFile => win.ini style config files.
> shlex  => unix shell script style parsing.

You can also use a python module as a shared config; just define whatever
values you want in Python code and import the module where you need it.

Kent

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

--
No virus found in this incoming message.
Checked by AVG Free Edition.
Version: 7.5.432 / Virus Database: 268.17.18/662 - Release Date: 2007/01/31
03:16 PM
 

-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.432 / Virus Database: 268.17.18/662 - Release Date: 2007/01/31
03:16 PM
 

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


Re: [Tutor] Python code to connect using PPPoE

2007-01-29 Thread Johan Geldenhuys
Thanks,

Unfortunately I am on a device that does not have this in the kernel and I
can't recompile the kernel to include PPPoE nor can I load other utils to do
tasks for me. 

So I must do it all in Python.
I found Scapy that seems to support PPPoE connections, but finding out how
that can be used, seems to be a trial and error process. The scapy mailing
list does seem to be so helpful than this one.

Any other suggestions would be appreciated.
Thanks

Johan 

-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] On Behalf Of Hugo
González Monteverde
Sent: 26 January 2007 12:25 AM
To: tutor@python.org
Subject: Re: [Tutor] Python code to connect using PPPoE

Hi Johan,

PPPoE is both in the Linux Kernel (for the low level work) and as some
executables and scripts.

It fou want to establish a connection from a Python script (E.G. ehn the
computer has no internet access and you need it) The best way would be to
call the appropriate utilities, and parse their output. This means calling
adsl-connect, ficonfig, and the like, maybe parsing the output from
ifconfig. Take a look at the module named subprocess to do that.

Reimplementing these utilities in Python is some work, but doable. 
Implementing PPPoE in Python, reading the device files and all that... 
well... it's almost nonsense. For this, you have to use the kernel.

Johan Geldenhuys wrote:
> Kent,
> I want to establish the connection with Python. I think in Linux you 
> can use a PPPoE package to make life easier, but I don't want to use 
> the Kernel to do that.
> 
> Johan
> 

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

-- 
No virus found in this incoming message.
Checked by AVG Free Edition.
Version: 7.5.432 / Virus Database: 268.17.11/652 - Release Date: 2007/01/25
03:32 PM
 

-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.432 / Virus Database: 268.17.12/655 - Release Date: 2007/01/28
01:12 PM
 

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


Re: [Tutor] Python code to connect using PPPoE

2007-01-24 Thread Johan Geldenhuys
Is there a module that I can use for this or is it a "os" function?

Johan

-Original Message-
From: Kent Johnson [mailto:[EMAIL PROTECTED] 
Sent: 24 January 2007 04:39 PM
To: [EMAIL PROTECTED]
Cc: tutor@python.org
Subject: Re: [Tutor] Python code to connect using PPPoE

Johan Geldenhuys wrote:
> Kent,
> I want to establish the connection with Python. I think in Linux you 
> can use a PPPoE package to make life easier, but I don't want to use 
> the Kernel to do that.

If you are on Linux, maybe you can use os.command() to control rp-pppoe.
http://www.roaringpenguin.com/penguin/openSourceProducts/rpPppoe

If you are on Windows maybe win32ras does what you want?

Kent

--
No virus found in this incoming message.
Checked by AVG Free Edition.
Version: 7.5.432 / Virus Database: 268.17.8/649 - Release Date: 2007/01/23
08:40 PM
 

-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.432 / Virus Database: 268.17.8/649 - Release Date: 2007/01/23
08:40 PM
 

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


Re: [Tutor] Python code to connect using PPPoE

2007-01-24 Thread Johan Geldenhuys
Kent,
I want to establish the connection with Python. I think in Linux you can use
a PPPoE package to make life easier, but I don't want to use the Kernel to
do that.

Johan 

-Original Message-
From: Kent Johnson [mailto:[EMAIL PROTECTED] 
Sent: 24 January 2007 03:52 PM
To: [EMAIL PROTECTED]
Cc: tutor@python.org
Subject: Re: [Tutor] Python code to connect using PPPoE

Johan Geldenhuys wrote:
> Hi all,
>  
> I don't know if this the right place to ask the question, but I did 
> some Googling and struggled to get decent examples of code to use for 
> PPPoE connection.
>  
> I have a wireless modem that uses PPPoE to connect and want to use 
> Python to connect to the internet through this modem using PPPoE.
>  
> Does anybody know where I can get something like this? Is it in 
> Twisted or is there possibly a "cleaner" example of this?

I'm not too sure what you want to do. Are you trying to use Python to
establish the connection, or do you want to access the internet over an
established connection?

If it is the former, I don't have an answer for you. For the latter, check
out urllib, urllib2, httplib, etc.

Kent

--
No virus found in this incoming message.
Checked by AVG Free Edition.
Version: 7.5.432 / Virus Database: 268.17.8/649 - Release Date: 2007/01/23
08:40 PM
 

-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.432 / Virus Database: 268.17.8/649 - Release Date: 2007/01/23
08:40 PM
 

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


[Tutor] Python code to connect using PPPoE

2007-01-24 Thread Johan Geldenhuys
Hi all,
 
I don't know if this the right place to ask the question, but I did some
Googling and struggled to get decent examples of code to use for PPPoE
connection.
 
I have a wireless modem that uses PPPoE to connect and want to use Python to
connect to the internet through this modem using PPPoE.
 
Does anybody know where I can get something like this? Is it in Twisted or
is there possibly a "cleaner" example of this?
 
Thanks 
 
Johan

-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.432 / Virus Database: 268.17.8/649 - Release Date: 2007/01/23
08:40 PM
 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Division doesn't work

2007-01-18 Thread Johan Geldenhuys
Thanks at lot. Something as simple as that...
 
J

   _  

From: Geoframer [mailto:[EMAIL PROTECTED] 
Sent: 18 January 2007 02:10 PM
To: Johan Geldenhuys
Cc: tutor@python.org
Subject: Re: [Tutor] Division doesn't work


You assign s as an integer... it should be a float to get the right
result...

So either define s as 

s = 14105.0

or as

s = float(14105)

it'll then result in the right answer :

In [17]: s=14105.0
In [18]: s/1024
Out[18]: 13.7744140625

In [19]: s = float(14105)
In [20]: s/1024
Out[20]: 13.7744140625

HTH - Geofram


On 1/18/07, Johan Geldenhuys mailto:[EMAIL PROTECTED]"[EMAIL PROTECTED]> wrote: 

Hi all,
 
In my script I want to convert 14105 bytes to kilobytes and and this is what
I do:
 
>>> s = 14105
>>> print '%0.2f' % (s/1024)
13.00 
 
This not correct and I don't know why. The answer is 13.77.
 
Any pointers please that would help my in the right direction?
 
Thanks
 
Johan



--
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.432 / Virus Database: 268.16.13/632 - Release Date: 2007/01/16
04:36 PM



___
Tutor maillist  -  HYPERLINK "mailto:Tutor@python.org"Tutor@python.org
HYPERLINK "http://mail.python.org/mailman/listinfo/tutor";
\nhttp://mail.python.org/mailman/listinfo/tutor






--
No virus found in this incoming message.
Checked by AVG Free Edition.
Version: 7.5.432 / Virus Database: 268.16.13/632 - Release Date: 2007/01/16
04:36 PM



-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.432 / Virus Database: 268.16.13/632 - Release Date: 2007/01/16
04:36 PM
 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Division doesn't work

2007-01-18 Thread Johan Geldenhuys
Hi all,
 
In my script I want to convert 14105 bytes to kilobytes and and this is what
I do:
 
>>> s = 14105
>>> print '%0.2f' % (s/1024)
13.00 
 
This not correct and I don't know why. The answer is 13.77.
 
Any pointers please that would help my in the right direction?
 
Thanks
 
Johan

-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.5.432 / Virus Database: 268.16.13/632 - Release Date: 2007/01/16
04:36 PM
 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] quick ?

2006-09-15 Thread Johan Geldenhuys




I would make list of all the numbers in the beginning and then just add
numbers in a range to the list.
It's much easier to test for something in a list than to compare each
number with the previous one.



Here is a example:

import random

def randnum():
    c = []
    l = len(c)
    
   # Numbers in your list = 6
    while l < 6:
   for x in range(6):
   s = random.randrange(1, 50) # your range will be 1-49

   # test for duplicates
   if s not in c:
  c.append(s)
  l = len(c)
    c.sort()
    d = len(c)
    print ' '* 20 + 'Randoms: %s and the Bonus number: %s' %
(str(c[:5]), str(c[5]))
   
    c = []
    
if __name__ == '__main__':
   q = int(raw_input('How many picks do ou need?>'))
   for x in range(q):
   randnum()

HTH 
Johan 




Bob Gailer wrote:

  [EMAIL PROTECTED] wrote:
  
  
I am new to Python (and programming).  In teaching myself I wrote a
small program that will pick random lottery numbers, I want to check for
duplicates and rerun the random function.  But I am hitting a wall. 
This is what I think should work, but I still get duplicates.  TIA.

  
  random.shuffle() is the predefined way to do this. But for more general 
things like this it is better to use a list to hold multiple values.

Example:

import random
picks = [] # collect unique picks
count = input("How many quick picks do you need? ")
while len(picks) < count:
  pick = random.randint(1,55)
  if not pick in picks: 
picks.append(pick)
print picks

OR

import random
picks = [0]*55
count = input("How many quick picks do you need? ")
got = 0
while got < count:
  pick = random.randint(1,55)
  if not picks[pick]: 
picks[pick] = 1
got += 1
for i in range(len(picks)+1):
  if picks[i]:
print i, 


  



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


Re: [Tutor] HTML page status

2006-09-12 Thread Johan Geldenhuys




I don't know if this will work in all cases. I tried it with a internet
connection and could get a 'OK' response. Then I tried it withoput a
internet connection and received a Traceback error, which is not what I
want.

It gave me some idea what is possible.

Johan

Michael P. Reilly wrote:
On 9/12/06, Johan Geldenhuys
<[EMAIL PROTECTED]>
wrote:
  
  
Hi all,

I looked a little bit at the urllib and it all looks fairly easy.
What I didn't see, if it is there, was how to know or identify if a page
was successfully downloaded. I want to do tests to see if a connection

to a webpage was successful by parsing whatever came back.

Will this be the easiest way of doing this or is there a different way
of testing the availability of webpages? Let's say I can connect to a
webpage, but it failed to upload 100%, how will I know that the

connection was not 100% successful? I'm not very familiar with url
parsing and HTML to know if there are other indicators to notify me if a
page or any web access is possible.

Once this was done, can I add features to say how fast the page was

downloaded?

Thanks

Johan
  
  
  
I've just finished writing a smoke test engine after releasing new
webpages.  I use httplib.HTTPConnection classes.
  
Here is an example:
  
  import urlparse,
httplib
  class SiteCheck:
    reqtype = 'POST'
    def __init__(self, url):
    self.url = "">
    pieces = urlparse.urlparse(url)
    self.hostname = pieces[1]
    self.conn = httplib.HTTPConnection(self.hostname)
    def run(self):
    self.conn.request(self.reqtype, self.url
)
    response = self.conn.getresponse()
    method_name = 'response_%d' % response.status
    try:
    method = getattr(self, method_name)
    except AttributeError:
    self.response_default(response)
    else:
    method(response)
    def response_default(self, response):
    self.result = '%d %s' % (response.status, response.reason)
    def response_200(self, response):
  
    self.result = response.reason # "OK"
    def response_302(self, response):
    self.result = response.msg['Location'] # 302 redirect
  
  Hopefully this will give you some ideas.
  -Arcege
-- 
There's so many different worlds,
So many different suns.
And we have just one world,
But we live in different ones.



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


[Tutor] HTML page status

2006-09-12 Thread Johan Geldenhuys
Hi all,

I looked a little bit at the urllib and it all looks fairly easy.
What I didn't see, if it is there, was how to know or identify if a page 
was successfully downloaded. I want to do tests to see if a connection 
to a webpage was successful by parsing whatever came back.

Will this be the easiest way of doing this or is there a different way 
of testing the availability of webpages? Let's say I can connect to a 
webpage, but it failed to upload 100%, how will I know that the 
connection was not 100% successful? I'm not very familiar with url 
parsing and HTML to know if there are other indicators to notify me if a 
page or any web access is possible.

Once this was done, can I add features to say how fast the page was 
downloaded?

Thanks

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


[Tutor] HTML page status

2006-09-12 Thread Johan Geldenhuys

Hi all,

I looked a little bit at the urllib and it all looks fairly easy.
What I didn't see, if it is there, was how to know or identify if a page 
was successfully downloaded. I want to do tests to see if a connection 
to a webpage was successful by parsing whatever came back.

Will this be the easiest way of doing this or is there a different way 
of testing the availability of webpages? Let's say I can connect to a 
webpage, but it failed to upload 100%, how will I know that the 
connection was not 100% successful? I'm not very familiar with url 
parsing and HTML to know if there are other indicators to notify me if a 
page or any web access is possible.

Once this was done, can I add features to say how fast the page was 
downloaded?

Thanks

Johan


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


Re: [Tutor] parsing

2006-07-13 Thread Johan Geldenhuys




rezult is not a dictionary in your example, it's a list. You can create
a dictionary with all your keys and values:

rezult ={
'title': 'TITLE', 
'body':['body_1', 'body_2'], 
'h1':['1_1', 'END'], 
'h2':['2_1', '2_2'],
'h3':['3_1'],
'p':['p_1', 'p_2'],
'id_one':['div_one_1', 'div_one_2', 'div_one_3'],
'span_sp_1':['sp_text'],
'td':['td_1', 'td_3', 'td_4'],
'td_sp_2':['td_2']
}

How to get it out of your HTML page, I don't know.


Johan


Ismael Garrido wrote:

  Сергій wrote:
  
  
First, excuse me my English... English is not my native language, but 
I hope
that I will be able to describe my problem.

I am new in python for web, but I want to do such thing:

Suppose I have a html-page, like this:
"""
TITLE

body_1
1_1
2_1
div_one_1
p_1
p_2
div_one_2

sp_text
div_one_2
div_one_3

3_1
2_2
p_3
body_2
END

td_1
td_2
td_3
td_4
...


"""

I want to get all info from this html in a dictionary that looks like 
this:

rezult = [{'title':['TITLE'],
{'body':['body_1', 'body_2']},
{'h1':['1_1', 'END']},
{'h2':['2_1', '2_2']},
{'h3':['3_1']},
{'p':['p_1', 'p_2']},
{'id_one':['div_one_1', 'div_one_2', 'div_one_3']},
{'span_sp_1':['sp_text']},
{'td':['td_1', 'td_3', 'td_4']},
{'td_sp_2':['td_2']},

]

Huh, hope you understand what I need.
Can you advise me what approaches exist to solve tasks of such type... 
and
may be show some practical examples
Thanks in advance for help of all kind...

  
  
Try ElementTree or Amara.
http://effbot.org/zone/element-index.htm
http://uche.ogbuji.net/tech/4suite/amara/

If you only cared about contents, BeautifulSoup is the answer.

Ismael
___
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] Internet programming with python

2006-01-18 Thread Johan Geldenhuys
Thanks, Kent.

I found this one also. There is a wide range of tutorials here.

Johan

Kent Johnson wrote:

>Johan Geldenhuys wrote:
>  
>
>>Wesley,
>>
>>I am doing some socket programming in my work and I need to learn about 
>>writing webpages and CGI stuff in Pyhon. I have Apache on my PC and 
>>could start and write some pages to test on it. It is still a bit vage  
>>to me how to do that  and  thought that a book like hat could be beneficial.
>>
>>I read about your tutorial in Feb. but can't make it, unless you come to 
>>South Africa ;-) .
>>
>>I will check out "Foundations of Python Network Programming" by John 
>>Goerzen.
>>
>>Any tutorials on the net I could use?
>>
>>
>
>Socket Programming HOW TO: http://www.amk.ca/python/howto/sockets/
>The docs for the CGI module are fairly extensive:
>http://docs.python.org/lib/module-cgi.html
>
>Voidspace has a number of useful CGI-related modules and recipes:
>http://www.voidspace.org.uk/python/cgi.shtml
>http://www.voidspace.org.uk/python/recipebook.shtml
>
>More links here: http://wiki.python.org/moin/CgiScripts
>
>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] Internet programming with python

2006-01-18 Thread Johan Geldenhuys
Wesley,

I am doing some socket programming in my work and I need to learn about 
writing webpages and CGI stuff in Pyhon. I have Apache on my PC and 
could start and write some pages to test on it. It is still a bit vage  
to me how to do that  and  thought that a book like hat could be beneficial.

I read about your tutorial in Feb. but can't make it, unless you come to 
South Africa ;-) .

I will check out "Foundations of Python Network Programming" by John 
Goerzen.

Any tutorials on the net I could use?

Thanks for he help

Johan


w chun wrote:

>On 1/18/06, Johan Geldenhuys <[EMAIL PROTECTED]> wrote:
>  
>
>>Has the book 'Internet programming with Python' (ISBN: 1558514848,
>>publisher: M&T Books, 1996) ever been revised or is there a secod editin
>>available?
>>I don't have it, but I would like this or something simular very much.
>>
>>Any ideas what the status is or where I can find it?
>>
>>
>
>
>hi johan,
>
>this book is long out-of-print, and i doubt any revision is coming in
>the near-term (but i don't know for sure).  what is it about this book
>that interests you?  is it the title alone?
>
>if so, there are plenty of current books out there with material that
>you're looking for.  you could also tell us what topics are of
>interest to you.  if not, then we should still be able to help you
>with your interest areas.
>
>for example, i teach a 3-hour tutorial with that very same name, i.e.,
>http://wiki.python.org/moin/PyCon2006/Tutorials/InternetProgrammingWithPython
>and it involves 3 distinct areas of "internet programming," namely
>socket programming, internet *client* programming (i.e., FTP, NNTP,
>SMTP, POP3, etc.), and finally, web and CGI programming.  there are
>corresponding chapters in my book, "Core Python" too.  other books out
>there include "Foundations of Python Network Programming" by John
>Goerzen, and another one by Steve Holden, "Python Web Programming,"
>both of which are very good.
>
>hope this helps, but if you want more help, you need to be more
>specific about your interest areas.
>
>cheers,
>-- wesley
>- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
>"Core Python Programming", Prentice Hall, (c)2006,2001
>http://corepython.com
>
>wesley.j.chun :: wescpy-at-gmail.com
>cyberweb.consulting : silicon valley, ca
>http://cyberwebconsulting.com
>
>  
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Internet programming with python

2006-01-18 Thread Johan Geldenhuys
Hi all,

Has the book 'Internet programming with Python' (ISBN: 1558514848, 
publisher: M&T Books, 1996) ever been revised or is there a secod editin 
available?
I don't have it, but I would like this or something simular very much.

Any ideas what the status is or where I can find it?

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


Re: [Tutor] Numeric import error

2005-12-22 Thread Johan Geldenhuys




>>> import Numeric
Traceback (most recent call last):
  File "", line 1, in ?
ImportError: No module named Numeric

Pujo Aji wrote:
Can you open the python interpreter and write:
import Numeric
  
What kind of error message you have?
Cheers,
pujo
  
  On 12/22/05, Johan Geldenhuys
   <[EMAIL PROTECTED]>
wrote:
  Hi
all,


I have installed Numeric (Suse 10.0) and it is in my site-packages
folder, but I can't import the module.

Any idea how to fix this/

TIA

Johan
___

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] Numeric import error

2005-12-22 Thread Johan Geldenhuys
Hi all,

I have installed Numeric (Suse 10.0) and it is in my site-packages 
folder, but I can't import the module.

Any idea how to fix this/

TIA

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


Re: [Tutor] Pygame mailing list info needed

2005-12-21 Thread Johan Geldenhuys




This will do, thanks.

Johan

Lee Harr wrote:

  
I subscribed to the pygame-users mailing list through [EMAIL PROTECTED],
but I don't know where to send the mail too so that everybody can see it.

Any suggestion on how to use that mailing list?


  
  

http://www.google.com/search?q=pygame+mailing+list
2nd link ...

"""
Pygame maintains an active mailing list. You can email the list at
[EMAIL PROTECTED]
"""

Or have you already found that and you are you having a problem with
your mail not going through or your questions not being answered?

_
Don't just search. Find. Check out the new MSN Search! 
http://search.msn.click-url.com/go/onm00200636ave/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


Re: [Tutor] Books

2005-12-21 Thread Johan Geldenhuys
Are here any new books on web programming with Python?

Johan

David Holland wrote:

>I would recommend python programming for the absolute beginner.
>
>
>   
>   
>   
>___ 
>Yahoo! Messenger - NEW crystal clear PC to PC calling worldwide with voicemail 
>http://uk.messenger.yahoo.com
>___
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>  
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Print random letters

2005-12-21 Thread Johan Geldenhuys
Hi all,

I want to print out random letters from A - Z. I know how to do this 
with numbers, but don't know with letters.

Any ideas wil be greatly appreciated.

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


[Tutor] Pygame mailing list info needed

2005-12-21 Thread Johan Geldenhuys
Hi,
I subscribed to the pygame-users mailing list through [EMAIL PROTECTED], 
but I don't know where to send the mail too so that everybody can see it.

Any suggestion on how to use that mailing list?

Thanks,

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


Re: [Tutor] opts and try except

2005-11-20 Thread Johan Geldenhuys
Maybe this recipe will help. Here I used and tested the arguments that 
the user must enter before using the module:

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

Johan

Eric Walker wrote:

>All,
>I have a program now that works just like I want it. Now I want to 
>integerate something to say print usage info when the user puts in the wrong 
>number or type of options. Also print usage say if you type program name and 
>-h or -H. I currently just have functions defined and at the bottom make a 
>function call. Do I need to do like the def main(): and then the if __name__ 
>== "__main__"? I need an example of how to implement this. 
>
>Thanks in advance.
>
>
>python newbie.
>___
>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 topic draft

2005-11-17 Thread Johan Geldenhuys




This script was not intended to be used from the command line, but to
be called from elsewhere. It was only a test piece of code. 
If you use the ping command with the args that you are calling it with,
there is no need to kill the process, it will terminate after 10
requests.   8-) 

Johan

Christopher Arndt wrote:

  Alan Gauld schrieb:
  
  
Thanks, I may use that as one of the example programs if
you don't mind?

  
  
I took the liberty of refactoring Johan's example a bit, to make it more
reusable. See attached file.

Chris
  
  

"""Wrapper object for external commands, that allows to kill them after later..

   ::Author: Johan Geldenhuys
 [EMAIL PROTECTED]

   ::Version: 0.0.2

   ::Date last updated: 2005-11-16

   ::Changes:
  - refactored by Christopher Arndt

   :: TODO:  Capture the output from line 41 to a file.
"""

import os, signal, time

class KillableCommand(object):

def __init__(self, command, *args):
self.pid = None
self.command = command
self.args = args

def kill(self, signal=signal.SIGTERM):
try:
os.kill(self.pid, signal)
except:
raise OSError, "Could not kill process."

def run(self, *args):
self.pid = os.fork()
args = list(self.args + args)
if self.pid == 0:
   os.execvp(self.command, [self.command] + args)

if __name__ == '__main__':
cmdname = "ping"
print "Starting", cmdname
#cmd = KillableCommand('tcpdump', '-npi')
cmd = KillableCommand(cmdname, '-c', '10')
cmd.run('www.python.org')
print "PID: ", cmd.pid
print "Letting it run for 5 seconds..."
time.sleep(5)
try:
print "Trying to kill pid %d..." % cmd.pid
cmd.kill()
except OSError, e:
print e
else:
print "Killed pid %d." % cmd.pid
  
  

___
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 topic draft

2005-11-17 Thread Johan Geldenhuys




What is this line supposedto do?
cmd.run('www.python.org')


Christopher Arndt wrote:

  Alan Gauld schrieb:
  
  
Thanks, I may use that as one of the example programs if
you don't mind?

  
  
I took the liberty of refactoring Johan's example a bit, to make it more
reusable. See attached file.

Chris
  
  

"""Wrapper object for external commands, that allows to kill them after later..

   ::Author: Johan Geldenhuys
 [EMAIL PROTECTED]

   ::Version: 0.0.2

   ::Date last updated: 2005-11-16

   ::Changes:
  - refactored by Christopher Arndt

   :: TODO:  Capture the output from line 41 to a file.
"""

import os, signal, time

class KillableCommand(object):

def __init__(self, command, *args):
self.pid = None
self.command = command
self.args = args

def kill(self, signal=signal.SIGTERM):
try:
os.kill(self.pid, signal)
except:
raise OSError, "Could not kill process."

def run(self, *args):
self.pid = os.fork()
args = list(self.args + args)
if self.pid == 0:
   os.execvp(self.command, [self.command] + args)

if __name__ == '__main__':
cmdname = "ping"
print "Starting", cmdname
#cmd = KillableCommand('tcpdump', '-npi')
cmd = KillableCommand(cmdname, '-c', '10')
cmd.run('www.python.org')
print "PID: ", cmd.pid
print "Letting it run for 5 seconds..."
time.sleep(5)
try:
print "Trying to kill pid %d..." % cmd.pid
cmd.kill()
except OSError, e:
print e
else:
print "Killed pid %d." % cmd.pid
  
  

___
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 topic draft

2005-11-17 Thread Johan Geldenhuys
That will be great. In the "@TODO" part you will see that I still need 
to take the output from the command  and capture that into a file. Can 
you help me with that?

Johan

Alan Gauld wrote:

> Thanks, I may use that as one of the example programs if
> you don't mind?
>
> Alan G.
>
>
> - Original Message - From: "Johan Geldenhuys" 
> <[EMAIL PROTECTED]>
> To: "Alan Gauld" <[EMAIL PROTECTED]>
> Cc: "Python Tutor list" 
> Sent: Wednesday, November 16, 2005 8:12 AM
> Subject: Re: [Tutor] new topic draft
>
>
>> Alan,
>>
>> You may remember that I asked questions on killing a process, a while 
>> back,
>>
>> Sice this is relatedto the tutorial that yu are writing, this was the
>> best solution that worked for me to killa process for a command that
>> keeps on running like eg. 'tcpdump'.
>>
>> HTH
>>
>> Johan
>> BTW, There will a be many a felllow Pythonists that will benefit from a
>> tut like this, great work !!
>>
>>
>> Alan Gauld wrote:
>>
>>> I've just added an incomplete draft copy of my latest tutorial topic
>>> on using the Operating System from Python. The material that's
>>> there discusses the role of the OS and looks at file handling
>>> usng os/os.path/shutil etc.
>>>
>>> http://www.freenetpages.co.uk/hp/alan.gauld/tutos.htm
>>>
>>> If anyone would like to take a look and provide feedback on
>>> general direction/depth etc that'd be greatly appreciated.
>>>
>>> TIA,
>>>
>>> Alan G
>>> Author of the learn to program web tutor
>>> http://www.freenetpages.co.uk/hp/alan.gauld
>>>
>>>
>>> ___
>>> Tutor maillist  -  Tutor@python.org
>>> http://mail.python.org/mailman/listinfo/tutor
>>>
>>>
>>>
>>
>
>
> 
>  
>
>
>
>> """
>>   This class will execute the command, let it run for 5 seconds and 
>> kill the process.
>>
>>   ::Author: Johan Geldenhuys
>> [EMAIL PROTECTED]
>>
>>   ::Version: 0.0.1
>>
>>   ::Date last updated: 2005-11-03
>>
>>   ::Changes:
>>
>>   :: TODO:  Capture the output from line 41 to a file.
>> """
>>
>> import os, signal, time
>>
>> class command(object):
>>
>>def __init__(self):
>>
>>pass
>>
>>
>>def kill(self, pid, signal=signal.SIGTERM):
>>try:
>>
>>print "trying to kill pid...", pid
>>os.kill(pid, signal)
>>#os.waitpid(pid, 0)
>>print "Killed %d"%pid
>>except:
>>   print "couldn't stop process"
>>
>>def main(self, interface):
>>
>>self.interface = interface
>>self.pid = os.fork()
>>
>>if self.pid == 0:
>>
>>   os.execvp('tcpdump', ['tcpdump', '-npi', self.interface])
>>
>>print 'PID: ',self.pid
>>print 'Let it run for 5 seconds...'
>>time.sleep(5)
>>self.kill(self.pid)
>>
>>
>> if __name__ == '__main__':
>>   print "starting test"
>>   c = command()
>>   c.main('eth0')
>>
>>
>
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] new topic draft

2005-11-16 Thread Johan Geldenhuys

Alan,

You may remember that I asked questions on killing a process, a while back,

Sice this is relatedto the tutorial that yu are writing, this was the 
best solution that worked for me to killa process for a command that 
keeps on running like eg. 'tcpdump'.


HTH

Johan
BTW, There will a be many a felllow Pythonists that will benefit from a 
tut like this, great work !!



Alan Gauld wrote:


I've just added an incomplete draft copy of my latest tutorial topic
on using the Operating System from Python. The material that's 
there discusses the role of the OS and looks at file handling

usng os/os.path/shutil etc.

http://www.freenetpages.co.uk/hp/alan.gauld/tutos.htm

If anyone would like to take a look and provide feedback on 
general direction/depth etc that'd be greatly appreciated.


TIA,

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


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

 

"""
   This class will execute the command, let it run for 5 seconds and kill the process.
   
   ::Author: Johan Geldenhuys
 [EMAIL PROTECTED]
   
   ::Version: 0.0.1
   
   ::Date last updated: 2005-11-03
   
   ::Changes:
   
   :: TODO:  Capture the output from line 41 to a file.
"""

import os, signal, time

class command(object):

def __init__(self):

pass


def kill(self, pid, signal=signal.SIGTERM):
try:

print "trying to kill pid...", pid
os.kill(pid, signal)
#os.waitpid(pid, 0) 
print "Killed %d"%pid
except:
   print "couldn't stop process"

def main(self, interface):

self.interface = interface
self.pid = os.fork()

if self.pid == 0:
   
   os.execvp('tcpdump', ['tcpdump', '-npi', self.interface])
   
print 'PID: ',self.pid
print 'Let it run for 5 seconds...'
time.sleep(5)
self.kill(self.pid)


if __name__ == '__main__':
   print "starting test"
   c = command()
   c.main('eth0')

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


Re: [Tutor] Looking for suggestions

2005-11-14 Thread Johan Geldenhuys
Haven't look at the code in detail, but it would be great exercise to 
write a web gui for this game like the one for Tick-Tack-Toe.

Any suggestions where to start with something like this?

Johan

PS: Fun to play.

->Terry<- wrote:

>-BEGIN PGP SIGNED MESSAGE-
>Hash: SHA1
>
>
>I have written a small peg game using Pygame.
>This is the first working version. I have a
>request and a couple of perhaps silly questions.
>
>To anyone willing to take the time to have a
>look at the code and offer any advice or
>suggestions, I would be much appreciative.
>I'm looking for code suggestions rather than
>game-play suggestions, although I'm open to
>any help.
>
>I haven't got my head really wrapped around the
>OO stuff, so I'm thinking rewriting it using
>classes would make a good project to learn
>with. Is this the sort of thing that one would
>use classes for? Or is is better left as
>simple as possible?
>
>Now here is the perhaps silly question. Is
>something like this need to have a license?
>What I mean is, as I play with and improve
>this game and want to share it with others,
>should I choose a license and add the legal
>stuff with the distributed product?
>
>I have learned so much reading this list. I
>hope I've asked my questions right.
>
>The game appears to also work on Windows also,
>but does require you to have Pygame installed.
>It was written on Slackware with Python 2.4.1
>
>The code:
>
>http://members.socket.net/~tvbare/pypeg/pypeg.py>
>
>And the images:
>
>http://members.socket.net/~tvbare/pypeg/board.png>
>http://members.socket.net/~tvbare/pypeg/peg.png>
>
>Cheers,
>- -- 
> Terry
>
>
>"Be who you are and say what you feel, because those
>  who mind don't matter and those who matter don't mind."
>  -- Dr. Seuss
>-BEGIN PGP SIGNATURE-
>Version: GnuPG v1.2.7 (GNU/Linux)
>
>iD8DBQFDeCyyQvSnsfFzkV0RAqnBAJ9TEwpP7gmUPt06ZWCS/vUJ9lLSXACbBhFl
>NxIKZYKxi4OK9vR13HYP7IA=
>=gYkg
>-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] Another Quick Question

2005-11-13 Thread Johan Geldenhuys




Could this be a OS thing?
I use Linux and it works here.

Steve Haley wrote:

  
  
  
  
  Folks,
   
  I’m one of the people new
to Python who has started
going through a beginner’s book to learn the basics of the language
(“Python
Programming for the Absolute Beginner”).  In the second chapter the
author (Michael Dawson) illustrates the use of escape sequences with,
among
other things, the “\a” to sound the system bell.  However, when I
run the little program myself, the program runs but I get no sound –
all is
get is the word BEL in while letters on a blue background.  I’ve turned
the volume up all the way and still no sound.  I know the speakers on
my laptop
work because I just finished my daily session trying to learn a little
Spanish
which involves sound.
   
  I went to the language
reference which also seems to
indicate I should get a sound with exactly what the author is saying. 
The
exact line is:
   
  print “\a”
   
  I’m not sure why but this
kind of thing bothers me. 
Can anyone suggest why my laptop won’t produce a bell?  Does the fact
that I’m running version 2.1 have something to do with it?  Does my
laptop have something against me and just doesn’t want to ring its bell
for me? (just kidding with that last one)
   
  Thanks in advance.
  Steve
   
  
  

___
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] simple report writing?

2005-11-10 Thread Johan Geldenhuys
Did you manage to get something that worked for you?
Johan

CPIM Ronin wrote:

>Can someone suggest a specific tutorial strictly on report writing?
>
>I'm able to write reports fairly easily in Python. I know the stuff like 
>str(round(x,2)) where x = 3.145678 will yield 3.14. What I'm looking for is 
>to be able to control left and right justification, column by column while 
>using string and numeric data of variable lengths so that my reports look 
>much neater.
>
>Possibly a generalized def print_line(*x)?
>
>Thanks.
>
>RC
>
>_
>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


Re: [Tutor] logging to a database

2005-11-10 Thread Johan Geldenhuys
Try looking here;
http://sourceforge.net/projects/mysql-python

Johan

captnswing wrote:

>Hello all,
>I would like to log messages to a database (mysql)
>I found the example log_test14.py that comes with python logging  
>module http://www.red-dove.com/python_logging.html
>but that example is a bit greek for me ... :) and it doesnt work with  
>mysql
>is there some kind of tutorial how to get going if you want to log to  
>a database?
>thanks,
>-frank
>
>___
>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] Percentage

2005-11-08 Thread Johan Geldenhuys




Thanks, that helps.


Jorge Godoy wrote:

  Johan Geldenhuys <[EMAIL PROTECTED]> writes:

  
  
Now that I have the answer (16.801), How do I round it of to 16.80
 ? I only need it to be to the closest 1/100.

  
  
  
  

  
print "%.2f" % 16.801

  

  
  16.80
  
  

  
a = 16.80001
b = "%.2f" % a
b

  

  
  '16.80'
  
  

  
float(b)

  

  
  16.801
  
  

  
str(float(b))

  

  
  '16.8'
  
  
(The reason for the '0001' is because of the numeric base used to
represent data -- binary -- and the numeric base I'm requesting the answer to
be in -- decimal.)


Be seeing you,
  



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


Re: [Tutor] Percentage

2005-11-08 Thread Johan Geldenhuys




Now that I have the answer (16.801), How do I round it of
to 16.80 ? I only need it to be to the closest 1/100.

TIA

Jorge Godoy wrote:

  Frank Moore <[EMAIL PROTECTED]> writes:

  
  
Johan,

You could try:

percentage = (42 * 250)/100

This gives the answer 105.

  
  
And that sounds weird, doesn't it?  42 is smaller than 250, so I'd expect it
to be less than 100% of the value...  In fact, it is 

  
  

  
42.0/250

  

  
  0.16801
  
  

  
(42.0/250)*100

  

  
  16.801
  
  
I suspect the problem is due to the fact that Python does integer division by
default: 

  
  

  
42/250

  

  
  0
  
  
So, how to make it generic?

  
  

  
a = 42
b = 250
a / b

  

  
  0
  
  

  
float(a)/b

  

  
  0.16801
  
  
One of the members has to be a floating point so that floating point division
is performed instead of integer division.


Be seeing you,
  



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


Re: [Tutor] Percentage

2005-11-07 Thread Johan Geldenhuys




Wow, you gave 105% on this one.  ;-)


Frank Moore wrote:

  Johan Geldenhuys wrote:

  
  
Hi all,

What is the syntax if I want to work out what percentage 42 is out of 250?
 


  
  Johan,

You could try:

percentage = (42 * 250)/100

This gives the answer 105.

Cheers,
F.
___
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] Percentage

2005-11-07 Thread Johan Geldenhuys




I have it like that, just thought there could be another way.
 8-) 

Jorge Godoy wrote:

  Johan Geldenhuys <[EMAIL PROTECTED]> writes:

  
  
What is the syntax if I want to work out what percentage 42 is out of 250?

  
  
If you want it as a factor to multiply / divide by something:

perc = 42/250

If you want it to "read" as percentage:

perc_100 = (42/250)*100


Sds,
  



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


[Tutor] Percentage

2005-11-07 Thread Johan Geldenhuys
Hi all,

What is the syntax if I want to work out what percentage 42 is out of 250?

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


Re: [Tutor] Sorting a dictionary

2005-11-04 Thread Johan Geldenhuys




Thanks, Danny.

You see, I didn't put all the keys and values in the dicionary
manually. It was generated while parsing a file with some Python code,
that's why the dict is not in order. I just want to do it to read
easier and look something up.

How will I then put my dict together again after sorting the items, so
that the keys will follow from small to large?

Johan

Danny Yoo wrote:

  
  
  
ser_port = {'4401': 'ds-srvr', \
 '5427': 'sco-peer-tta', \
 '4446': 'n1-fwp', \
 '3734': 'synel-data', \
 '4447': 'n1-rmgmt', \
 '5745': 'fcopy-server', \
 '5990': 'wbem-exp-https', \
 '4026': 'as-debug', \
 '3724': 'battlenet'}

  
  
Hi Johan,

Just as a quick side note: all those continuation characters '\' at the
end of those lines are unneccessary --- Python knows that there's more to
the line because of it's in the middle of a dictionary definition.  So you
can clean things up slightly by doing:

###
ser_port = {
 '4401': 'ds-srvr',
 '5427': 'sco-peer-tta',
 '4446': 'n1-fwp',
 '3734': 'synel-data',
 '4447': 'n1-rmgmt',
 '5745': 'fcopy-server',
 '5990': 'wbem-exp-https',
 '4026': 'as-debug',
 '3724': 'battlenet',
}
###

Everything lines up nicely, and there's a little less line noise.  *grin*

We can even leave a trailing comma on the last key-value pair, just to
make adding more entries into the list easier, as we've done for the
'3724' entry.


I hope this helps!


  



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


[Tutor] Sorting a dictionary

2005-11-04 Thread Johan Geldenhuys
Hi all,
In my new project I needed a dictionary with TCP/UDP port numbers as 
keys and the service for that key as the value.
I got the info from the services file in Linux and compiled a dictionary 
as I needed.

The only thing that I want to do is to sort the dictionary from the 
smallest key number to the largest key number.

Example:

I have:
ser_port = {'4401': 'ds-srvr', \
 '5427': 'sco-peer-tta', \
 '4446': 'n1-fwp', \
 '3734': 'synel-data', \
 '4447': 'n1-rmgmt', \
 '5745': 'fcopy-server', \
 '5990': 'wbem-exp-https', \
 '4026': 'as-debug', \
 '3724': 'battlenet'}

I want:
ser_port = { '3724': 'battlenet', \
'3734': 'synel-data', \
'4026': 'as-debug', \
'4401': 'ds-srvr', \
'4446': 'n1-fwp', \
'4447': 'n1-rmgmt', \
'5427': 'sco-peer-tta', \
'5745': 'fcopy-server', \
'5990': 'wbem-exp-https'}

My dictionary comsists of a few thousand entries and it will not be fun 
to do this manually. How do I sort the dictionary to read better/easier?

TIA,
BTW: If anybody wants this to use, please ask.

Johan

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


Re: [Tutor] Exit from program early

2005-11-03 Thread Johan Geldenhuys
Try using 'sys.exit()' where you want the script to stop if you haven't 
supplied enough arguments.
in you example, it looks like it will go on to the else anyway AND print 
the string at the end.

HTH,
Johan


Roy Bleasdale wrote:

>Hi
>
>In the example below I would like the program to stop if I forgot to 
>provide an argument . Though I could do all my processing indented under 
>the else statement, I was wondering if there was a command that would allow 
>me to halt the program execution early.
>
>Regards,
>
>Roy
>
>
># Example program - Test for valid argument
>
>import sys
>
>if len(sys.argv) < 2:
> print "opps missing an argument"
> # Nice if I could stop and exit program here
>else:
> print "Argument provided!!"
> # Looking good so go do some stuff
>
>print "Done some stuff"
>
>___
>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] printing statement

2005-11-03 Thread Johan Geldenhuys




Found it. This is what I was looking for:
"""
>>> print ('file'+'dir'.center(20))+('\n'+'='*15)
file    dir
===
>>>   
"""

It's actually a string operator 'center(width)' that I was
looking for.

I saw the '%', but that is wahat I wanted to use.

Johan

Colin J. Williams wrote:
bob
wrote:
  
  
  At 11:31 AM 11/3/2005, Johan Geldenhuys
wrote:

 


Hi all,
  
Just a quick question;
  
  
How do I code this output:
  
"""
  
files  dirs
  
==
  
"""
  
  
I want to print something a few space away from the left side or in the
  
middle of the line.
  
   


In the Python Library Reference look up 2.3.6.2 String Formatting
Operations - % interpolation


In general you create a "template" of the desired output with %s (or
other conversion type) wherever you want a value substituted.

"%-15s%-15s" % ('files', 'dirs') will give

"files  dirs   "

"%-15s%-15s" % (filename, directory) will give

"funny.doc  c:\root    "

assuming the variabies filename, directory have the values shown.

the - means left align, 15 is field width. 
___

Tutor maillist  -  Tutor@python.org

http://mail.python.org/mailman/listinfo/tutor


 


  
Have you considered the % formatting operator?
  
See 2.3.6.2 String Formatting Operations in the Library Reference.
  
  
Colin W.
  
  



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


[Tutor] printing statement

2005-11-03 Thread Johan Geldenhuys
Hi all,
Just a quick question;

How do I code this output:
"""
files  dirs
==
"""

I want to print something a few space away from the left side or in the 
middle of the line.

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


Re: [Tutor] Capture command output

2005-11-03 Thread Johan Geldenhuys




The version of python that I have is 2.2.2 and I can't upgrade, sorry.
As far as I know this only from version 2.4.2??

Johan

Kent Johnson wrote:

  Johan Geldenhuys wrote:
  
  
I've been musy with the os command on how to kill a process. That's been 
sorted out to an extend. Many thanks for your input.

Now I have a question in the same direction:

I use os.execpv(cmd, [cmd, args]). That executes the command that have 
output. This was the best way of getting the pid and killing the process 
after a certain time.

How do I capture that output to a file?
Can I use os.popen() or something like that after I did the os.execvp() 
execution or is there a standard way of putting any output in a file/

  
  
Have you tried using subprocess.Popen()? It supports capturing output of the child process and it gives access to the pid of the child.

Kent

  



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


[Tutor] Capture command output

2005-11-02 Thread Johan Geldenhuys
I've been musy with the os command on how to kill a process. That's been 
sorted out to an extend. Many thanks for your input.

Now I have a question in the same direction:

I use os.execpv(cmd, [cmd, args]). That executes the command that have 
output. This was the best way of getting the pid and killing the process 
after a certain time.

This is my code:
import os, signal, time
pid = os.fork()
print 'pid; ',pid
if pid == 0: #child process
   os.execvp('tcpdump', ['tcpdump', '-np'])  # Need syntax to add 
another arg
time.sleep(5) # let it run for 5 seconds
kill(pid) # kill the process

def kill(pid, signal=signal.SIGTERM):
   print "trying to kill pid...", pid
   os.kill(pid, signal)
   os.waitpid(pid, 0)
   print "Killed %d"%pid


How do I capture that output to a file?
Can I use os.popen() or something like that after I did the os.execvp() 
execution or is there a standard way of putting any output in a file/

Thanks,

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


Re: [Tutor] os command

2005-11-02 Thread Johan Geldenhuys
Hugo,

I see that 'os.execcvp()' doesn't actually make two seperate processes. 
The advice you gave me works good. I just had to fgure out with what 
params I should call it. I'm still a bit unsure of how to call the sysem 
command with more than one argument.
This is what I have working now:
"""

import os, signal, time
pid = os.fork()
print 'pid; ',pid
if pid == 0: #child process
  
   #os.execvp('tcpdump', ['tcpdump', '-i modem0 > cap1.txt'])
   os.execvp('ping', ['ping', '127.0.0.1 -c 30 > cap.txt'])
  
time.sleep(5)
kill(pid)

def kill(pid, signal=signal.SIGTERM):
print "trying to kill pid...", pid
os.kill(pid, signal)
os.waitpid(pid, 0)
print "Killed %d"%pid
"""

The ping command is executed but the part where it must put the replies 
in the file is not recognized. How do I use the addisional arguments to 
be seen?

Thanks,

Johan
Hugo González Monteverde wrote:

> In UNIX, you use the fork() exec() technique for starting a new 
> process,  from the very first process(init) onwards. The os.system() 
> uses  a shell
> to do that, or you may do it yourself (in your script)
>
> A "command" is just an executable file running(process), unless you've 
> got a library function that does just that, then you could do what you 
> must without creating a new process.
>
> Probably your best bet would be to use the subprocess module. It was 
> designed around the limitations of the previous methods.
>
> Take a look at what oyu can do with it at:
>
> http://www.python.org/doc/2.4.2/lib/module-subprocess.html
>
> For example, the pid of the command would be available at the pid 
> atribute of a subprocess instance.
>
> p.pid
>
> Hugo   
>
> Johan Geldenhuys wrote:
>
>> Sorry for the late reply,
>> But is it necessary to use a child process? I don't want to execute 
>> the command in another process. What happens with the parent process 
>> and how do I execute my command in the parent process?
>>
>> Thanks
>>
>> Hugo González Monteverde wrote:
>>
>>> Hi,
>>>
>>> os.system will return the errorval of the application. You need to
>>>
>>> 1) get the pid of the child process
>>> 2) kill it using os.kill(os.SIGTERM)
>>> 3) reap the killed process
>>>
>>> This is all in unix/linux, of course.
>>>
>>> what I do (untested, please check order of args and correct usage of 
>>> exec):
>>>
>>> pid = os.fork()
>>>
>>> if pid == 0: #child process
>>> os.execvp("tcpdump", "tcpdump", "-n",  "-i",  "eth0")
>>>
>>> else:   #parent
>>> time.sleep(5)
>>> os.kill(pid, os.SIGTERM)
>>> os.waitpid(pid, 0)   #wait for process to end
>>>
>>>
>>>
>>> Johan Geldenhuys wrote:
>>>
>>>> I have script that calls a system command that I want to run for 5 
>>>> minutes.
>>>> """
>>>> import os
>>>> cmd = 'tcpdump -n -i eth0'
>>>> os.system(cmd)
>>>> """
>>>>
>>>> I can start a timer after the cmd is issued, but I don't know how 
>>>> to send a control signal to stop the command after I issued it. 
>>>> This is normally from the shell  ^c.
>>>>
>>>> This cmd my run in more than one thread on different interfaces and 
>>>> I don't whant all of then stopped at once. I think the best way is 
>>>> to make a thread for each interface where the cmd can be issued and 
>>>> stopped without the danger of stopping he wrong thread.
>>>>
>>>> Can anybody help?
>>>>
>>>> Thanks
>>>>
>>>> Johan
>>>> ___
>>>> 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] Tutorials on the web

2005-11-02 Thread Johan Geldenhuys
Here is a link to a range of tutorials:
http://www.awaretek.com/tutorials.html

Maybe this wil help some people to know where to find a good tutorial 
ona specific subject.

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


[Tutor] Decoding decleration

2005-11-02 Thread Johan Geldenhuys
I receive this error when executing a file:
"Non-ASCII character '\x8b' in file task.py on line 1, but no encoding 
declared".

Can anybody tell me what the encoding is supposed to look like and is it 
standard on all files that is trying to use Non-ASCII characters?

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


Re: [Tutor] os command

2005-11-02 Thread Johan Geldenhuys
Sorry for the late reply,
But is it necessary to use a child process? I don't want to execute the 
command in another process. What happens with the parent process and how 
do I execute my command in the parent process?

Thanks

Hugo González Monteverde wrote:

> Hi,
>
> os.system will return the errorval of the application. You need to
>
> 1) get the pid of the child process
> 2) kill it using os.kill(os.SIGTERM)
> 3) reap the killed process
>
> This is all in unix/linux, of course.
>
> what I do (untested, please check order of args and correct usage of 
> exec):
>
> pid = os.fork()
>
> if pid == 0: #child process
> os.execvp("tcpdump", "tcpdump", "-n",  "-i",  "eth0")
>
> else:   #parent
> time.sleep(5)
> os.kill(pid, os.SIGTERM)
> os.waitpid(pid, 0)   #wait for process to end
>
>
>
> Johan Geldenhuys wrote:
>
>> I have script that calls a system command that I want to run for 5 
>> minutes.
>> """
>> import os
>> cmd = 'tcpdump -n -i eth0'
>> os.system(cmd)
>> """
>>
>> I can start a timer after the cmd is issued, but I don't know how to 
>> send a control signal to stop the command after I issued it. This is 
>> normally from the shell  ^c.
>>
>> This cmd my run in more than one thread on different interfaces and I 
>> don't whant all of then stopped at once. I think the best way is to 
>> make a thread for each interface where the cmd can be issued and 
>> stopped without the danger of stopping he wrong thread.
>>
>> Can anybody help?
>>
>> Thanks
>>
>> Johan
>> ___
>> 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] Talking to UDPServer

2005-11-01 Thread Johan Geldenhuys
I've done some network programming mostly with TCP and I don't think 
that the way the client connects to the server is a lot different (if 
any), The only difference is when you must decide the protcol family. 
"socket.SOCK_DGRAM" will be for UDP and "socket.SOCK_STREAM" will be for 
TCP. After this, the client can connect the same way.

Here is a simpler sample than the one Kent gave:

"""
from socket import *

HOST = 'localhost'
PORT = 3001
BUFSIZ = 1024
ADDR = (HOST, PORT)

tcpCliSock = socket(AF_INET, SOCK_STREAM) # change here for UDP
tcpCliSock.connect(ADDR)

while 1:
data = raw_input('>') # Enter text to be transmitted to the server.
if not data: break
tcpClisock.send(data)
data = tcpCliSock.recv(BUFSIZ)
if not data: break
print data
   
tcpCliSock.close()
"""
HTH,

Johan


Kent Johnson wrote:

> Carroll, Barry wrote:
>
>> Yes, that is exactly what I want.  I need to write a program that 
>> communicates with an existing server, using the UDP protocol.  This 
>> is my first time writing such a program, and I need help getting 
>> started. 
>
>
> Here is an example from Python Network Programming, by John Goerzen. 
> It opens a UDP port, sends a message, then echoes any received text to 
> the console. There is no higher-level support built in to Python, you 
> just open a datagram socket and push data out. Google for "Python udp" 
> for more examples.
>
> Kent
>
> #!/usr/bin/env python
> # UDP Example - Chapter 2
>
> import socket, sys, time
>
> host = sys.argv[1]
> textport = sys.argv[2]
>
> s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
> try:
>port = int(textport)
> except ValueError:
># That didn't work.  Look it up instread.
>port = socket.getservbyname(textport, 'udp')
>
> s.connect((host, port))
> print "Enter data to transmit: "
> data = sys.stdin.readline().strip()
> s.sendall(data)
> s.shutdown(1)
> print "Looking for replies; press Ctrl-C or Ctrl-Break to stop."
> while 1:
>buf = s.recv(2048)
>if not len(buf):
>break
>print "Received: %s" % buf
>
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Talking to UDPServer

2005-10-31 Thread Johan Geldenhuys




Maybe you could tel us if you already have the server listening on the
socket that you expec connections on? If, yes, do you want an example
of how a client connects to that socket?

Johan

Carroll, Barry wrote:

  
  
  
  
  Greetings:
   
  I am writing a
browser-based interface to a server program
which extends SocketServer.UDPServer.  The program listens on a
well-known
socket, receiving commands, verifying them and using their content to
drive our
test hardware, returning status to the client.  The current client
interface is a command line interface that allows the user to type in a
command
and sends it to the server, receives the status response and displays
it for
the user.  My job is to duplicate the client functionality in a set of
web
pages.  
   
  My problem is that, while
I can find documentation on
UDPServer, I cannot find anything on how a remote client talks to the
server.  How is this done in Python?  Can someone point me to a
how-to, tutorial or the like?  
   
  Thanks in advance.
   
  Barry
   
   
   
  
  

___
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] compare

2005-10-31 Thread Johan Geldenhuys
In your code that line is not executed. And if it was at some stage, it 
will give you an error.
max_item is a list and you cannot put a string and a list together:  
"TypeError: cannot concatenate 'str' and 'list' objects".

What are trying to do with this line? 'maximum = 0' and so product will 
be greater than maximum. It looks you are trying to append a list to seq 
that is already there?
Maybe it's a bad guess from me, I'm no expert.

Johan

Shi Mu wrote:

>What does this line 11 mean in the following code?
>
>1 # calc.py
>2 def calc(seq):
>3   maximum = 0
>4   max_item = []
>5   for i in seq:
>6 product = (i[0]*100 + i[1]*10 + i[2]) * (i[3]*10 + i[4])
>7 if product > maximum:
>8maximum = product
>9max_item = i
>   10 elif product == maximum:
>   11max_item += ','+i
>   12   return max_item, maximum
>   13
>   14 seq = [ [5,6,7,8,9], [5,6,7,9,8] ]
>   15 max_item, maximum = calc(seq)
>   16 print "Maximum at", max_item, ",product", maximum
>___
>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] Random number generator (was: Can anyone help me?)

2005-10-28 Thread Johan Geldenhuys




After I tested the previous code, I noticed that the odds is 1:49 that
a duplicate number can be found in the 6 digit range (and it happended)
and that 0 can also be found.

Here is the fix:

import random

def randnum():
    c = []
    for x in range(6):
    s = random.randrange(0, 50)
    if s not in c:
   c.append(s)
    else:
    return
    print ('Randoms: ',c)
    
    c = []
    
if __name__ == '__main__':
   
   for x in range(10): # For number of 6-digit sequences
   randnum()

AYS?

  
R. Alan Monroe wrote:
  

  Hey all,
I am trying to create a program that draws 6 numbers between 1 and 49 at random for creating lottery tickets. I want to have a better chance when I play. Can anyone help me code this or show me how
to, please?



Create (empty for now) list to hold your final numbers.
Have a for-loop that runs 6 times using range(6)
Inside the loop, just pick a random number and append it to your final
number list.

Alan

___
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] Can anyone help me?

2005-10-28 Thread Johan Geldenhuys




>>> def randnum():
...           c = []
...   for x in range(6):
... s = random.randrange(50)
... c.append(s)
...   print 'Randoms: ',c
...   c = []


This works good !!

Johan

R. Alan Monroe wrote:

  
Hey all,
I am trying to create a program that draws 6 numbers between 1 and 49 at random for creating lottery tickets. I want to have a better chance when I play. Can anyone help me code this or show me how
to, please?

  
  
Create (empty for now) list to hold your final numbers.
Have a for-loop that runs 6 times using range(6)
Inside the loop, just pick a random number and append it to your final
number list.

Alan

___
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] OT - Re: Can anyone help me?

2005-10-28 Thread Johan Geldenhuys




Any chance of winning  £25million is a good one.  ;-) 


Ed Singleton wrote:

  You can actually increase your chance of winning in the English lottery.

If two many tickets win a prize in one draw, the lowest prize (£10 for
three numbers) is not paid out.

Also the jackpot is shared between all the winning tickets (6 numbers)
some sets of numbers like 1,2,3,4,5,6 are chosen by over 20,000 people
a week.  You would share the jackpot with 20,000 other people.

Picking random numbers makes you less likely to chose the same numbers
as everyone else.

Incidently, the odds of winning the jackpot are 1 in 14 million
(roughly).  I've seen the jackpot go up to £25million which makes it
theoretically a good bet.

Ed

On 28/10/05, bob <[EMAIL PROTECTED]> wrote:
  
  
At 07:07 PM 10/27/2005, Nathan Pinno wrote:


  Hey all,
I am trying to create a program that draws 6 numbers between 1 and 49 at
random for creating lottery tickets. I want to have a better chance when I
play.
  

Define "better chance". Lottery odds are how many tickets you buy relative
to how many tickets everyone else has bought. No program will improve or
degrade your odds. The only way you can reduce your odds is to buy more
than one ticket with the same numbers.

Keep in mind that a lottery is as truly random as one can get (assuming no
rigging). There is no memory of past outcomes involved nor of better
guessing techniques.

___
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] os.system sending of break signals

2005-10-28 Thread Johan Geldenhuys
With what can I try and see what the PID is when using popen() or popen2() ?

One thing that I noticed now is that when using popen() and the 
sys.exit(). The command is completed before my Python shell is 
terminated and if I use popen2(), sys.exit() works immediately but the 
ping command runs still as a process untill completed.



Alan Gauld wrote:

>> >>> f = os.popen2('ping 192.168.8.85 -c 100 > cap1.txt')
>> >>> f[0].write('\x03')
>>
>> Thank command works, but 'f[1]' is in read-only mode and I can't 
>> write to it.
>> My command in the background is still not terminated.
>
>
> Thats almost certainly because ping never reads its input.
> In that case you'll need to send a kill signal to the process and
> to do that you need to find the process ID. I'm not sure if popen() 
> provides access to the PID but if not you could either search for it 
> (this might be too slow) or just drop down to use fork rather than 
> popen, as fork will return the PID.
>
>
> Alan G.
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] os.system sending of break signals

2005-10-28 Thread Johan Geldenhuys
If I use popen2, I need to write to one of the tuple parts.
 >>> f = os.popen2('ping 192.168.8.85 -c 100 > cap1.txt')
 >>> f[0].write('\x03')

Thank command works, but 'f[1]' is in read-only mode and I can't write 
to it.
My command in the background is still not terminated.

BTW I use Linux as OS.

So, it doesn't work.


Alan Gauld wrote:

>> >>> f = os.popen('ping 192.168.8.85 -c 100 > cap2.txt')
>>
>> You will see that I send the output from the command to a file, 
>> because I want to test how stop the command before it reaches 100 pings.
>> If I don't write the output to the file 'cap2.txt' and succeeds in 
>> closing 'f', all the data returned to 'f' will be lost.
>
>
> You can read the output of popen into your program with
> f.read(), but that will read all of the output after the program has 
> run. However I think you can readline() too to catch it line by line. 
> You can also write() data to f thus allowing you to send your 
> Ctrl-C.(You may need popen2 or even popen3 to do the simultaneous 
> read//write bit. #Or better still use the new subprocess module in v2.4)
>
> Does that do what you need?
>
> Alan G
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] os.system sending of break signals

2005-10-28 Thread Johan Geldenhuys
So far:
I tried
 >>> f = os.popen('ping 192.168.8.85 -c 100 > cap2.txt')

You will see that I send the output from the command to a file, because 
I want to test how stop the command before it reaches 100 pings.
If I don't write the output to the file 'cap2.txt' and succeeds in 
closing 'f', all the data returned to 'f' will be lost.

If i use:
 >>>f.close()
Then 'f' is not closed and the commands until 100 packets has been send.

So, I am still looking for a way to stop the command before it 
terminates by itself. I will not be able to get the process ID in all he 
cases to kill it that way.

Then I tried :
 >>> f = os.popen2('ping 192.168.8.85 -c 100 > cap3.txt')
 >>> f
(', mode 'w' at 0x40389530>, ', 
mode 'r' at 0x404a69f8>)
 >>> f[0].close()
 >>> f[1].close()
 >>> f
(', mode 'w' at 0x40389530>, ', mode 'r' at 0x404a69f8>)

This as you can see closes the fd's but the command is not terminated, 
because I can see my filesize is growing.

Any other Ideas or what am I doing wrong?

TIA,

Alan Gauld wrote:

>> I send a command to os.system(cmd) and want to send a break signal in 
>> the same way. Is this possible? The break signal is ctrl c (^c).
>> I tried this, but it didn't work: os.system('\x03') I think Hex 03 is 
>> the signal for ctrl c.
>
>
> Its not possible with os.system because os.system runs the called 
> program to completion in a separate process. You would need to mess 
> about with threads and process ids to do it that way. However if you 
> use popen() (or maybe popen2()? )you should be able to send a Ctrl-C 
> character to the process. However whether that actually terminates it 
> will depend on the OS, the process and whether Ctrl-C is being caught 
> anywhere. But at least there's a chance of it working!
>
> HTH,
>
> Alan G
> Author of the learn to program web tutor
> http://www.freenetpages.co.uk/hp/alan.gauld
>
>
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] os.system sending of break signals

2005-10-27 Thread Johan Geldenhuys
Hi all,
I send a command to os.system(cmd) and want to send a break signal in 
the same way. Is this possible? The break signal is ctrl c (^c).
I tried this, but it didn't work: os.system('\x03') I think Hex 03 is 
the signal for ctrl c.

Thanks,


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


Re: [Tutor] os command

2005-10-26 Thread Johan Geldenhuys




So, for a newbie like me I might struggle with this one  :-( 

I saw that the thread in comp.lang.python talks about a deamon flag for
a thread. This sounds like a idea that could work. I don't know how to
use that, but will use the example given there.

Thanks.

Kent Johnson wrote:

  Johan Geldenhuys wrote:
  
  
I have script that calls a system command that I want to run for 5 minutes.
"""
import os
cmd = 'tcpdump -n -i eth0'
os.system(cmd)
"""

I can start a timer after the cmd is issued, but I don't know how to 
send a control signal to stop the command after I issued it. This is 
normally from the shell  ^c.

  
  
This is problematic. In general there is no clean way to kill a thread in Python. The usual approach is to set a flag which the thread checks but this won't work for you.

A recent thread in comp.lang.python has some discussion and suggestions but it is inconclusive:
http://groups.google.com/group/comp.lang.python/browse_frm/thread/94281f5a797489b1/ebca44930a016f74?q=os.system+thread&rnum=5&hl=en#ebca44930a016f74

Kent
  



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


[Tutor] os command

2005-10-26 Thread Johan Geldenhuys
I have script that calls a system command that I want to run for 5 minutes.
"""
import os
cmd = 'tcpdump -n -i eth0'
os.system(cmd)
"""

I can start a timer after the cmd is issued, but I don't know how to 
send a control signal to stop the command after I issued it. This is 
normally from the shell  ^c.

This cmd my run in more than one thread on different interfaces and I 
don't whant all of then stopped at once. I think the best way is to make 
a thread for each interface where the cmd can be issued and stopped 
without the danger of stopping he wrong thread.

Can anybody help?

Thanks

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


Re: [Tutor] new user question about while loops

2005-10-26 Thread Johan Geldenhuys




I am confused. It looks to me as if the while loop will never work,
because it stays inside while <100 and further down in the loop, if
it is < 100, it should go out of the loop. How can it stay running
while <100 and yet go out if  < 100?

Johan
 

Nick Eberle wrote:

  
  
  print
"This is a coin flip game"
   
  print
"\n100 flips will be made and it will show the amount of times heads or
tails came up"
   
  
  import
random
  
#assigning variables to track the amount of times heads or tails comes
up
  heads=0
tails=1
   
  flip=100
while flip < 100:
    flip -= 1
    random.randrange(2)
    if flip < 100:
    break
   
  print
"\nThe amount of times tails came up was" , tails , "The amount of
times heads came up was" , heads
   
  raw_input()
  
  
  
  
  From: bob
[mailto:[EMAIL PROTECTED]]
  Sent: Tue 10/25/2005 10:58 PM
  To: Nick Eberle; tutor@python.org
  Subject: Re: [Tutor] new user question about while loops
  
  
  At 10:53 PM 10/25/2005, Nick Eberle wrote:
  Content-class:
urn:content-classes:message
Content-Type: multipart/alternative;
boundary="_=_NextPart_001_01C5D9F1.A836CF4F"

Sorry for potential double post, error with first
send
--
Hello all,
 
I had a new question about python. I am
pretty much in tutorial learning stages, but attempting to create
sample programs not in my book to learn how to construct scripts.
 
I understand the format of while loops,
but is it possible to use the random.randrange function in them?
 
My goal, create a program that flips a
coin 100 times, at the end it says the number of times it flipped heads
and flipped tails.
 
My dilemia, how do I get this to work
with a while loop? I tried intially assigning
 
heads=0
tails=1
 
then I figured I could just do a while
loop and then use the random function each time. At the end it could
count the number of times the random generated a 0 or a 1.
 
However I can't seem to construct it in
a way that makes or works. 
  
Show us your code, as flawed as it might be. Then we can advise you.
  

___
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] "Decompile" pyc file

2005-10-20 Thread Johan Geldenhuys




When I want to download the zip file from the source, I get the error
that the page does not exist. Where can I get it?

Thanx.

Bernard Lebel wrote:

  Sorry for the late reply.

Thanks a lot Kent, that was really helpful.


Bernard



On 10/14/05, Kent Johnson <[EMAIL PROTECTED]> wrote:
  
  
Bernard Lebel wrote:


  Hello,

Is there a way to "decompile" a pyc file? I have a big problem where
the py file was lost, but the pyc file is instact. I would need to
extract the source code from the pyc file.
  

Google 'python decompiler'

try http://www.freshports.org/devel/decompyle/
or the commercial service at http://www.crazy-compilers.com/decompyle/

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

  



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


Re: [Tutor] guidance for web site development

2005-10-14 Thread Johan Geldenhuys
I am also looking for a good tutorial on this subject. Have you tried 
http://www.modpython.org/ ?
I think that the mod_python mailing list will be a better place to ask. 
I'm going to.

Johan

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 deriviant 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.
>
>thanks in advance.
>
>Nitin Chandra
>___
>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] PLC programming with Python?

2005-10-12 Thread Johan Geldenhuys
Hi all,
Can Python be used to do PLC (programmable logic controller) 
programming? I'm not sure because Python needs some platform to run on?

Thanks,

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


Re: [Tutor] Stopping function after given time

2005-10-10 Thread Johan Geldenhuys
You can use the Timer in threading. Look at what is done in the attached 
script. You can basically use three functions to start the timer, stop 
the timer and do what ever it is to be done upon expiring.


There maybe easier ways, but this will work. You can call the 
start_timer with a time in seconds and then it will terminate and there 
you can call a different function that does the rest of your stuff.


Johan.

Raduz wrote:


Hi all
Simple question: Is it possible to stop a running function after certain 
predefined time? 

Right now I have some home-made bash scripts for recording shows from net 
broadcasted ogg stream, that use wget for stream downloading, and two "at" 
jobs - one for first script (which prepares directory it's going to save to, 
dumps info about it's own PID, and execs wget for actual download), second for 
another script (which reads PID info dumped by the first script, uses it to 
kill wget and performs some clean-up tasks). 
I would like to convert this routine to Python using pycurl module, or maybe 
even standard urllib.urlretrieve. Problem is, downloaded file is a stream 
without end, so I have to stop the downloader manually, and I would prefer to 
drop the "two scripts" approach - no more PID saving and process killing. I 
want one clean package, which will start the download, let it run for some 
time, and then stop it correctly. I just don't know how to time the download. 
Can anybody give some sugestions, please? Is the threading way to go? Thanks.


 

"""
  This module is helpful when something must be done on a timer.
  It is for testing purposes but the main class can be used in other applications
  with modifications to the timerExpired function. You can put your own stuff in there
  that must happen when the timer has expired.
  
  It is used by executing it from the shell with arguments -t, -s and optional -x.
  argument -t: timer duration in seconds.
  argument -s: choice to stop the timer after a default 5 seconds,
  optional -x: if -s was 'y' and an delay in seconds before the timer must be stopped.
  
  
  Author: J Geldenhuys
  AccessTel
  Date  : 2005-08-11
  
"""

# The threading module is used that has the code to start
# and stop the timer instance, so, why not use it?
from threading import Timer

# time module is imported to sleep a while after timer is started 
# before stopping it.
import time

# Main class to get timer instance going
class timer:
  
  # start timer with n seconds and go to self.timerExpired
  def startTimer(self, n):
self.t = Timer(n, self.timerExpired)
print 'Timer started for %d seconds'% n

#start the timer instance
self.t.start()

  # Called if argument is true to stop it.
  def stopTimer(self):

# First look if the timer is active
if self.t.isAlive():
print 'Timer found active'

#Stop the timer instance
self.t.cancel()
print 'Timer stopped'

# If not active, do nothing
else:
print 'Timer inactive'

  # Put code in here to execute after timer has expired.
  def timerExpired(self):
print 'Timer expired, go to do what you want'

# Help the user understand how to use this module
def printUsageAndExit():
print
print "Usage: %s -t[time-out] "\
  "-s[sleep before stopping, 'y' or 'n'] \r\noptional -x[seconds to wait before stopping]\r\n\r\n"\
  "Example: timertest.py -t 10 -s y -x 6\r\n" % sys.argv[0]
print
sys.exit(1)


if __name__ == '__main__':

import sys, getopt, string

l = (len(sys.argv))

if l <= 4:
   printUsageAndExit()
arg3 = int('5')
optlist, args = getopt.getopt(sys.argv[1:], "t:s:x:")
for opt in optlist:

if opt[0] == '-t':
   if not (opt[1].isdigit()):
  printUsageAndExit()
   arg1 = int(opt[1])
   
elif opt[0] == '-s':
   arg2 = (opt[1])
  
   #printUsageAndExit()
   
   
elif opt[0] == '-x':
   if not (opt[1].isdigit()):
  printUsageAndExit()
   arg3 = int(opt[1])
   

x = timer()
if arg2 == 'y':
   x.startTimer(arg1)
   time.sleep(arg3)
   print 'You chose to stop the timer after %s with option %s'%(str(arg3), arg2)
   x.stopTimer()
   
if arg2 == 'n':
   x.startTimer(arg1)
   
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Console output

2005-10-05 Thread Johan Geldenhuys

This might help. Never used it though.

Johan


Christian Wyglendowski wrote:


> -Original Message-
 

From: [EMAIL PROTECTED] 
[mailto:[EMAIL PROTECTED] On Behalf Of Oliver Maunder

Sent: Wednesday, October 05, 2005 1:13 PM
To: tutor@python.org
Subject: [Tutor] Console output

Does anyone know how I can update a line of console output 
without creating a new line? 
   



Hi Oliver,

If you are on a *nix system, check out the "curses" package in the
standard library.  I have never used it, but it provides ways to
accomplish what you are after.

HTH,

Christian
http://www.dowski.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

 

class progressBar:
	def __init__(self, minValue = 0, maxValue = 10, totalWidth=12):
		self.progBar = "[]"   # This holds the progress bar string
		self.min = minValue
		self.max = maxValue
		self.span = maxValue - minValue
		self.width = totalWidth
		self.amount = 0   # When amount == max, we are 100% done 
		self.updateAmount(0)  # Build progress bar string

	def updateAmount(self, newAmount = 0):
		if newAmount < self.min: newAmount = self.min
		if newAmount > self.max: newAmount = self.max
		self.amount = newAmount

		# Figure out the new percent done, round to an integer
		diffFromMin = float(self.amount - self.min)
		percentDone = (diffFromMin / float(self.span)) * 100.0
		percentDone = round(percentDone)
		percentDone = int(percentDone)

		# Figure out how many hash bars the percentage should be
		allFull = self.width - 2
		numHashes = (percentDone / 100.0) * allFull
		numHashes = int(round(numHashes))

		# build a progress bar with hashes and spaces
		self.progBar = "[" + '#'*numHashes + ' '*(allFull-numHashes) + "]"

		# figure out where to put the percentage, roughly centered
		percentPlace = (len(self.progBar) / 2) - len(str(percentDone)) 
		percentString = str(percentDone) + "%"

		# slice the percentage into the bar
		self.progBar = self.progBar[0:percentPlace] + percentString + 
self.progBar[percentPlace+len(percentString):]

	def __str__(self):
		return str(self.progBar)

==

import time
prog = progressBar(0, 100, 77)
for i in xrange(101):
prog.updateAmount(i)
print prog, "\r",
time.sleep(.05)

==

# Best not to print it every iteration, Terry Carroll, 2004/01/26
#  It can be a substantial performance hit to print the bar every iteration, whether it changes or not. At 100 iterations, like Josiah's' example, it changes every iteration, so it won't' matter. But if you have more than a few thousand, it's' worth checking and not printing an unchanged bar: 
limit = 100

prog = progressBar(0, limit, 77)
oldprog = str(prog)
for i in xrange(limit+1):
prog.updateAmount(i)
if oldprog != str(prog):
print prog, "\r",
oldprog=str(prog)
print
=

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


Re: [Tutor] Python Editors (particualrly Vim)

2005-09-22 Thread Johan Geldenhuys




jedit is also good. I use that. The only thing is that you can't execute the script from there. It is great for collapsing at indentions.
www.jedit.org

Johan
On Thu, 2005-09-22 at 13:54 +0100, Ed Singleton wrote:


Okay, I've also found this:
http://cream.sourceforge.net/features.html

Which is amazing!  It's an easy-to-use mod for Vim.  It's modeless and
lots of other doubtless heretical things, but it includes an
outstanding auto-complete mode for text files!  Ctrl-Space auto
completes the word you're typing based on what you've already written
in the file.

I've also been trying SPE and that looks to be the most pleasing
editor so far.  It's also written in Python (AFAICT) which will
probably have benefits in the future.

Ed

On 21/09/05, Ed Singleton <[EMAIL PROTECTED]> wrote:
> I don't believe there's any kinds of wars on this mailing group.  :)
>
> I found this Python Vim code completion thing in my searches today:
> http://freshmeat.net/projects/pydiction/
>
> Don't know how good it is, but it looks like it'd do the job.
>
> Ed
>
> On 21/09/05, Gabriel Farrell <[EMAIL PROTECTED]> wrote:
> > Uh oh, looks like you're begging for an editor war.
> >
> > That said, I'm in the vim camp.  It can do everything you specified
> > for all of the languages you mention (well, I'm not sure about
> > collapsible code...web search...aha![1]).  After using it for four
> > years, I'm still learning new tricks (see, for example, this page I
> > found today on indentation[2]).
> >
> > vim's extendable with python scripts, but a lot of what you need for
> > coding is already built in.  I find most of my info either in the help
> > manual that comes with it (:h) or at vim.org.
> >
> > gsf
> >
> > [1] http://www.dgp.toronto.edu/~mjmcguff/learn/vim/folding.txt
> > [2] http://www.vim.org/tips/tip.php?tip_id=83
> >
> >
> > On Wed, Sep 21, 2005 at 02:00:20PM +0100, Ed Singleton wrote:
> > > I've been trying to decide which editor to use to edit Python (on
> > > Windows mostly).
> > >
> > > My wishlist of features would be:
> > >
> > > - automatic code formatting (indentation etc)
> > > - collapsible code (to collapse def's etc)
> > > - automatic code coloring (that's easily changeable)
> > > - auto-completion of namespaces
> > > - easy to run scripts from the editor (a shortcut key to run them or something)
> > >
> > > As I also do a lot of html, css and _javascript_ it would be cool to
> > > have an editor that could also handle them, in which case I would want
> > > the same features for those languages, as well as the ability to write
> > > macros, scripts, etc in python.
> > >
> > > Having looked at loads of editors, I've ended up looking at emacs and vim.
> > >
> > > Emacs seems too difficult with not enough support for using the mouse.
> > >
> > > Vim seemed better, and I get the impression that it is possible to use
> > > python to script the editor, but I can't find much information on
> > > using vim as a python editor on windows.
> > >
> > > My various questions are:
> > >
> > > What other features should I be looking for?
> > >
> > > What would be the best editor for a beginner to start using, with a
> > > view to the long term?
> > >
> > > Where can I find some authoritative information about setting emacs or
> > > vim up as a fully featured python editor?
> > >
> > > Thanks
> > >
> > > Ed
> > > ___
> > > 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


  1   2   >