Threading problem / Paramiko problem ?

2009-12-28 Thread mk

Hello everyone,

I wrote "concurrent ssh" client using Paramiko, available here: 
http://python.domeny.com/cssh.py


This program has a function for concurrent remote file/dir copying 
(class SSHThread, method 'sendfile'). One thread per host specified is 
started for copying (with a working queue of maximum length, of course).


It does have a problem with threading or Paramiko, though:

- If I specify, say, 3 hosts, the 3 threads started start copying onto 
remote hosts fast (on virtual machine, 10-15MB/s), using somewhat below 
100% of CPU all the time (I wish it were less CPU-consuming but I'm 
doing sending file portion by portion and it's coded in Python, plus 
there are other calculations, well..)


- If I specify say 10 hosts, copying is fast and CPU is under load until 
there are 2-3 threads left; then, CPU load goes down to some 15% and 
copying gets slow (at some 1MB/s).


It looks as if the CPU time gets divided in more or less even portions 
for each thread running at the moment when the maximum number of threads 
is active (10 in this example) *and it stays this way even if some 
threads are finished and join()ed *.


I do join() the finished threads (take a look at code, someone). Yet the 
CPU consumption and copying speed go down.


Now, it's either that, or Paramiko "maxes out" sending bandwidth per 
thread to the "total divided by number of senders". I have no idea which 
and what's worse, no idea how to test this. I've done profiling which 
indicated nothing, basically all function calls except time.sleep take 
negligible time.


Regards,
mk

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


Re: Threading problem / Paramiko problem ?

2009-12-28 Thread MRAB

mk wrote:

Hello everyone,

I wrote "concurrent ssh" client using Paramiko, available here: 
http://python.domeny.com/cssh.py


This program has a function for concurrent remote file/dir copying 
(class SSHThread, method 'sendfile'). One thread per host specified is 
started for copying (with a working queue of maximum length, of course).


It does have a problem with threading or Paramiko, though:

- If I specify, say, 3 hosts, the 3 threads started start copying onto 
remote hosts fast (on virtual machine, 10-15MB/s), using somewhat below 
100% of CPU all the time (I wish it were less CPU-consuming but I'm 
doing sending file portion by portion and it's coded in Python, plus 
there are other calculations, well..)


- If I specify say 10 hosts, copying is fast and CPU is under load until 
there are 2-3 threads left; then, CPU load goes down to some 15% and 
copying gets slow (at some 1MB/s).


It looks as if the CPU time gets divided in more or less even portions 
for each thread running at the moment when the maximum number of threads 
is active (10 in this example) *and it stays this way even if some 
threads are finished and join()ed *.


I do join() the finished threads (take a look at code, someone). Yet the 
CPU consumption and copying speed go down.


Now, it's either that, or Paramiko "maxes out" sending bandwidth per 
thread to the "total divided by number of senders". I have no idea which 
and what's worse, no idea how to test this. I've done profiling which 
indicated nothing, basically all function calls except time.sleep take 
negligible time.



From what I can see, your script basically does a "busy wait" in
mainprog(), repeatedly checking whether any threads have finished.

It might use less CPU time if you used the Queue module and the threads
informed the main loop of their progress and when they are about to
finish by putting messages in the queue. The main loop would get the
messages from the queue, updating the progress display or starting a new
thread as appropriate. It wouldn't be constantly polling the threads.
--
http://mail.python.org/mailman/listinfo/python-list


socket problem and html problem

2010-10-10 Thread bussiere bussiere
here is my code and two questions :
why it says to me that i can't bind the socket ?
normally it had closed it and kill it :/
and why it returns me plain text and not html ?

Regards and a pack of m&m's to the one who will help me on this two
questions.


import socket
import sys
# Create a TCP/IP socket



class Serverhttp:
def __init__(self):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 2)
print >>sys.stderr, 'starting up on %s port %s' % server_address
sock.bind(server_address)
# Listen for incoming connections
sock.listen(1)
off = 2
self.message = ""
while True:
# Wait for a connection
print >>sys.stderr, 'waiting for a connection'
if off == 2 or off == 1:
connection, client_address = sock.accept()
try:
print >>sys.stderr, 'connection from', client_address

# Receive the data in small chunks and retransmit it
while True:
if off == 1:
sock = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
server_address = ('localhost', 17000)
sock.bind(server_address)
connection, client_address = sock.accept()
off = 0
data = connection.recv(1024)
print >>sys.stderr, 'received "%s"' % data
if data:
self.message = self.traitement(data)
connection.sendall(self.message)
connection.close()
sock.close()
del(sock)
off = 1
else:
print >>sys.stderr, 'no more data from',
client_address
break

finally:
# Clean up the connection
connection.close()


def traitement(self,string):
return
"Content-type:text/html;charset=utf8\n\ntest"
if __name__ == "__main__":
s = Serverhttp()

Google Fan boy
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: win32com problem - Problem Solved

2006-10-25 Thread cfriedalek
Problem solved.

Turns out it was a problem of mistranslating VBS code to Python.

The PYTHON line "print str(tet)" casts tet to a string and prints. This
is what I thought the VBS line "Str = Tet.ConvertToString()" was doing.
But of course "ConvertToString()" is a method of a Tet instance. So in
python the correct line should have been "print tet.ConvertToString".

Learning all the time.

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


Problem

2009-10-15 Thread Ander
I can't send emails out. Can u fix this problem please?


The
message could not be sent. The authentication setting might not be
correct for your outgoing e-mail [SMTP] server. For help solving this
problem, go to Help, search for "Troubleshoot Windows Mail", and read
the "I'm having problems sending e-mail" section. If you need help
determining the proper server settings, please contact your e-mail
service provider.

The rejected e-mail address was
'antraxak_1...@hotmail.com'. Subject 'adasf', Account: 'mail.hot.ee',
Server: 'mail.hot.ee', Protocol: SMTP, Server Response: '550 5.7.1
: Recipient address rejected: Mail
appeared to be SPAM or forged. Ask your Mail/DNS-Administrator to
correct HELO and DNS MX settings or to get removed from DNSBLs; MTA
helo: rulltukkpc, MTA hostname:
86-43-219-112-dynamic.b-ras2.bbh.dublin.eircom.net[86.43.219.112]
(helo/hostname mismatch)', Port: 25, Secure(SSL): No, Server Error: 550,
Error Number: 0x800CCC79

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


problem

2009-08-08 Thread sumit
i want 2 hav the header files for regular expression to non
deterministin autometa
so whr should i find it?plz help
-- 
http://mail.python.org/mailman/listinfo/python-list


problem

2015-12-04 Thread Dylan Goodwin
Every time I try and run python 3.5 it keeps coming up with modify, repair
or uninstall
-- 
https://mail.python.org/mailman/listinfo/python-list


Problem

2015-12-08 Thread Namrah Anwar
Dear Administration,

I am Namrah Anwar writing to you from Pakistan. I downloaded Python version
3.5.1 and 2.7 and after installation at first, upon opening again it asked
for Modify, repair or uninstall options. I tried to fix it but could not.
Can you please help me out how to fix this and why it is asking every time
for same option?

Thanking you in anticipation.

-- 


*Regards,Namrah Anwar*
*PhD Student (Fellowship) - Cancer Biology - Agha Khan University-Karachi*
*Masters in Health care Biotechnology  (ASAB) NUST, Islamabad*
*Pakistan.*
-- 
https://mail.python.org/mailman/listinfo/python-list


problem

2016-01-14 Thread Shivam Gupta
Hello,

I am using python 3.5.1 on my windows 8.1. The problem is that whenever i
save any file any after that when i run it the screen just close
immediately after i double click on python file.

Thank you.
-- 
https://mail.python.org/mailman/listinfo/python-list


Problem

2017-07-20 Thread Hongze Liu
Hello Python,

I encountered this problem:
 File "C:\Users\Hongze\AppData\Local\Programs\python\Python36\lib\runpy.py",
line 193, in _run_module_as_main
"__main__", mod_spec)
  File "C:\Users\Hongze\AppData\Local\Programs\python\Python36\lib\runpy.py",
line 85, in _run_code
exec(code, run_globals)
  File "ok\__main__.py", line 46, in 
  File "ok\client\cli\ok.py", line 201, in main
  File "ok\client\protocols\rate_limit.py", line 41, in run
  File "ok\client\utils\storage.py", line 28, in get
  File "ok\client\utils\storage.py", line 18, in contains
  File "C:\Users\Hongze\AppData\Local\Programs\python\Python36\lib\shelve.py",
line 243, in open
return DbfilenameShelf(filename, flag, protocol, writeback)
  File "C:\Users\Hongze\AppData\Local\Programs\python\Python36\lib\shelve.py",
line 227, in __init__
Shelf.__init__(self, dbm.open(filename, flag), protocol, writeback)
  File 
"C:\Users\Hongze\AppData\Local\Programs\python\Python36\lib\dbm\__init__.py",
line 94, in open
return mod.open(file, flag, mode)
  File "C:\Users\Hongze\AppData\Local\Programs\python\Python36\lib\dbm\dumb.py",
line 324, in open
return _Database(file, mode, flag=flag)
  File "C:\Users\Hongze\AppData\Local\Programs\python\Python36\lib\dbm\dumb.py",
line 71, in __init__
self._update()
  File "C:\Users\Hongze\AppData\Local\Programs\python\Python36\lib\dbm\dumb.py",
line 106, in _update
key, pos_and_siz_pair = _ast.literal_eval(line)
  File "C:\Users\Hongze\AppData\Local\Programs\python\Python36\lib\ast.py",
line 48, in literal_eval
node_or_string = parse(node_or_string, mode='eval')
  File "C:\Users\Hongze\AppData\Local\Programs\python\Python36\lib\ast.py",
line 35, in parse
return compile(source, filename, mode, PyCF_ONLY_AST)
ValueError: source code string cannot contain null bytes


I attempted to reinstall python and used "Repair" option, however, the
issue still exists.

Thanks
-- 
https://mail.python.org/mailman/listinfo/python-list


Problem!!

2011-07-03 Thread amir chaouki
i have written code on linux for parsing text files and it works great
but when i try to run it on windows it goes crazy, do you have any
idea???
-- 
http://mail.python.org/mailman/listinfo/python-list


problem

2018-10-04 Thread Rémy Dpx
Hello,
I’ve got a problem with my Python.
Indeed my Idle act like if my ctrl button were always pushed ( when i press Q, 
it selects everything ; when i press W, it goes back in the last form)
I tried to uninstall and download back and also to change the version, but my 
problem is still there.
I hope u will give me a solution.
Thanks.
Rémy


---
L'absence de virus dans ce courrier électronique a été vérifiée par le logiciel 
antivirus Avast.
https://www.avast.com/antivirus
-- 
https://mail.python.org/mailman/listinfo/python-list


Problem

2020-09-29 Thread Ron Villarreal via Python-list
Tried to open Python 3.8. I have Windows 10. Icon won’t open.
-- 
https://mail.python.org/mailman/listinfo/python-list


problem

2020-01-17 Thread mrunali


I am face a problem to download MySQL for python as well as I can not able to 
install kivy on my laptop . please give me solution for it .
Sent from Mail for Windows 10

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


Re: socket problem and html problem

2010-10-14 Thread Stefan Behnel

bussiere bussiere, 11.10.2010 08:30:

here is my code and two questions :
why it says to me that i can't bind the socket ?
normally it had closed it and kill it :/
and why it returns me plain text and not html ?


I think the reason why no-one answered yet is that it's not immediately 
clear what you are talking about. You posted a bunch of source code with 
basically no introduction to it, and the tiny bit of textual context that 
you provide is not easy to understand either. Try to make it easier for 
others to help you.


Give this a read:

http://www.catb.org/esr/faqs/smart-questions.html

Stefan

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


Classical FP problem in python : Hamming problem

2005-01-23 Thread Francis Girard
Hi,

First,

My deepest thanks to Craig Ringer, Alex Martelli, Nick Coghlan and Terry Reedy 
for having generously answered on the "Need help on need help on generator" 
thread. I'm compiling the answers to sketch myself a global pictures about 
iterators, generators, iterator-generators and laziness in python.

In the meantime, I couldn't resist to test the new Python features about 
laziness on a classical FP problem, i.e. the "Hamming" problem.

The name of the game is to produce the sequence of integers satisfying the 
following rules :

(i) The list is in ascending order, without duplicates
(ii) The list begins with the number 1
(iii) If the list contains the number x, then it also contains the numbers 
2*x, 3*x, and 5*x
(iv) The list contains no other numbers.

The algorithm in FP is quite elegant. Simply suppose that the infinite 
sequence is produced, then simply merge the three sequences (2*x,3*x,5*x) for 
each x in the infinite sequence we supposed as already produced ; this is 
O(n) complexity for n numbers.

I simply love those algorithms that run after their tails.

In haskell, the algorithm is translated as such :

-- BEGIN SNAP
-- hamming.hs

-- Merges two infinite lists
merge :: (Ord a) => [a] -> [a] -> [a]
merge (x:xs)(y:ys)
  | x == y= x : merge xs ys
  | x <  y= x : merge xs (y:ys)
  | otherwise = y : merge (x:xs) ys

-- Lazily produce the hamming sequence
hamming :: [Integer]
hamming 
  = 1 : merge (map (2*) hamming) (merge (map (3*) hamming) (map (5*) hamming))
-- END SNAP


In Python, I figured out this implementation :

-- BEGIN SNAP
import sys
from itertools import imap

## Merges two infinite lists
def imerge(xs, ys):
  x = xs.next()
  y = ys.next()
  while True:
if x == y:
  yield x
  x = xs.next()
  y = ys.next()
elif x < y:
  yield x
  x = xs.next()
else: # if y < x:
  yield y
  y = ys.next()

## Lazily produce the hamming sequence 
def hamming():
  yield 1 ## Initialize the machine
  for n in imerge(imap(lambda h: 2*h, hamming()),
  imerge(imap(lambda h: 3*h, hamming()),
 imap(lambda h: 5*h, hamming(:
yield n
  print "Falling out -- We should never get here !!"

for n in hamming():
  sys.stderr.write("%s " % str(n)) ## stderr for unbuffered output
-- END SNAP


My goal is not to compare Haskell with Python on a classical FP problem, which 
would be genuine stupidity.

Nevertheless, while the Haskell version prints Hamming sequence for as long as 
I can stand it, and with very little memory consumation, the Python version 
only prints :

>>>>>> hamming.py
1 2 3 4 5 6 8 9 10 12 15 16 18 20 24 25 27 30 32 36 40 45 48 50 54 60 64 72 75 
80 81 90 96 100 108 120 125 128 135 144 150 160 162 180 192 200 216 225 240 
243 250 256 270 288 300 320 324 360 375 384 400 405 432 450 480 486 500 512 
540 576 600 625 640 648 675 720 729 750 768 800 810 864 900 960 972 1000 1024 
1080 1125 1152 1200 1215 1250 1280 1296 1350 1440 1458 1500 1536 1600 1620 
1728 1800 1875 1920 1944 2000 2025 2048 2160 2187 2250 2304 2400 2430 2500 
2560 2592 2700 2880 2916 3000 3072 3125 3200 3240 3375 3456 3600 3645 3750 
3840 3888 4000 4050 4096 4320 4374 4500 4608 4800 4860 5000 5120 5184 5400 
5625 5760 5832 6000 6075 6144 6250 6400 6480 6561 6750 6912 7200 7290 7500 
7680 7776 8000 8100 8192 8640 8748 9000 9216 9375 9600 9720 1 10125 10240 
10368 10800 10935 11250 11520 11664 12000 12150 12288 12500 12800 12960 13122 
13500 13824 14400 14580 15000 15360 15552 15625 16000 16200 16384 16875 17280 
17496 18000 18225 18432 18750 19200 19440 19683 2 20250 20480 20736 21600 
21870 22500 23040 23328 24000 24300 24576 25000 25600 25920 26244 27000 27648 
28125 28800 29160 3 30375 30720 31104 31250 32000 32400 32768 32805 33750 
34560 34992 36000 36450 36864 37500 38400 38880 39366 4 40500 40960 41472 
43200 43740 45000 46080 46656 46875 48000 48600 49152 5 50625 51200 51840 
52488 54000 54675 55296 56250 57600
Processus arrÃtÃ

After 57600, my machine begins swapping like crazy and I do have to kill the 
python processus. 

I think I should not have this kind of behaviour, even using recursion, since 
I'm only using lazy constructs all the time. At least, I would expect the 
program to produce much more results before surrending.

What's going on ?

Thank you

Francis Girard
FRANCE

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


cx_Oracle problem

2009-09-15 Thread Squid
It's time for another round of "stump-the-geek". (thats what we call
it in my office)

If actual code is needed I can provide but lets start off small for
this one...

I've got a Python script that uses cx_Oracle to access an Oracle DB.
running the script from command line runs perfect
running the script as a cron job produces "Unable to acquire Oracle
environment handle" in log.

In both cases it is running as the same user, in the same environment.

any ideas???
-- 
http://mail.python.org/mailman/listinfo/python-list


regex (?!..) problem

2009-10-04 Thread Wolfgang Rohdewald
Hi,

I want to match a string only if a word (C1 in this example) appears
at most once in it. This is what I tried:

>>> re.match(r'(.*?C1)((?!.*C1))','C1b1b1b1 b3b3b3b3 C1C2C3').groups()
('C1b1b1b1 b3b3b3b3 C1', '')
>>> re.match(r'(.*?C1)','C1b1b1b1 b3b3b3b3 C1C2C3').groups()
('C1',)

but this should not have matched. Why is the .*? behaving greedy
if followed by (?!.*C1)? I would have expected that re first 
evaluates (.*?C1) before proceeding at all.

I also tried:

>>> re.search(r'(.*?C1(?!.*C1))','C1b1b1b1 b3b3b3b3 
C1C2C3C4').groups()
('C1b1b1b1 b3b3b3b3 C1',)

with the same problem.

How could this be done?

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


os.chmod problem

2009-10-13 Thread Victor Subervi
Hi;
I have the following code:

  if 13 < x < 20:
y += 1
w += 1
try:
  getpic = "getpic" + str(w) + ".py"
  try:
os.remove(getpic)
  except:
pass
  code = """#! /usr/bin/python
import cgitb; cgitb.enable()
import MySQLdb
import cgi
import sys,os
sys.path.append(os.getcwd())
from login import login
def pic():
  user, passwd, db, host = login()
  form = cgi.FieldStorage()
  db = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db)
  cursor= db.cursor()
  sql = "select pic%s from productsX where id=%s;"
  cursor.execute(sql)
  content = cursor.fetchone()[0]
  cursor.close()
  print content
print 'Content-type: image/jpeg'
print
pic()
print ''""" % (str(w), str(w))
  script = open(getpic, "w")
  script.write(code)
  print '\n' % str(x)
  print '\n' % (getpic)
  os.chmod(getpic, 755)
  count2 += 1
except:
  pass

Forgive the empty except :) The problem is that the os.chmod command doesn't
work. It's obviously in the right directory, because the script correctly
writes there. What do?

On another note, I find it interesting that the above revised code does in
fact get that darned image to finally post correctly. It appears that this
python server insists on my calling a function...that I can't simply code it
out without defining a function. Never run into that before.
TIA,
Victor
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem

2009-10-15 Thread Xavier Ho
On Fri, Oct 16, 2009 at 3:28 AM, Ander  wrote:

> I can't send emails out. Can u fix this problem please?
>

I don't know what I'm missing here, but you evidently sent out an email to
the Python mailing list...

Cheers,
Xav
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem

2009-10-15 Thread Tim Chase

I can't send emails out. Can u fix this problem please?


The problem is on line 72.

Oh wait...you didn't include any code or the traceback.  Yeah,
that's gonna make it a little difficult to diagnose.  But I'm
gonna guess that "The authentication setting might not be correct
for your outgoing e-mail [SMTP] server."  Check your use of the 
SMTP libs to ensure that you're authenticating to your SMTP 
server correctly.  Notably, the login() method.


-tkc




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


Calendar Problem

2009-11-03 Thread Victor Subervi
Hi;
I have the following:

import calendar, datetime

myCal = calendar.calendar(6)
today = datetime.date.today()
day = today.day
mo = today.month
yr = today.year
month = myCal.monthdayscalendar(yr, mo)

The last line throws errors no matter how I try and tweak it. The current
incarnation complains about myCal being a string. What do?
TIA,
Victor
-- 
http://mail.python.org/mailman/listinfo/python-list


CTypes problem.

2009-11-17 Thread Martijn Arts
 I wanted to use PyWiiUse, but, well, it sucks

Then I thought; it can't be THAT hard, can it? So I began porting WiiUse to
Python using ctypes, but apparently, I did something wrong.

poll() gives back an event, *but* (there's always a but) the event doesn't
register. Or... Well... See for yourself, I think it has something to do
with Pointers, but I have no idea, really ;)

So, here's the code:
Code :-P 
-- 
http://mail.python.org/mailman/listinfo/python-list


crontab problem

2009-11-21 Thread Victor Subervi
Hi;
I have the following in crontab -eu root:
@daily /usr/local/bin/mysql-backup-daily.sh
@weekly /usr/local/bin/mysql-backup-weekly.sh
@monthly /usr/local/bin/mysql-backup-monthly.sh

[r...@13gems globalsolutionsgroup.vi]# ls /usr/local/bin/mysql-*
/usr/local/bin/mysql-daily.sh  /usr/local/bin/mysql-monthly.sh
/usr/local/bin/mysql-weekly.sh

These scripts worked on another server. The daily writes to:
/usr/backup/database/mysql-backups/mysql-backup-dailys/
However, a day later, nothing is there. Please advise.
TIA,
Victor
-- 
http://mail.python.org/mailman/listinfo/python-list


getattr problem

2009-12-01 Thread Victor Subervi
Hi;
I have the following code that execute without a problem:

import sys,os
sys.path.append(os.getcwd())
import options
storesTables = []
junkStores = string.join(addStore(), ', ')
for table in optionsTables():
  if table not in ('particulars', junkStores):
storesTables.append(table)
for table in storesTables:
  try:
fn = getattr(options, table)
print fn()
  except:
pass

I need to change the obvious line to this or something similar (that
actually works):

fn = getattr(options, '%s("names")' % table)

That is, I need to pass the variable "names" to each table as it is called.
How do I do this?
TIA,
Victor
-- 
http://mail.python.org/mailman/listinfo/python-list


Insane Problem

2009-12-02 Thread Victor Subervi
Hi;
I have spent 2-3 hours trying to track this bug. Here's the code snippet:

  form = cgi.FieldStorage()
  fn = getattr(options, 'products')
  ourOptionsNames = []
  optionsNames, doNotUse  = fn('names')
  for name in optionsNames:
test = table + '-' + name
print test
check = form.getfirst(test, '')
print check
if check != '':
  ourOptionsNames.append(name)

Now, when it looks through with test=='products', it doesn't report that any
of the values from the form are checked. However, when I explicitly write
out something like:
print form.getfirst('products-sizes', '')
which I checked on the form from the referring page, it does in fact print
out! My test prints show that 'products-sizes' is being passed to "check"
and should therefore be appended to "ourOptionsNames". But it isn't! What am
I missing here??
TIA,
Victor
-- 
http://mail.python.org/mailman/listinfo/python-list


another problem..

2009-12-16 Thread codefly
now.. another problem..
when i type me = code2()
the error is here..
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'module' object is not callable
-- 
http://mail.python.org/mailman/listinfo/python-list


Import Problem

2009-12-20 Thread Victor Subervi
Hi;
I have this import statement:

from particulars import storePrimaryStandAlone, addStore, ourStores

particulars.py has this code:

def addStore():
  return 'jewelry'

def ourStores():
  return ['products', 'prescriptions']

def storePrimaryStandAlone():
  return 'prescriptions'

But I get this error:

/var/www/html/angrynates.com/cart/createTables2.py
  263 
  264 '''
  265
  266 createTables2()
  267
createTables2 = 
 /var/www/html/angrynates.com/cart/createTables2.py in createTables2()
  105 these.append(basic)
  106   i = 0
  107   specialtyStore = addStore()
  108   addStore = []
  109   addStore.append(specialtyStore)
specialtyStore undefined, global addStore = 

UnboundLocalError: local variable 'addStore' referenced before assignment
  args = ("local variable 'addStore' referenced before assignment",)

What's strange is that it imports ourStores just fine. but even if I copy
ourStores to addStore the latter doesn't get imported! Why? Now, I've worked
around this problem by just importing all of particulars, but why did my
import fail?
TIA,
Victor
-- 
http://mail.python.org/mailman/listinfo/python-list


Strange Problem

2009-12-22 Thread Victor Subervi
Hi;
I have the following code:

  print 'printTheForm: ', descrProds, ''
  for value in descrProds:
print 'value: ', value, ''

which prints this:

printTheForm: [['ID', 'tinyint', '5', '0', None], ['SKU', 'varchar', '40',
'', None], ['Category', 'varchar', '40', '', None], ['Name', 'varchar',
'50', '', None], ['Title', 'varchar', '100', '', None], ['Description',
'mediumtext', '100', '', None], ['Price', 'float', '8', '0.0', None],
['SortFactor', 'int', '4', '0', None], ['Availability', 'tinyint', '1', '0',
'1'], ['OutOfStock', 'tinyint', '1', '0', '0'], ['ShipFlatFee', 'float',
'5', '0.0', '0.00'], ['ShipPercentPrice', 'tinyint', '2', '0', '0'],
['ShipPercentWeight', 'tinyint', '2', '0', '0'], ['Associations', 'varchar',
'40', '', None], ['TempPrice', 'tinyint', '1', '0', None], ['LastDatePrice',
'date', '10', '/mm/dd', None], ['Weight', 'float', '7', '0.0', None],
['Metal', 'enum', ['14k gold', '18k gold', 'white gold', 'silver',
'tungsten', 'titanium'], '', None], ['PercentMetal', 'tinyint', '2', '0',
None], ['colorsShadesNumbersShort', 'set', [''], '', None]]
value: ['ID', 'tinyint', '5', '0', None]
value: ['SKU', 'varchar', '40', '', None]
value: ['Category', 'varchar', '40', '', None]
value: ['Name', 'varchar', '50', '', None]
value: ['Title', 'varchar', '100', '', None]
value: ['Description', 'mediumtext', '100', '', None]
value: ['Price', 'float', '8', '0.0', None]
value: ['SortFactor', 'int', '4', '0', None]
value: ['Availability', 'tinyint', '1', '0', '1']
value: ['OutOfStock', 'tinyint', '1', '0', '0']
value: ['ShipFlatFee', 'float', '5', '0.0', '0.00']
value: ['ShipPercentPrice', 'tinyint', '2', '0', '0']
value: ['ShipPercentWeight', 'tinyint', '2', '0', '0']
value: ['Associations', 'varchar', '40', '', None]
value: ['TempPrice', 'tinyint', '1', '0', None]
value: ['LastDatePrice', 'date', '10', '/mm/dd', None]

You'll notice that the first print statement prints out several tuples that
don't get printed out in the last statement (they're truncated). Why?
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Append Problem

2010-01-02 Thread Victor Subervi
Hi;
I have the following code snippet:

  print 'Original: ', catChains, ''
  while i < MAXLEVEL:
flag = 0
j = 0
while j < len(parents):
  for chain in catChains:
if parents[j] == chain[len(chain)-1]:
  chain.append(children[j])
  print '1: ', catChains, ''
  catChains.append(chain)
  print '2: ', catChains, ''
  flag = 1
  j += 1
i += 1
if flag == 0:
  break
  print 'Final: ', catChains

which prints this:

Original: [['prodCat1'], ['prodCat2']]
1: [['prodCat1', 'prodCat3'], ['prodCat2']]
2: [['prodCat1', 'prodCat3'], ['prodCat2'], ['prodCat1', 'prodCat3']]
1: [['prodCat1', 'prodCat3', 'prodCat5'], ['prodCat2'], ['prodCat1',
'prodCat3', 'prodCat5']]
2: [['prodCat1', 'prodCat3', 'prodCat5'], ['prodCat2'], ['prodCat1',
'prodCat3', 'prodCat5'], ['prodCat1', 'prodCat3', 'prodCat5']]
Final: [['prodCat1', 'prodCat3', 'prodCat5'], ['prodCat2'], ['prodCat1',
'prodCat3', 'prodCat5'], ['prodCat1', 'prodCat3', 'prodCat5']]

Why is it that my append statement *deletes* elements of my tuple? The
entire code follows:

#! /usr/bin/python

import string
import cgitb; cgitb.enable()
import MySQLdb
import cgi
import sys,os
sys.path.append(os.getcwd())
from login import login
import datetime, Cookie, random
from particulars import title
from templateFrame import top, bottom
from particulars import myCookie
import time
import fpformat
from sets import Set

def makeNav():
  print 'Content-type: text/html\r\n'
  print '\n'
  user, passwd, db, host = login()
  db = MySQLdb.connect(host, user, passwd, db)
  cursor= db.cursor()
  form = cgi.FieldStorage()
  store = form.getfirst('store')
  sql = 'select Category, Parent from categories%s;' % (store[0].upper() +
store[1:])
  cursor.execute(sql)
  children = [itm[0] for itm in cursor]
  parents = [itm[1] for itm in cursor]
  catChains = []
  i = 0
  while i < len(parents):
if parents[i] is None:
  child = []
  child.append(children[i])
  catChains.append(child)
i += 1
  i = 0
  MAXLEVEL = 10
  print 'Original: ', catChains, ''
  while i < MAXLEVEL:
flag = 0
j = 0
while j < len(parents):
  for chain in catChains:
if parents[j] == chain[len(chain)-1]:
  chain.append(children[j])
  print '1: ', catChains, ''
  catChains.append(chain)
  print '2: ', catChains, ''
  flag = 1
  j += 1
i += 1
if flag == 0:
  break
  print 'Final: ', catChains
  lastChain = []
  lastChain.append('root')
  print ""
  for chain in sorted(catChains):
link = ''
i = 0
while i < len(chain):
  link += '%s/' % string.replace(chain[i], ' ', '_')
  i += 1
link = '%s.py' % link[:-1]
if len(chain) == len(lastChain)+1: # This is a new category level within
the current chain.
  print "%s" % (' ' * (len(chain)-1))
elif len(chain) == len(lastChain): # This is a new category within in
the same parent level.
  pass # This is just here to remind me how this works!
j = 0
while len(chain) < len(lastChain)-j:
  j += 1
  print "%s" % (' ' * (len(chain)-j))
print "%s%s" % ((' ' *
len(chain)), chain[len(chain)-1].lower(), link, chain[len(chain)-1])
lastChain = chain
  print ''

makeNav()

PS (Mainly, I believe, for Carsten): While programming is difficult for me,
I am writing (and have pretty much finished) this (almost) fully automated
shopping cart. I don't intend to write any other serious programming
project. However, a shopping cart is vital to my Web design business. I will
hereafter outsource my programming. But, as any good supervisor knows, one
has to know how to supervise! If I can't read code, then I'm at the mercy of
my programmer(s). If I can't afford to hire some top gun who can supervise,
then it's my responsibility. Plus, if my programmer(s) quit, I need to step
in and take over. I'm an ok businessman, and absolutely gifted in sales. And
in poetry ;)
beno

-- 
The Logos has come to bear
http://logos.13gems.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


suds problem

2010-01-07 Thread Fencer
Hello, I just started using suds to use web services. First I tried suds 
with a very simple web service I had written and was running myself. 
That worked fine. Then I tried to use the web services provided by KEGG:

http://soap.genome.jp/KEGG.wsdl
But I get a SAXParseException due to a supposed mis-matched tag when I 
try to consume that wsdl with suds. I checked the wsdl in oxygene and it 
claims it's valid. What is the problem here? My test program is below 
and it's very simple:

from suds.client import Client

url = 'http://soap.genome.jp/KEGG.wsdl'

client = Client(url)

print client

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


Interesting (?) problem

2010-01-11 Thread mk

Hello everyone,

I have two lists of IP addresses:

hostips = [ 'a', 'b', 'c', 'd', 'e' ]

thread_results = [ 'd', 'b', 'c' ]

I need to sort thread_results in the same order as hostips.

(Obviously, hostips can contain any valid ip addresses as strings, they 
are sorted alphabetically here just for sake of example.)


Since explicit is better than implicit, I will clarify: thread_results 
is obviously result of threads communicating with IPs from hostips, and 
that can finish at various times, thus returning ips into thread_results 
in any order.


Sorting would be trivial to do if thread_results were not a subset of 
hostips (obviously, for some IPs communication can fail which excludes 
them from the result).


One approach I can see is constructing hostips_limited list that would 
contain only ips that are in thread_results but that would preserve 
order of hostips:


hostips_limited = []
for h in hostips:
if h in thread_results:
hostips_limited.append(h)

..and then doing sorting thread_results.

But maybe there is more elegant / faster approach?



Incidentally, it *seems* that list comprehension preserves order:

hostips_limited = [ h for h in hostips if h in thread_results ]

Empirically speaking it seems to work (I tested it on real ips), but 
please correct me if that's wrong.




Regards,
mk

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


Interesting Problem

2010-01-20 Thread Victor Subervi
Hi;
I think I finally have an interesting problem for y'all. I need to import a
script from a lower dir, forcing me to change dirs:

cwd = os.getcwd()
os.chdir('%s/..' % cwd)
sys.path.append(os.getcwd())
from templateFrame import top, bottom
os.chdir(cwd)

Because I've found I must do my form evaluations *before* changing dir as
above, I am forced to call these values as globals:

form = cgi.FieldStorage()
store = form.getfirst('store')
cat = form.getfirst('cat')
id = form.getfirst('id')
pkg = form.getfirst('pkg')
patientID = form.getfirst('patientID')

Now, apparently because of python's problem with globals, when I call "id"
as follows:

cursor.execute('select ProductID from productsPackages where PackageID=%s' %
id)

I get the following error:

/var/www/html/angrynates.com/cart/Store_frame2.py
  135   cursor.close()
  136   bottom()
  137
  138 Store_frame2()
  139
Store_frame2 = 
 /var/www/html/angrynates.com/cart/Store_frame2.py in Store_frame2()
  119 printAProduct()
  120   else:
  121 cursor.execute('select ProductID from productsPackages where
PackageID=%s' % id)
  122 for id in [itm[0] for itm in cursor]:
  123   printAProduct(id)
global cursor = , cursor.execute = >, global id = '1'

UnboundLocalError: local variable 'id' referenced before assignment
  args = ("local variable 'id' referenced before assignment",)

Full code below. Please advise.
TIA,
beno

#! /usr/bin/python

import string
import cgitb; cgitb.enable()
import cgi
import MySQLdb
import sys,os
from sets import Set
import fpformat
cwd = os.getcwd()
sys.path.append(cwd)
from login import login
from particulars import truncate

form = cgi.FieldStorage()
store = form.getfirst('store')
cat = form.getfirst('cat')
id = form.getfirst('id')
pkg = form.getfirst('pkg')
patientID = form.getfirst('patientID')

try:
  browser = form.getfirst('browser', 'all')
except:
  browser = headers()

os.chdir('%s/..' % cwd)
sys.path.append(os.getcwd())
from templateFrame import top, bottom
os.chdir(cwd)

ourFile = string.split(__file__, "/")
p = ourFile[len(ourFile) - 1]
p = p[: - 9]
site = ourFile[4][:-10]
if site != '':
  site = site[:-1]

user, passwd, db, host = login()
db = MySQLdb.connect(host, user, passwd, db)
cursor= db.cursor()

cursor.execute('describe %s;' % store)
descr = cursor.fetchall()
cols = []
for elt in descr:
  cols.append(elt[0])

def printAProduct(id=id):
  lastID = ''
  cursor.execute('select * from %s where ID="%s"' % (store, id))
  vals = cursor.fetchone()
  prodDict = dict(zip(cols, vals))
  for col, item in prodDict.iteritems():
if col == 'ID':
  print '' % item
try: # Stores such as products (but not prescriptions) will pass through
  from particulars import ourOptions
  if col in ourOptions():
print '' % (col, item)
except:
  pass
if col[:3] != 'pic':
  notSet = 1
  if isinstance(item, (str, int, long, float, long, complex, unicode,
list, buffer, xrange, tuple)):
print '%s: %s\n' % (col, item)
  else:
try:
  html = "%s: " % (col, col)
  notSet = 0
  for itm in item:
try:
  color, number = itm.split('_')
  html += "%s" % (itm, color)
except:
  html += "%s" % (itm, itm)
  html += ""
  print html
except:
  pass
#  if notSet == 1:
#if len(col) > 49:
#  colX = col[:50] + '...'
#   else:
# colX = col
#   print '%s: %s\n' % (colX, item)
elif col == 'pic1':
  try:
if (item != None):
#  if (item != None) and (len(item > 0)):
  print '\n' % (store, col[3:], id, store, col[3:], id, store, col[3:],
id)
  except TypeError:
raise
  except:
raise
#  i += 1
#  try:
#content = item[x].tostring()
# pic = "tmp" + str(i) + ".jpg"
#try:
#  os.remove(pic)
#except:
#  pass
#img = open(pic, "w")
#img.write(content)
#print '' % pic
#img.close()
#  except:
#pass

def Store_frame2():
  top(browser, p)
  i = 0
  print '\n'
  print ''
  print "" % store
  print ""
  if pkg == 'no':
printAProduct()
  else:
cursor.execute('select ProductID from productsPackages where
PackageID=%s' % id)
for id in [itm[0] for itm in cursor]:
  printAProduct(id)
  if store == 'prescriptions':
print ""
print ""
  elif truncate()[store] != '':
pass
  else:
print "Quantity: "
print ""
  print ''
  print '\n'
  print '\n'
  cursor.close()
  bottom()

Store_frame2()


-- 
The Logos has come to bear
http://logos.13gems.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


socket problem

2009-03-02 Thread step
  my server program is writed with c in windows using mingw,using
"select" model

 client is writed with python

 the problem is , when the client connect the server, the function
FD_ISSET(cilentfd,&set) always true, but it hvae read no data, i also
no send data to server.

 why? i use telnet program in windows to test my server ,it
good ,FD_ISSET  is work ok, it return false
--
http://mail.python.org/mailman/listinfo/python-list


Pickle Problem

2009-03-03 Thread Fab86
Hello,

I am new to using Python and am looking at exporting some of my code
into a seperate document.

The code I am using for the pickle is:

file = open('testdoc.txt', 'w')

pickle.dump(res1.total_results_available,file)
pickle.dump(res2.total_results_available,file)
pickle.dump(res3.total_results_available,file)
file.close()

res1.total_results_available and others are simply integers which are
recalled from the Yahoo Search API and they print fine cmd or console
but when trying to pickle them they are displayed like this:

I14
.I15200
.I86000
.

But in console simply printing these attributes I get:

14
15200
86000

Can anyone help?

Many thanks,

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


PyEval_EvalCode(...) problem

2009-03-10 Thread googler . 1 . webmaster
Hi!

I have a problem with PyEval_EvalCode(...)
I compile the following code and execute them with PyEval_EvalCode
(...)


class MyClass(mod.Upper):
pass

register(MyClass) #just the type, not the instance


Thats all. So register(...) is a Python C API method so i take the
type and store
it in a global variable. PyEval_EvalCode(...) returns not NULL and I
do not decref
the dictionary, just the returnvalue.

After PyEval_EvalCode(..) is executed I would like to create an
instance of MyClass
which crashes because information of the inherited types are corrupt.
If I call

PyObject_CallObject(obj, NULL) in register(..) where PyEval_EvalCode
(..) is still active
everything works fine but when I call it after PyEval_EvalCode, even I
did not decref anything)
its not working. Can anyone of you help me? The refcounts of the
MyClass type are > 0.



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


py2exe problem

2009-04-01 Thread Wolfgang Forstmeier

Hey list,

what kind of error do I have with getting this error at starting my app.
Im am not using IdleConf.GetOption right now.

 Warning: configHandler.py - IdleConf.GetOption -
 problem retrieving configration option 'name'
 from section 'Keys'.
 returning default value: ''
--
http://mail.python.org/mailman/listinfo/python-list


Eval Problem

2009-04-06 Thread Victor Subervi
Hi:
I have this code:

x = 1
while x <= bitties:
  file = open(p + str(x) + ".txt")
  for line in file:
print line
  print eval(bits[x - 1])
  x += 1

which throws this error:

[Mon Apr 06 12:07:29 2009] [error] [client 190.166.0.221] PythonHandler
mod_python.cgihandler: Traceback (most recent call last):
[Mon Apr 06 12:07:29 2009] [error] [client 190.166.0.221] PythonHandler
mod_python.cgihandler: File
"/usr/lib64/python2.4/site-packages/mod_python/apache.py", line 299, in
HandlerDispatch\n result = object(req)
[Mon Apr 06 12:07:29 2009] [error] [client 190.166.0.221] PythonHandler
mod_python.cgihandler: File
"/usr/lib64/python2.4/site-packages/mod_python/cgihandler.py", line 96, in
handler\n imp.load_module(module_name, fd, path, desc)
[Mon Apr 06 12:07:29 2009] [error] [client 190.166.0.221] PythonHandler
mod_python.cgihandler: File "/var/www/vhosts/
articles.13gems.com/httpdocs/index_frame.py", line 89, in ?\n print
eval(bits[1])
[Mon Apr 06 12:07:29 2009] [error] [client 190.166.0.221] PythonHandler
mod_python.cgihandler: File "", line 1
[Mon Apr 06 12:07:29 2009] [error] [client 190.166.0.221] PythonHandler
mod_python.cgihandler: tableBottom(348,180)
[Mon Apr 06 12:07:29 2009] [error] [client 190.166.0.221] PythonHandler
mod_python.cgihandler: ^
[Mon Apr 06 12:07:29 2009] [error] [client 190.166.0.221] PythonHandler
mod_python.cgihandler: SyntaxError: invalid syntax

However, if I edit out the offending line and add:

print tableBottom(348,180)

it prints! What´s wrong?
TIA,
Victor
--
http://mail.python.org/mailman/listinfo/python-list


Package problem

2009-05-18 Thread Sverre
I'm using Ubuntu and some of the packages in the repository are too
old. So I got the thought to remove nearly  all packages downloaded
from the repository and install them with easy_install. Is this a way
to go without greater problems?
-- 
http://mail.python.org/mailman/listinfo/python-list


Feedparser problem

2009-06-04 Thread Jonathan Nelson
I'm trying to add a feedreader element to my django project.  I'm
using Mark Pilgrim's great feedparser library.  I've used it before
without any problems.  I'm getting a TypeError I can't figure out.
I've tried searching google, bing, google groups to no avail.

Here's the dpaste of what I'm trying to do and the result I'm
getting:

http://dpaste.com/51406/

I've tried checking my firewall settings.  I'm using Windows 7 and
Python 2.6.  Win 7 is allowing other Python programs through.  I've
tried several different RSS urls with the same result.

Any thoughts would be greatly appreciated.
-- 
http://mail.python.org/mailman/listinfo/python-list


Feedparser Problem

2009-06-05 Thread Jonathan Nelson
I'm working with Feedparser on months old install of Windows 7, and
now programs that ran before are broken, and I'm getting wierd
messages that are rather opaque to me.   Google, Bing, News groups
have all left me empty handed.

I was wondering if I could humbly impose upon the wizards of
comp.lang.python to lend me their wisdom and insight to this problem
that is too difficult for my little mind.

Here's what I'm going through:

>>>from feedparser import parse
>>>url='http://feeds.nytimes.com/nyt/rss/Technology'
>>>url2='http://feeds.washingtonpost.com/wp-dyn/rss/technology/index_xml'
>>>d = parse(url)
>>>d2= parse(url2)
>>>d
{'bozo':1,
'bozo_exception': TypeError("__init__() got an unexpected keyword
argument 'timeout'",),
'encoding': 'utf-8',
'entries': [],
'feed':{},
'version': None}
>>>d2
{'bozo': 1,
 'bozo_exception': TypeError("__init__() got an unexpected keyword
argument 'timeout'",),
 'encoding': 'utf-8',
 'entries': [],
 'feed': {},
 'version': None}

I've checked my firewall settings, and python is allowed.  Other
python programs can get data from the web.  I know that the 'bozo' is
for malformed xml.  I've searched through both of those rss feeds, and
I can't find the argument 'timeout' anywhere in them.

Any ideas, thoughts or directions in which I might go?

Thanks to all in advance,
Jonathan
-- 
http://mail.python.org/mailman/listinfo/python-list


Input problem

2009-06-16 Thread Prasoon
I am new to pythonand using python 2.6
I want to know when to use raw_input( ) and when to use input( )???

According to my interpretation one should use input( ) when entering
numbers etc and
raw_input( ) when a string is too be entered.

Correct me if I am wrong

Also if I want to enter two numbers 'a' and b such that while entering
them through the keyboard
there is a space between the two...

For example:
>>>Enter two numbers:
 .12 15

Can I use input( ) such that 12 gets accepted in 'a' and 15 in 'b'

I mean how to handle spaces???/

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


encoding problem

2009-06-27 Thread netpork
Hello,

I have ssl socket with server and client, on my development machine
everything works pretty well.
Database which I have to use is mssql on ms server 2003, so I decided
to install the same python config there and run my python server
script.

Now here is the problem, server is returning strange characters
although default encoding is the same on both development and server
machines.


Any hints?

Thanks in advance.
-- 
http://mail.python.org/mailman/listinfo/python-list


tkinter problem

2009-07-08 Thread Paul Simon
I have the "tkinter" problem and need some assistance to straighten it out.
>From the web page "http://wiki.python.org/moin/TkInter"; I tested as in "step
1" and cannot import "_tkinter." I do not have that file on my computer, but
do have tkinter.py in /usr/local/lib/python2.6/lib-tk. as well as the
directories /usr/lib/tk8.5 and /usr/lib/tcl8.5.
This  python stuff is great, but the documentation frequently
feels like it is just a bit out of my grasp. I realize that all of this is
free but I understand the instructions on the web page to repair only to the
point of confusion. I'm not an expert. How do I modify my python
configuration? Is there a file that needs to be edited? Which setup.py file
do I use? Make? or python setup.py build and python setup.py install?
Thanks. I appreciate your help.
Paul Simon 


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


Threading.Condition problem

2009-07-10 Thread Gabriel Rossetti

Hello everyone,

I wrote a small example that listens for xmpp msgs in a thread. The main 
program calls a function that blocks (using Condition.wait) until a msg 
has been received and then returns the msg. When a msg arrives, it is 
put in a variable in the thread's object, it then calls the notify() 
attr on the Condition object. For some reason, this doesn't work, the 
thread gets the msg, tries to notify the Condition object, fails because 
the lock has not been acquired yet and blocks. I tried ignoring the 
failure, thinking that since it has not been acquired yet then when it 
is, it will get the msg right away and never call Condition.wait, thus 
not causing any problems, but this does not work either. Does someone 
know what I am doing wrong? I attached the code to this msg.


Thank you,
Gabriel
# Copyright (c) 2001-2006 Twisted Matrix Laboratories.
# See LICENSE for details.

import sys
from twisted.internet import reactor
from twisted.names.srvconnect import SRVConnector
from twisted.words.xish import domish, xpath
from twisted.words.protocols.jabber import xmlstream, client, jid

PRESENCE = '/presence' # this is an global xpath query to use in an observer
MESSAGE = '/message'   # message xpath
IQ = '/iq' # iq xpath

class XMPPClientConnector(SRVConnector):
def __init__(self, reactor, domain, factory):
SRVConnector.__init__(self, reactor, 'xmpp-client', domain, factory)


def pickServer(self):
host, port = SRVConnector.pickServer(self)

if not self.servers and not self.orderedServers:
# no SRV record, fall back..
port = 5222

return host, port



class Client(object):

def __init__(self, client_jid, secret, dest=None):
"""
"""
self.dest = dest
f = client.XMPPClientFactory(client_jid, secret)
f.addBootstrap(xmlstream.STREAM_CONNECTED_EVENT, self.connected)
f.addBootstrap(xmlstream.STREAM_END_EVENT, self.disconnected)
f.addBootstrap(xmlstream.STREAM_AUTHD_EVENT, self.authenticated)
f.addBootstrap(xmlstream.INIT_FAILED_EVENT, self.init_failed)
connector = XMPPClientConnector(reactor, client_jid.host, f)
connector.connect()

def rawDataIn(self, buf):
print "RECV: %s" % unicode(buf, 'utf-8').encode('ascii', 'replace')

def rawDataOut(self, buf):
print "SEND: %s" % unicode(buf, 'utf-8').encode('ascii', 'replace')

def connected(self, xs):
"""
"""
print 'Connected.'

self.xmlstream = xs

# Log all traffic
xs.rawDataInFn = self.rawDataIn
xs.rawDataOutFn = self.rawDataOut


def disconnected(self, xs):
"""
"""
print 'Disconnected.'
try:
reactor.stop()
except:
pass

def authenticated(self, xs):
"""
"""
def sendPresence():
presence = domish.Element((None, 'presence'))
xs.send(presence)

def sendMsg(user, res=None):
msg = domish.Element(("jabber:client", "message"))
msg["to"] = "%...@localhost%s" % (user, "/" + res if res else "")
body = msg.addElement("body", content = "Hello world %s" % res if res else "")
subject = msg.addElement("subject", content = "will this be displayed?")
thread = msg.addElement("thread", content = "this shouldn't be displayed")
xs.send(msg)


print "Authenticated."

xs.addObserver(PRESENCE, self.onPresence, 1)
#xs.addObserver(IQ, self.onIq, 1)
xs.addObserver(MESSAGE, self.onMessage, 1)

reactor.callLater(0, sendPresence)

if(self.dest):
reactor.callLater(2, sendMsg, self.dest, "toto")
reactor.callLater(4, sendMsg, self.dest, "titi")

#msg = domish.Element(("jabber:client", "message"))
#msg["to"] = "grosse...@localhost"
#body = msg.addElement("body", content = "Hello world")
#subject = msg.addElement("subject", content = "will this be displayed?")
#thread = msg.addElement("thread", content = "this shouldn't be displayed")
#xs.send(msg)

#msg = domish.Element(("jabber:client", "iq"))
#msg["to"] = "ser...@localhost"
#msg["id"] = "666"
#xs.send(msg)

#msg = domish.Element(("jabber:client", "presence"))
#msg["to"] = "grosse...@localhost"
#msg["type"] = "subscribe"
#xs.send(msg)

#reactor.callLater(5, xs.sendFooter)

def onMessage(self, msg):
"""
Act on the message stanza that has just been received.
"""
# return to sender
#msg = create_reply(msg)
#self.xmlstream.send(msg) # send the modified domish.Element
pass

#def onIq(self, iq):
#"""
#Act on the iq stanza that has just been received.

#"""
#iq = create_reply(iq)
#self.xmlstream.send(iq)

def onPresence(

Threading.Condition problem

2009-07-10 Thread Gabriel Rossetti
Sorry if this appears twice, I sent it once with an attachment and it 
never arrived so maybe the attachment is posing problems. I inlined the 
code this time (at the bottom), thank you,


Gabriel

## Original message 

Hello everyone,

I wrote a small example that listens for xmpp msgs in a thread. The main
program calls a function that blocks (using Condition.wait) until a msg
has been received and then returns the msg. When a msg arrives, it is
put in a variable in the thread's object, it then calls the notify()
attr on the Condition object. For some reason, this doesn't work, the
thread gets the msg, tries to notify the Condition object, fails because
the lock has not been acquired yet and blocks. I tried ignoring the
failure, thinking that since it has not been acquired yet then when it
is, it will get the msg right away and never call Condition.wait, thus
not causing any problems, but this does not work either. Does someone
know what I am doing wrong? I attached the code to this msg.

Thank you,
Gabriel



 Example code 

from __future__ import with_statement
import xmpp, sys
from threading import Thread, Condition, Event


class Listener(Thread):
def __init__(self, ws):
Thread.__init__(self)
self.interrupt = Event()
self.message = None
self._cv = ws._cv
self.client = ws._client
self.client.RegisterHandler('message', self.onMessage)

def onMessage(self, conn, msg):
self.message = msg
try:
self._cv.notify()
except RuntimeError:
print "self._cv has not acquired the lock yet"

def getMsg(self):
return self.message

def run(self):
try:
while(not self.interrupt.isSet()):
self.client.Process(1)
except KeyboardInterrupt:
return 0

class WS(object):
def __init__(self, username, password, res):
self._jid = xmpp.protocol.JID(username)
self._client = xmpp.Client(self._jid.getDomain())
self._cv = Condition()

if(self._client.connect(server=("localhost", 5222)) == ""):
raise Exception("Error while connecting!")

if(self._client.auth(self._jid.getNode(), password, res) is None):
raise Exception("Authentication failed!")

self._client.sendInitPresence()

self._listener = Listener(self)
self._listener.start()

def getMsg(self, mid=None):
"""
"""
with self._cv:
res = self._listener.getMsg()
while not res:
self._cv.wait()
res = self._listener.getMsg()
return res

if(__name__ == "__main__"):
ws = WS("t...@localhost", "123", "test")
res = ws.getMsg()
print "I just received : %s" % str(res)
sys.exit(0)


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


Regexp problem

2009-07-30 Thread Beldar
Hi there!

I have a problem and i'm not very good at regular expressions.
I have a text like "lalala lalala tiruri beldar-is-listening tiruri
lalala" I need a regexp to get the 'beldar' part, the format is
'something-is-listening', i need to get the something part, use it in
my code, and then replace the whole 'something-is-listening' for
another string.

Someone can help me please? Thank you!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem

2009-08-07 Thread Piet van Oostrum
> sumit  (s) wrote:

>s> i want 2 hav the header files for regular expression to non
>s> deterministin autometa
>s> so whr should i find it?plz help

What header files? C? You can find lots of header files by googling. But
the header files contain only the interface, not the implementation. And
conversion from regular expression to non-deterministic automaton is an
implementation matter, so the header file will not help you there. You
will need the C or C++ file.

And then, do you want Python's implementation or any implementation.
Please be specific when you ask something.

Start by googling for regex.h for general software.
Python header file is in
http://svn.python.org/view/python/trunk/Modules/sre.h and the
implementation in http://svn.python.org/view/python/trunk/Modules/_sre.c
but I don't think it goes non deterministic. For that you can better
look into the general 'grep'-like software. For example start here:
http://arglist.com/regex/ 
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Permission Problem

2010-03-01 Thread Victor Subervi
Hi;
I encountered and solved this problem before with the help of the list, but
it's back, and I've reviewed and done everything I was shown to do last
time, so I'm lost. Here's the script:

#!/usr/bin/python

import cgitb; cgitb.enable()
import cgi
import sys,os
sys.path.append(os.getcwd())
from login import login
import MySQLdb
import re, string
import fpformat

form = cgi.FieldStorage()
width = form.getfirst('width')
lines = '''
#!/usr/bin/python

return %s''' % width
f = 'width.py'
try:
  os.remove(f)
except OSError:
  pass
f = open(f, 'w')
f.writelines(lines)
f.close()

Simple enough. Here's the permissions:

drwxrwxrwx 31 root root   4096 Feb 23 04:57 ..
-rwxrwxrwx  1 root root390 Mar  1 05:52 preload.py

All loaded up deliberately to try and get it to work. Here's the error:

 /var/www/html/globalsolutionsgroup.vi/preload.py
   21 except OSError:
   22   pass
   23 f = open(f, 'w')
   24 f.writelines(lines)
   25 f.close()
f = 'width.py', builtin open = 
IOError: [Errno 13] Permission denied: 'width.py'
  args = (13, 'Permission denied')
  errno = 13
  filename = 'width.py'
  strerror = 'Permission denied'

What'd I do wrong?
TIA,
beno

-- 
The Logos has come to bear
http://logos.13gems.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Multiprocessing problem

2010-03-02 Thread Matt Chaput

Hi,

I'm having a problem with the multiprocessing package.

I'm trying to use a simple pattern where a supervisor object starts a 
bunch of worker processes, instantiating them with two queues (a job 
queue for tasks to complete and an results queue for the results). The 
supervisor puts all the jobs in the "job" queue, then join()s the 
workers, and then pulls all the completed results off the "results" queue.


(I don't think I can just use something like Pool.imap_unordered for 
this because the workers need to be objects with state.)


Here's a simplified example:

http://pastie.org/850512

The problem is that seemingly randomly, but almost always, the worker 
processes will deadlock at some point and stop working before they 
complete. This will leave the whole program stalled forever. This seems 
more likely the more work each worker does (to the point where adding 
the time.sleep(0.01) as seen in the example code above guarantees it). 
The problem seems to occur on both Windows and Mac OS X.


I've tried many random variations of the code (e.g. using JoinableQueue, 
calling cancel_join_thread() on one or both queues even though I have no 
idea what it does, etc.) but keep having the problem.


Am I just using multiprocessing wrong? Is this a bug? Any advice?

Thanks,

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


Import problem

2010-03-06 Thread Johny
I have this directory structure

C:
  \A
 __init__.py
 amodule.py

 \B
  __init__.py
  bmodule.py

   \D
__init__.py
dmodule.py

and  I want to import  bmodule.py
C:\>cd \

C:\>python
Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit
(Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> from A.B import  bmodule
I am bmodule
>>>
C:\>

so far so good. Now I would like to import bmodule but if the current
directory is \D subdirectory.

C:> cd \A\B\D
C:\A\B\D>
C:\A\B\D>python
Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit
(Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path.append('C:\\A')
>>> from A.B import bmodule
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named A.B

C:\>

so I can not import a module from the parent directory? Or where did I
make an error?
Thanks for help

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


Refresh Problem

2010-04-11 Thread Victor Subervi
Hi;
I send variables to a script. The script adds appropriate lines into a
database of an order to my shopping cart. When I refresh the screen, as no
doubt some customers will do, it re-ads those orders. Now, I can delete
them, but that's not the point. I don't want it to re-ad the orders. How do
I skirt this problem?
TIA,
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Threading problem

2010-04-25 Thread sdistefano
I have the following issue:

My program runs a thread called the MainThread, that loops trough a
number of URLs and decides when it's the right time for one to be
fetched.  Once a URL has to be fetched, it's added to a Queue object,
where the FetchingThread picks up and does the actual work. Often,
URLs have to be fetched with frequencies of 100ms, so the objects will
get added to the queue repeatedly. Even though it takes more than
100ms to get the URL and process it, ideally what would happen is:
ms0: Request 1 is sent
ms100: request 2 is sent
ms150: request 1 is processed
ms200: request 3 is sent
ms250: request 2 is processed

and so on... The problem is that for some reason python runs the main
thread considerably more than the checking thread. If I ask them both
to 'print' when run, this becomes obvious ; even if I create more
check threads than main threads (I even tried 50 check threads and 1
main thread). Despite my terminology, both the mainthread and
fetchthread are created in exactly the same way.

what part of threading in python am I not properly understanding?

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


FTP problem

2011-01-14 Thread Thomas Philips
I'm using ftplib for the first time, and am having trouble getting it
to work. I type

>>> from ftplib import FTP
>>> ftp = FTP('ftp.indexftp.barcap.com', 'A Valid Username', ' A Valid 
>>> Password')

where I have suppressed the user name and password, and I get

Traceback (most recent call last):
  File "", line 1, in 
ftp = FTP('ftp.indexftp.barcap.com')
  File "C:\Python26\lib\ftplib.py", line 116, in __init__
self.connect(host)
  File "C:\Python26\lib\ftplib.py", line 131, in connect
self.sock = socket.create_connection((self.host, self.port),
self.timeout)
  File "C:\Python26\lib\socket.py", line 498, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
gaierror: [Errno 11001] getaddrinfo failed

I have tried this on two different computers and on two different
versions of Python (2.6 and 2.7). I get the same error both times, and
have no understanding of what the problem might be. Any assistance
would be greatly appreciated.

Sincerely

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


BackupRead problem

2011-01-15 Thread Stefan Sonnenberg-Carstens

I'm trying to create a Backup/Restore app.
I'm really struggeling for a long time.

I can successfully read directories, but not files.
Every time, I'll try I get "Access denied", Error 5.

It's running with admin privs.

Any ideas ?

#!python
import sys
import os
import os.path
import getopt
import time


DELETE=0x0001
READ_CONTROL=0x0002
WRITE_DAC=0x0004
WRITE_OWNER=0x0008
SYNCHRONIZE=0x0010
STANDARD_RIGHTS_REQUIRED=0x000FL
STANDARD_RIGHTS_READ=READ_CONTROL
STANDARD_RIGHTS_WRITE=READ_CONTROL
STANDARD_RIGHTS_EXECUTE=READ_CONTROL
STANDARD_RIGHTS_ALL=0x001F
SPECIFIC_RIGHTS_ALL=0x

FILE_ATTRIBUTE_REPARSE_POINT=0x400

from ctypes import *

if os.name == 'nt':

import win32security
import win32process
import win32file

try:
import win32api
except ImportError,e:
print >>sys.stderr,'Could not load win32api module. Can not 
continue'

os._exit(1)
try:
import wmi
except ImportError,e:
print >>sys.stderr,'Could not load wmi module. Can not continue'
os._exit(1)
try:
import ctypes
except ImportError,e:
print >>sys.stderr,'Could not load ctypes module. Can not continue'
os._exit(1)
else:
print >>sys.stderr,'Sorry, your platform %s is not supported' % os.name
os._exit(1)

if len(sys.argv) >= 1:
try:
opts,args = getopt.getopt(sys.argv[1:],'h',('help',))
except getopt.GetoptError,e:
print str(e)
if not ctypes.windll.shell32.IsUserAnAdmin():
win32api.ShellExecute(None,'runas',sys.executable,' 
'.join(sys.argv),r'C:\WINDOWS',0)

else:
print >>sys.stderr,'Running with administrative privileges'
token = 
win32security.OpenProcessToken(win32process.GetCurrentProcess(),win32security.TOKEN_ADJUST_PRIVILEGES|win32security.TOKEN_QUERY)

if token:
for priv in 
(win32security.SE_BACKUP_NAME,win32security.SE_RESTORE_NAME):

luid = win32security.LookupPrivilegeValue(None,priv)
newState = [(luid,win32security.SE_PRIVILEGE_ENABLED)]
try:
win32security.AdjustTokenPrivileges(token,0,newState)
except:
print >>sys.stderr,'Could not get (some) required 
priviledge(s): ',win32api.FormatMessage(win32api.GetLastError())

os._exit(1)
win32api.CloseHandle(token)
else:
print >>sys.stderr,'Could not get token for running process'
os._exit(1)
print >>sys.stderr,'Acquired backup/restore context 
(SeRestorePrivilege and SeBackupPrivilege enabled)'
inf = 
win32file.CreateFile(r'C:\Windows\System32\drivers\etc\hosts',READ_CONTROL,0,None,win32file.OPEN_EXISTING,win32file.FILE_FLAG_BACKUP_SEMANTICS,None)

buf = win32file.AllocateReadBuffer(4096)
ctx = 0
(bytes_read,buf,ctx) = 
win32file.BackupRead(inf,4096,buf,False,True,ctx)

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


LDFLAGS problem

2011-02-21 Thread Robin Becker
After installing python 2.7.1 on a Freebsd 8.0 system with the normal configure 
make dance


./configure --prefix=$HOME/PYTHON --enable-unicode=ucs2
make
make install

I find that when I build extensions PIL, MySQLdb I'm getting errors related to a 
dangling ${LDFLAGS}


eg  MySQLdb


running build_ext
building '_mysql' extension
creating build/temp.freebsd-7.0-RELEASE-i386-2.7
gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall 
-Wstrict-prototypes -fPIC -Dversion_info=(1,2,2,'final',0) -D__version__=1.2.2 
-I/usr/local/include/mysql -I/home/rptlab/PYTHON/include/python2.7 -c _mysql.c 
-o build/temp.freebsd-7.0-RELEASE-i386-2.7/_mysql.o -fno-strict-aliasing -pipe
gcc -pthread -shared ${LDFLAGS} 
build/temp.freebsd-7.0-RELEASE-i386-2.7/_mysql.o -L/usr/local/lib/mysql 
-lmysqlclient_r -lz -lcrypt -lm -o 
build/lib.freebsd-7.0-RELEASE-i386-2.7/_mysql.so
gcc: ${LDFLAGS}: No such file or directory
error: command 'gcc' failed with exit status 1


where should I be looking to fix this problem?
--
Robin Becker

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


Decimal problem

2010-06-10 Thread durumdara
Hi!

In the prev. week I tested my home Python projects with KinterBasDB
embedded, PsyCOPG, and SQLite.

All of them worked well, and everything was good.

But the database blob table deletion was slow in SQLite, so I thought
I will try this with FireBird and PGSQL.

Today I tried to copy the SQLite DataBase into FireBird, and PGSQL.

Psycopg drop this error:

import psycopg2
pdb = psycopg2.connect("dbname=testx user=postgres password=x")

C:\Python26\lib\site-packages\psycopg2\__init__.py:62: RuntimeWarning:
can't import decimal module probably needed by _psycopg
RuntimeWarning)

I wondered, because this was working before...

Then I tried to start KinterBasDB:

  File "C:\Python26\lib\site-packages\kinterbasdb\__init__.py", line
478, in con
nect
return Connection(*args, **keywords_args)
  File "C:\Python26\lib\site-packages\kinterbasdb\__init__.py", line
644, in __i
nit__
self._normalize_type_trans()
  File "C:\Python26\lib\site-packages\kinterbasdb\__init__.py", line
1047, in _n
ormalize_type_trans
self.set_type_trans_out(_NORMAL_TYPE_TRANS_OUT)
  File "C:\Python26\lib\site-packages\kinterbasdb\__init__.py", line
1073, in se
t_type_trans_out
return _k.set_Connection_type_trans_out(self._C_con, trans_dict)
  File "C:\Python26\lib\site-packages\kinterbasdb\__init__.py", line
1907, in _m
ake_output_translator_return_type_dict_from_trans_dict
return_val = translator(sample_arg)
  File "C:\Python26\lib\site-packages\kinterbasdb
\typeconv_fixed_decimal.py", li
ne 91, in fixed_conv_out_precise
from decimal import Decimal
ImportError: cannot import name Decimal

I deleted my complete Python with all packages, and I reinstalled it.
But the problem also appeared...

What is this? And what the hell happened in this machine that
destroyed my working python apps...?

Thanks:
   dd


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


Namespace problem?

2010-07-01 Thread Josh English
I have a script that generates a report from a bunch of data I've been
collecting for the past year. I ran the script, successfully, for
several weeks on test runs and creating more detailed reports.

Today (back from vacation) and the script doesn't work. It's giving me
a name error.

I'm running python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.
1310 32 bit (Intel)]. (Upgrading is not a possibility right now.
Eventually we'll be upgraded top Windows 7.)

Here is the reduced code:

fws_first_col = 6

for student in range(32):

if True:
idx = fws_first_col

for _month in range(12):
idx += 2
fws_last_col = idx


print fws_last_col

I get:

NameError: name 'fws_last_col' is not defined

This snippet of code works on it's own, but not in the main script. I
know it looks funny, but this should preserve the appropriate nesting
of things.

Where else could I look to find this problem?
-- 
http://mail.python.org/mailman/listinfo/python-list


parmiko problem

2010-07-19 Thread George Trojan
I have a problem with connecting to a host without specifying password 
(but with ssh keys configured correctly. That is


[tina src]$ sftp alice
Connecting to alice...
sftp>

works, but the code

import paramiko
paramiko.util.log_to_file('/tmp/paramiko')
t = paramiko.Transport(('alice', 22))
t.connect(username='gtrojan') # , password='a-passwd'])
sftp = paramiko.SFTPClient.from_transport(t)
sftp.close()
t.close()

results in the following output in /tmp/paramiko:

DEB [20100719-19:58:22.497] thr=1   paramiko.transport: starting thread 
(client mode): 0xb81e1150L
INF [20100719-19:58:22.501] thr=1   paramiko.transport: Connected 
(version 2.0, client OpenSSH_4.3)
DEB [20100719-19:58:22.502] thr=1   paramiko.transport: kex 
algos:['diffie-hellman-group-exchange-sha1', 
'diffie-hellman-group14-sha1', 'diffie-hellman-group1-sha1'] server 
key:['ssh-rsa', 'ssh-dss'] client encrypt:['aes128-cbc', '3des-cbc', 
'blowfish-cbc', 'cast128-cbc', 'arcfour128', 'arcfour256', 'arcfour', 
'aes192-cbc', 'aes256-cbc', 'rijndael-...@lysator.liu.se', 'aes128-ctr', 
'aes192-ctr', 'aes256-ctr'] server encrypt:['aes128-cbc', '3des-cbc', 
'blowfish-cbc', 'cast128-cbc', 'arcfour128', 'arcfour256', 'arcfour', 
'aes192-cbc', 'aes256-cbc', 'rijndael-...@lysator.liu.se', 'aes128-ctr', 
'aes192-ctr', 'aes256-ctr'] client mac:['hmac-md5', 'hmac-sha1', 
'hmac-ripemd160', 'hmac-ripemd...@openssh.com', 'hmac-sha1-96', 
'hmac-md5-96'] server mac:['hmac-md5', 'hmac-sha1', 'hmac-ripemd160', 
'hmac-ripemd...@openssh.com', 'hmac-sha1-96', 'hmac-md5-96'] client 
compress:['none', 'z...@openssh.com'] server compress:['none', 
'z...@openssh.com'] client lang:[''] server lang:[''] kex follows?False
DEB [20100719-19:58:22.502] thr=1   paramiko.transport: Ciphers agreed: 
local=aes128-ctr, remote=aes128-ctr
DEB [20100719-19:58:22.502] thr=1   paramiko.transport: using kex 
diffie-hellman-group1-sha1; server key type ssh-rsa; cipher: local 
aes128-ctr, remote aes128-ctr; mac: local hmac-sha1, remote hmac-sha1; 
compression: local none, remote none
DEB [20100719-19:58:22.571] thr=1   paramiko.transport: Switch to new 
keys ...
DEB [20100719-19:58:22.578] thr=2   paramiko.transport: [chan 1] Max 
packet in: 34816 bytes
WAR [20100719-19:58:22.611] thr=1   paramiko.transport: Oops, unhandled 
type 3
DEB [20100719-20:00:22.502] thr=1   paramiko.transport: EOF in transport 
thread


and a traceback in the terminal:

Traceback (most recent call last):
  File "./try.py", line 18, in 
sftp = paramiko.SFTPClient.from_transport(t)
  File "build/bdist.linux-x86_64/egg/paramiko/sftp_client.py", line 
102, in from_transport
  File "build/bdist.linux-x86_64/egg/paramiko/transport.py", line 655, 
in open_session
  File "build/bdist.linux-x86_64/egg/paramiko/transport.py", line 745, 
in open_channel

EOFError

When the remove the comment on the connect() line and specify password 
the code works fine. Is this a bug, or I am missing something? I am 
running Python 2.6.3 on Centos 5.4.


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


pyodbc problem

2010-07-27 Thread Martin Gregorie
I have a small problem: I can't get pyodbc to connect to a PostgreSQL 
database. All it does is spit out a malformed error message. When I run 
this:

==
import pyodbc

dsn = pyodbc.dataSources()
print "Data sources:%s" % dsn

conn = pyodbc.connect(dsn="marchive")
print "ODBC connection: %s" % conn
==

I get this:

==
[k...@zappa python]$ python dsncheck.py
Data sources:{'ma': 'PostgreSQL', 'marchive': 'PostgreSQL'}
Traceback (most recent call last):
  File "dsncheck.py", line 6, in 
conn = pyodbc.connect(dsn="marchive")
pyodbc.Error: ('0', '[0] [unixODBC]c (0) (SQLDriverConnectW)')
==

so the data source exists and is evidently found by connect(), whiuch 
seems unable to make sense of it.

The pgsql module works well, but I would prefer to use ODBC because its 
not so closely bound to a single RDBMS. unixODBC, which I understand 
underlies pyodbc, works OK too:

==
[k...@zappa python]$ isql marchive marchive n/a
+---+
| Connected!|
|   |
| sql-statement |
| help [tablename]  |
| quit  |
|   |
+---+
SQL> select count(*) from address;
+-+
| count   |
+-+
| 32  |
+-+
SQLRowCount returns 1
1 rows fetched
SQL> quit
==

Questions:
- Why does pyodbc blow up when its apparently trying to talk to unixODBC?
- What does this mean:
pyodbc.Error: ('0', '[0] [unixODBC]c (0) (SQLDriverConnectW)')

I'm new to Python, though not to Linux, PostgreSQL, ODBC, C or Java. 
My rig and software:

Linux:  Fedora 12 Where I'm running Python and ODBC,
  Lenovo Thinkpad R61i: Core Duo.
Fedora 10 Where PostgreSQL is installed,
  IBM NetVista: Pentium III. 
PostgreSQL: 8.3.8
Python: 2.6.2
pyodbc  2.1.5-3.fc12 ) By yum from RH repository
unixODBC2.2.14-11.fc12   )


-- 
martin@   | Martin Gregorie
gregorie. | Essex, UK
org   |
-- 
http://mail.python.org/mailman/listinfo/python-list


favicon.ico problem

2010-08-09 Thread Navkirat Singh
Hi guys,

I am having this strange problem. I have programmed a very basic 
multiprocessing webserver using low level sockets. Each time the server 
receives a request it spawns a new process to handle the request. Now when 
through a web browser I type http://localhost:8001/ it automatically creates 
two processes: One process to server the '/' path and another one to serve the 
'/favicon.ico' path. I have not programmed it to serve the latter. Infact I 
dont even know where that name '/favicon.ico' comes from. Any insight into this 
weird behavior would be greatly appreciated.

Regards,
Nav
-- 
http://mail.python.org/mailman/listinfo/python-list


MySQL Problem

2010-09-02 Thread Victor Subervi
Hi;
I have this code:

print 'select * from spreadsheets s join products p on p.Item=s.Item
join productsCategories pc on p.ID=pc.ProductsID join categories c on
pc.CategoryID=c.ID where s.Client="%s" order by c.Category, c.Parent' %
(client,)
cursor.execute('select * from spreadsheets s join products p on
p.Item=s.Item join productsCategories pc on p.ID=pc.ProductsID join
categories c on pc.CategoryID=c.ID where s.Client=%s order by c.Category,
c.Parent', (client,))
tmp = cursor.fetchall()
print tmp

Now, when I run the print of the mysql command in the mysql interpreter, it
gives me the following data:

mysql> select * from spreadsheets s join products p on p.Item=s.Item join
productsCategories pc on p.ID=pc.ProductsID join categories c on
pc.CategoryID=c.ID where s.Client='Lincoln_Properties' order by c.Category,
c.Parent;
+-++---+++--+-++--+-+---+-++++---+--+
| ID  | Client | Multi | Item   | Markup | Temp | ID  |
Item   | Description  | UOM
| Cost  | ID  | ProductsID | CategoryID | ID | Category  |
Parent   |
+-++---+++--+-++--+-+---+-++++---+--+
| 163 | Lincoln_Properties | 0 | 5349513|  53.22 | NULL |  39 |
5349513| 24833RNH 24" x 33 " 8 Mic Natural Can Liners | 1000/CS
| 25.63 |  39 | 39 | 23 | 23 | Can Liners|
Bags |
| 156 | Lincoln_Properties | 0 | 5349520|  30.00 | NULL |  31 |
5349520| Can Liners Coreless 45 gal Clear | 250/CS
| 28.69 |  31 | 31 | 23 | 23 | Can Liners|
Bags |
| 161 | Lincoln_Properties | 0 | 40x48Green |  99.32 | NULL |  37 |
40x48Green | Green Can Liners | 1000/cs
| 17.56 |  37 | 37 | 23 | 23 | Can Liners|
Bags |
| 160 | Lincoln_Properties | 0 | 24x33Green |  60.04 | NULL |  36 |
24x33Green | Green Can Liners | 1000/CS
| 20.27 |  36 | 36 | 23 | 23 | Can Liners|
Bags |
| 162 | Lincoln_Properties | 0 | 5349518|  26.02 | NULL |  38 |
5349518| 28048VNR01 40" x 48" HI-D| 250/CS
| 25.63 |  38 | 38 |  1 |  1 | Facility Supplies |
BASE |
| 152 | Lincoln_Properties | 0 | 4440120|  72.44 | NULL |  35 |
4440120| 91315 Pearlescent White Lotion Gallon Soap   | 4/CS
| 17.85 |  35 | 35 | 67 | 67 | Liquid Hand   |
Soap |
| 609 | Lincoln_Properties | 0 | 2030572|   0.00 |1 | 343 |
2030572| Americo 20" Beige Floor Pad  | 5/cs
| 15.88 | 335 |343 | 49 | 49 | Mats  |
Restaurant Paper/Pla |
| 159 | Lincoln_Properties | 0 | 2028071|  20.00 | NULL |  34 |
2028071| 25025088 77 Sanisac Liner| 500/CS
| 14.88 |  34 | 34 | 34 | 34 | Tampons   | Bathroom
Paper   |
| 158 | Lincoln_Properties | 0 | 2062866|  33.31 | NULL |  33 |
2062866| 7410 1/2 Fold Seat Cover | 3000/CS
| 35.81 |  33 | 33 | 35 | 35 | Toilet Seat Cover | Bathroom
Paper   |
| 155 | Lincoln_Properties | 0 | 5380447|  30.00 | NULL |  30 |
5380447| Scottfold Foldedd Towel 1-Ply White  | 4375/CS
| 35.00 |  30 | 30 | 33 | 33 | Toilet Tissue | Bathroom
Paper   |
| 154 | Lincoln_Properties | 0 | 5207270|   7.01 | NULL |  29 |
5207270| Standard Roll Bath Tissue 2-Ply White| 80/CS
| 43.50 |  29 | 29 | 33 | 33 | Toilet Tissue | Bathroom
Paper   |
| 164 | Lincoln_Properties | 0 | 5207269|  20.00 | NULL |  28 |
5207269| 17713-00 Kleenex Cottonelle 2-Ply Toilet Tissue  | 60/CS
| 35.50 |  28 | 28 | 33 | 33 | Toilet Tissue | Bathroom
Paper   |
| 157 | Lincoln_Properties | 0 | 5217344|  17.49 | NULL |  32 |
5217344| 1900-60 Kleenex Scottfold White Towel| 2400/CS
| 26.81 |  32 | 32 | 32 | 32 | Towels| Bathroom
Paper   |
+-++---+++--+-++--+-+---+-++++---+--+
13 rows in set (0.00 sec)

You will notice there is this data therein:

| 609 | Lincoln_Properties | 0 | 2030572|   0.00 |1 

list problem...

2010-09-28 Thread Rog
Hi all,
Have been grappling with a list problem for hours...
a = [2, 3, 4, 5,.]
b = [4, 8, 2, 6,.]
Basicly I am trying to place a[0], b[0] in a seperate list
IF a[2] and b[2] is present.
I have tried sets, zip etc with no success.
I am tackling Euler projects with Python 3.1, with minimal
knowledge, and having to tackle the language as I progress.
Enjoyable frustration  :)

-- 
Rog
http://www.rog.pynguins.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Expression problem.

2010-10-06 Thread Nethirlon .
Hi,

I am having trouble with an expression.

I have the following line of code:

self.failUnless(c.as == 65215)

What happens when you compile this is that you get a syntax error.
This is because as has been made a keyword. failUnless is from the
module unittest.

Now my problem is this. the ".as" is no where defined in the code. The
code builds just fine if you removed it. But the origigal programmer
must have put it in for a reason. I just cant understand what that is.

Can anyone point me into the right direction? was ".as" before it
became a keyword some kind of string manipulator?

Let me know if you need more info.
Thanks
-- 
http://mail.python.org/mailman/listinfo/python-list


unicode problem?

2010-10-09 Thread Brian Blais
This may be a stemming from my complete ignorance of unicode, but when I do 
this (Python 2.6):

s='\xc2\xa9 2008 \r\n'

and I want the ascii version of it, ignoring any non-ascii chars, I thought I 
could do:

s.encode('ascii','ignore')

but it gives the error:

In [20]:s.encode('ascii','ignore')

UnicodeDecodeErrorTraceback (most recent call last)

/Users/bblais/python/doit100810a.py in ()
> 1 
  2 
  3 
  4 
  5 

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 0: ordinal 
not in range(128)

am I doing something stupid here?

of course, as a workaround, I can do: ''.join([c for c in s if ord(c)<128])

but I thought the encode call should work.

thanks,
bb

-- 
Brian Blais
bbl...@bryant.edu
http://web.bryant.edu/~bblais
http://bblais.blogspot.com/



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


downcasting problem

2010-10-25 Thread Nikola Skoric
Hi everybody,

I need to downcast an object, and I've read repeatedly that if you
need to downcast, you did something wrong in the design phase. So,
instead of asking how do you downcast in python, let me explain my
situation.

I have a 2-pass parser. 1st pass ends up with a bunch of superclass
object, and 2nd pass is supposed to downcast those to one of
subclasses so I can work with them.

Details:

I have a file full of lines which I parse into Line objects. I also
have two subclasses of Line, namely Individual and Family. Constructor
of both subclasses needs all Line objects in the file to be
constructed, so I cannot construct subclass objects in the first pass.

The Python way of doing this (as I understand it) would be to wrap a
subclass around Line and have the Line object as an attribute of a
subclass. Now, this obviously breaks polymorphism and I now have to
reimplement all of Line's classes in subclasses. Although
reimplementation is simple (def method(self): return
self.line.method()), that way of doing things is just not elegant.

So, is there any more elegant solution to my problem?

Thanks in advance.

-- 
"Now the storm has passed over me
I'm left to drift on a dead calm sea
And watch her forever through the cracks in the beams
Nailed across the doorways of the bedrooms of my dreams"
-- 
http://mail.python.org/mailman/listinfo/python-list


Jythonc Problem

2006-07-04 Thread Ian Vincent
I cannot find a Jython newsgroup, so apologies in advance if this 
question has been posted to the wrong group.

Just written my first Jython program (previously written Python ones) 
and it is working fine in 'interpreted mode'. I now want to compile it 
into Java classes but I get the following error:

Traceback (innermost last):
  File "/usr/share/jython/Tools/jythonc/jythonc.py", line 5, in ?
  File "/usr/share/jython/Tools/jythonc/main.py", line 299, in main
  File "/usr/share/jython/Tools/jythonc/main.py", line 162, in 
getOptions
AttributeError: class 'org.python.modules.os' has no attribute 'path'

Jython version is Jython 2.2a0 installed from the Suse 10.0 rpm
Java version is 1.4.2_06-b03 (possibly also installed from the Suse 10.0 
rpm.

Any help would be appreciated.

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


Tkinter problem

2006-07-07 Thread Jim Anderson

I'm running Kubuntu a derivative of Debian Linux. I'm using
Python 2.4 and tcl/tk 8.4. I'm running Tkinter programs and
they were running about a month ago. When I tried them again
yesterday, I got the following message:

 > python ~/prog/python/iodef/iodef.py
 > Traceback (most recent call last):
 >   File "/home/jja/prog/python/iodef/iodef.py", line 10, in ?
 > import pkgview
 >   File "/home/jja/prog/python/iodef/lib/pkgview.py", line 3, in ?
 > from Tkinter import *
 >   File "/usr/lib/python2.4/lib-tk/Tkinter.py", line 38, in ?
 > import _tkinter # If this fails your Python may not be configured 
 > for Tk
 > ImportError: /usr/lib/python2.4/lib-dynload/_tkinter.so: cannot open 
 > > shared object file: No such file or directory

My environment varibles, like PTYHONPATH and TK_LIBRIARY all look
correct and the tcl/tk and python librarys are all still in place.
There is a file '/usr/lib/python2.4/lib-dynload/_tkinter.so'. I'm
not sure if this is the file not being found, but that is what is
sounds like.

I did a search on this on the web and got some hits, but none of them
provide a solution to my problem.

Can anyone help with this problem?

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


os.access() problem

2006-07-11 Thread Phil Schmidt
I just got a new PC with Windows XP, and I want to run Leo on it. Leo
uses the os.access() function to check for read-only files. For some
reason, os.access(, os.W_OK) always returns false.

I wrote a 2-liner Python script to just test os.access on any file.
I have tried this with Python 2.4 and 2.5b1.
I have uninstalled and re-installed Python and Leo.
I have fiddled with file permissions on the target files as well as on
the Python installation itself.
I have used cacls to check the access control lists (and although I'm
not exactly certain what to do with this information, it appears to be
ok - I think).

None of the above has helped me to identify or fix the problem.

A scan of the Python newsgroup suggests that os.access() may not be the
best way to check for read-only, but the discussion is a bit deeper
than my understanding, so I'm not sure there's anything to it in this
case.

I realize this must be a Windows permissions thing, but I just can't
figure it out. I'm no expert in Windows security beyond basic
permissions, so I could be missing something simple. Can anyone offer
any suggestions?

Thanks,
Phil

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


Problem Solved

2006-07-13 Thread dylpkls91
Thank you all for your responses.

I have managed to figure out a solution using XML RPC which fits my
needs perfectly.

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


mysqldb problem

2006-07-19 Thread liupei
when I set mysql some fields collate utf8_bin, and then fetch these
fields is array.array,not the string I expected

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


list problem

2006-07-25 Thread placid
Hi all,

I have two lists that contain strings in the form string + number for
example

>>> list1 = [ ' XXX1', 'XXX2', 'XXX3', 'XXX5']

the second list contains strings that are identical to the first list,
so lets say the second list contains the following

>>> list1 = [ ' XXX1', 'XXX2', 'XXX3', 'XXX6']

and now what ive been trying to do is find the first string that is
available,
i.e a string that is in neither of the two lists so the following code
should only print XXX4 then return.

for i in xrange(1,10):
numpart = str(1) + str("%04i" %i)
str = "XXX" + numpart

  for list1_elm in list1:
  if list1_elm == str:
   break
  else:
   for list2_elm in list2:
   if list2_elm == str:
  break
   else:
  print str
  return

Cheer

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


Python Problem

2007-09-07 Thread Wiseman
Hi,

The line:

import enchant

works perfectly OK when I call a Python progrma (sp.py) from IDLE
(WInXP). When I try to run it ftom the command line (python sp.py) the
response is:

Traceback (most recent call last):
   File "sp.py", line 3, in 
 import enchant
ImportError: No module named enchant

Searching my computer (the whole of drive c:\) I could not find ANY
file called enchant.*.

Does anyone know what is wrong?

Thanks

((:-()  Meir


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


pickling problem

2007-06-07 Thread Brian Blais
Hello,

I have a somewhat nested dict that I want to pickle, but it (sometimes) 
contains some
no-no's  (specifically, in this case, functions).  I know I can't pickle them, 
but I
would like to be able to pickle the rest of the dict.  Is there a good way to 
be able
to walk through a dict, and take out all of the non-pickleable objects?  I could
replace them with something else (a tag of some sort, for me to reconstruct 
things
later).


thanks,

Brian Blais

-- 
-

  [EMAIL PROTECTED]
  http://web.bryant.edu/~bblais

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


subprocess.Popen() problem

2007-06-26 Thread 7stud
I have this program:

mytest.py
--
myinput = raw_input("Enter input: ")

if myinput == "hello":
print "goodbye"
--

and I want to execute it using subprocess.Popen().  I tried the
following but it just hangs:

---
import subprocess

f = open("/Users/me/2testing/dir1/aaa.txt", "w")
my_path = "/Users/me/2testing/"
my_file = "mytest.py"

p = subprocess.Popen(["python", "mytest.py"], stdin=subprocess.PIPE,
stdout = f,
stderr = f,
cwd = my_path
)

f.close()

p.stdin.write("hello")
p.wait()

f.open("/Users/me/2testing/dir1/aaa.txt")
print f.read()


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


Unicode problem

2007-07-07 Thread [EMAIL PROTECTED]
Hi to all, I have a little problem with unicode handling under Python.

I have this code

s = u'A unicode string with this damn apostrophe \x2019'

outf = codecs.open('filename.txt', 'w', 'iso-8859-15')
outf.write(s)

what I obtain is a UnicodeEncodeError that says me that character \x2019
maps to undefined.

But the character \x2019 is the apostrophe and in the unicode table it has
\x0027 as an equivalent, so the codecs should convert \x2019 to \x27 ( as
defined in iso-8859-15 )

The problem is that my software deals with italian strings that has a lot
of apostrophe and other similar simbols mapped between 2000 and 206F

Have can I resolve this issue? Should I prepocess the unicode strings or
is there a way to instruct Python to do the conversion?
-- 
http://mail.python.org/mailman/listinfo/python-list


IDLE problem

2007-04-02 Thread Urban, Gabor
Hi,
 
I have a strange problem with the latest 2.4.4 on MS XP. If I rrun a
test script in DOS window, it is ok. From the Python shell I got error:
 

 
Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on
win32
Type "copyright", "credits" or "license()" for more information.
 

Personal firewall software may warn about the connection IDLE
makes to its subprocess using this computer's internal loopback
interface.  This connection is not visible on any external
interface and no data is sent to or received from the Internet.


IDLE 1.1.4  
>>>  RESTART

>>> 

--
Ran 8 tests in 0.016s
 
OK
 
Traceback (most recent call last):
  File "D:\Gabaux\Python\TodoList\datetest.py", line 76, in -toplevel-
unittest.main()
  File "D:\Python24\lib\unittest.py", line 759, in __init__
self.runTests()
  File "D:\Python24\lib\unittest.py", line 797, in runTests
sys.exit(not result.wasSuccessful())
SystemExit: False
>>> 


The script I was executing was a simple unittest.TestCase descendant.
 
Any ideas?

Gabor Urban
NMC - ART 

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

Unicode problem

2007-04-07 Thread Rehceb Rotkiv
Please have a look at this little script:

#!/usr/bin/python
import sys
import codecs
fileHandle = codecs.open(sys.argv[1], 'r', 'utf-8')
fileString = fileHandle.read()
print fileString

if I call it from a Bash shell like this

$ ./test.py testfile.utf8.txt

it works just fine, but when I try to pipe the output to another process 
("|") or into a file (">"), e.g. like this

$ ./test.py testfile.utf8.txt | cat

I get an error:

Traceback (most recent call last):
  File "./test.py", line 6, in ?
print fileString
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in 
position 538: ordinal not in range(128)

I absolutely don't know what's the problem here, can you help?

Thanks,
Rehceb
-- 
http://mail.python.org/mailman/listinfo/python-list


Try problem

2007-04-13 Thread SamG
import sys
try:
 s=1
 if s==1:
  sys.exit(0)
 else:
  sys.exit(1)
except SystemExit,s:
 if (s==0):
  print s
 else:
  print "Hello"

How come i always end up getting the "Hello" printed on the screen as
logically i should a '0' printed?

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


pycurl problem

2007-04-18 Thread pabloski
Hi to all, I have a problem with a snippet of code that creates a Curl
object

the code is

c = pycurl.Curl()

c.key = keyCurrent
c.proxy = proxyCurrent
c.url = "http://www.google."; + lg + "/search?hl=" + lg + "&q=" + c.key +
"&meta=lr%3Dlang_" + lg + "&num=30"

c.setopt(pycurl.URL, c.url)
c.setopt(pycurl.PROXY, c.proxy)

the last two lines raise a TypeError

obviously proxyCurrent, lg and keyCurrent are parameters

I noted that if I define c.proxy and c.url as costants e.g. c.url =
"http://www.google.com/search?blah blah" and c.proxy =
"127.0.0.1:8080" it works

However if I define them as described before pycurl raises the TypeError
-- 
http://mail.python.org/mailman/listinfo/python-list


setDaemon problem.

2007-04-20 Thread Ramashish Baranwal
Hi,

I am facing an issue in daemonizing a thread using setDaemon method.
Here is my code-

import time
from threading import Thread

class MThread(Thread):
def run(self):
f = open('/tmp/t.log', 'w')
for i in range(10):
f.write('Iteration %d\n' % i)
time.sleep(1)
f.close()

if __name__ == "__main__":
t = MThread()
t.setDaemon(True)
print 'Starting thread'
t.start()

The scripts runs all fine, but nothing gets logged to "/tmp/t.log".
However when I run the same script without setting thread as daemon
(no call to t.setDaemon), everything works fine.

Am I missing anything?

Thanks in advance,
Ram

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


Redirection problem

2007-04-23 Thread CSUIDL PROGRAMMEr
I am new to python. so be patient with me

I am trying to redirect the output of os.popen command to a file. I
want to append to that file. but instead of appending. The file only
shows last command that was writtenn to  it.



 filehandle= open("/root/yhpc-2.0/installer/yhpc-log" ,"a+");
filehandle.write(" Command executed is " + cmd);
try:
  pipe= os.popen('%s > /root/yhpc-2.0/installer/yhpc-log' %cmd );
except : IOError;
  filehandle.close();


Any  suggestion would help.



filehandle.close();

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


Inheritance problem

2007-05-09 Thread amidzic . branko
I'm trying to solve a problem using inheritance and polymorphism in
python 2.4.2



I think it's easier to explain the problem using simple example:



class shortList:

def __init__(self):

self.setList()



def setList(self):

a = [1,2,3]

print a



class longList(shortList):

def __init__(self):

shortList.setList()

self.setList()



def setList(self):

a.extend([4,5,6])

print a



def main():

a = raw_input('Do you want short or long list? (s/l)')

if a.upper() == 'S':

lst = shortList()

else:

lst = longList()



lst.setList()



if __name__ == '__main__':

main()



After that I'm getting a message:

TypeError: unbound method setList() must be called with shortList
instance as first argument (got nothing instead)



Where is the problem?



Thanks in advance...

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


matplotlib problem

2007-05-10 Thread redcic
I've got a question regarding matplotlib. I use the command:
pylab.plot(...)
to create a graph.
Then, the execution of the code stops after the line:
pylab.show()
which is off course the last line of my code.

My problem is that I have to close the figure window before in order
to finish the execution of my code.
I'd like to be able to launch my program other times with different
parameters without having to close the figure windows before each
launch.
Just so you know, I'm using TkAgg backend and the SciTE editor.

Following the answer I was given in the thread:
http://groups.google.com/group/comp.lang.python/browse_thread/thread/939fc6c7a9645bd8/f939f2db9da55430?lnk=gst&q=redcic&rnum=1#f939f2db9da55430
I set "interactive : True" in matplotlibrc.
I also tried the other things I had been advised to do but I still
have the same problem.

Any other idea ?

Thanks,

Cédric

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


f2py problem

2007-05-15 Thread Alberto Vera
Hello.

After I installed f2py using Python, NumPy and Numarray software, I 
can't use f2py

I saw this error:

Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'f2py' is not defined
 >>>

Could you tell me what is the problem?

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


BeautifulSoup problem

2006-10-20 Thread placid
Hi all,

Just wondering if anyone knows how to get the text between the tags of
the following Tag object? 

Hello

Cheers

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


strange problem

2006-10-24 Thread ken
This file has 1,000,000+ lines in it, yet when I print the counter 'cin' 
at EOF I get around 10,000 less lines. Any ideas?

lineIn = 
csv.reader(file("rits_feed\\rits_feed_US.csv",'rb'),delimiter='|')
 for emp in lineIn:
 cin=cin+1
 print cin
-- 
http://mail.python.org/mailman/listinfo/python-list


win32com problem

2006-10-24 Thread cfriedalek
I'm interacting with a third party application using python and com.
However having problems and don't know what to look at next to resolve
the issue.

The app. can be driven by VBS. The following VBS code works:

Set Synergy = CreateObject("synergy.Synergy")
Synergy.OpenProject "D:/temp/project.mpi"
Synergy.Project.OpenItemByName "test_bar_3d_6l_pc1", "Study"
Set Tet = Synergy.StudyDoc.GetFirstTet()
While Not Tet Is Nothing
  Str = Tet.ConvertToString() + " "
  Set Tet = Synergy.StudyDoc.GetNextTet(Tet)
  MsgBox Str
WEnd

This prints "TE1" "TE2" etc


The "same" code in python returns > with each call
to the GetNextTet method.

import win32com.client
from win32com.client import Dispatch
Synergy = win32com.client.Dispatch("synergy.Synergy")
Synergy.OpenProject("D:/temp/project.mpi")
Synergy.Project.OpenItemByName("test_bar_3d_6l_pc1", "Study")
tet = Synergy.StudyDoc.GetFirstTet
while tet:
print str(tet)
tet = Synergy.StudyDoc.GetNextTet(tet)

Any clues on what I'm doing wrong, or how to investigate whether there
is a bug in win32com or in the third party apps com implementation.

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


dict problem

2006-10-25 Thread Alistair King
Hi,

ive been trying to update a dictionary containing a molecular formula, but seem 
to be getting this error:


Traceback (most recent call last):
  File "DS1excessH2O.py", line 242, in ?
updateDS1v(FCas, C, XDS)
NameError: name 'C' is not defined

dictionary is: 

DS1v = {'C': 6, 'H': 10, 'O': 5}



#'Fxas' in each case will be integers but 'atoms' should be a float

def updateDS1v(Fxas, x, XDS):
while Fxas != 0:
atoms = DS1v.get('x') + Fxas*XDS
DS1v[x] = atoms

updateDS1v(FCas, C, XDS)
updateDS1v(FHas, H, XDS)
updateDS1v(FOas, O, XDS)
updateDS1v(FNas, N, XDS)
updateDS1v(FSas, S, XDS)
updateDS1v(FClas, Cl, XDS)
updateDS1v(FBras, Br, XDS)
updateDS1v(FZnas, Zn, XDS)
print DS1v

I know there is probably a simple solution but im quite new to python and am 
lost?


Ali


-- 
Dr. Alistair King
Research Chemist,
Laboratory of Organic Chemistry,
Department of Chemistry,
Faculty of Science
P.O. Box 55 (A.I. Virtasen aukio 1)
FIN-00014 University of Helsinki
Tel. +358 9 191 50392, Mobile +358 (0)50 5279446
Fax +358 9 191 50366 

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


dict problem

2006-10-25 Thread Alistair King
Jon Clements wrote:

> > Alistair King wrote:
> >
> >   
>   
>> >> Hi,
>> >>
>> >> ive been trying to update a dictionary containing a molecular formula, 
>> >> but seem to be getting this error:
>> >>
>> >>
>> >> Traceback (most recent call last):
>> >>   File "DS1excessH2O.py", line 242, in ?
>> >> updateDS1v(FCas, C, XDS)
>> >> NameError: name 'C' is not defined
>> >>
>> >> dictionary is:
>> >>
>> >> DS1v = {'C': 6, 'H': 10, 'O': 5}
>> >>
>> >>
>> >>
>> >> #'Fxas' in each case will be integers but 'atoms' should be a float
>> >>
>> >> def updateDS1v(Fxas, x, XDS):
>> >> while Fxas != 0:
>> >> atoms = DS1v.get('x') + Fxas*XDS
>> >> DS1v[x] = atoms
>> >>
>> >> updateDS1v(FCas, C, XDS)
>> >> updateDS1v(FHas, H, XDS)
>> >> updateDS1v(FOas, O, XDS)
>> >> updateDS1v(FNas, N, XDS)
>> >> updateDS1v(FSas, S, XDS)
>> >> updateDS1v(FClas, Cl, XDS)
>> >> updateDS1v(FBras, Br, XDS)
>> >> updateDS1v(FZnas, Zn, XDS)
>> >> print DS1v
>> >>
>> >> I know there is probably a simple solution but im quite new to python and 
>> >> am lost?
>> >>
>> >> 
>> 
> >
> > I strongly suggest reading through the tutorial.
> >
> > I don't think there's enough code here for anyone to check it properly.
> > For instance, it looks like FCas exists somewhere as it's barfing on
> > trying to find C. Where is XDS defined etc...?
> >
> > I can't see updateDS1v() ever completing: any Fxas passed in not equal
> > to 0 will repeat indefinately.
> >
> > I'm guessing unless C is meant to be a variable, you mean to pass in
> > the string 'C'.
> >
> > A dictionary already has it's own update method
> >
> > Perhaps if you explain what you're trying to do in plain English, we
> > could give you some pointers.
> >
> > Jon.
> >
> >   
>   
sorry,

this has been a little rushed

XDS is defined before the function and is a float.
the Fxas values are also and they are integers


now ive tried

def updateDS1v(Fxas, x, XDS):
while Fxas != 0:
atoms = DS1v.get(x) + Fxas*XDS
DS1v['x'] = atoms

updateDS1v(FCas, 'C', XDS)
updateDS1v(FHas, H, XDS)
updateDS1v(FOas, O, XDS)
updateDS1v(FNas, N, XDS)
updateDS1v(FSas, S, XDS)
updateDS1v(FClas, Cl, XDS)
updateDS1v(FBras, Br, XDS)
updateDS1v(FZnas, Zn, XDS)
print DS1v

from this i get the error:

Traceback (most recent call last):
File "DS1excessH2O.py", line 242, in ?
updateDS1v(FCas, 'C', XDS)
File "DS1excessH2O.py", line 239, in updateDS1v
atoms = DS1v.get(x) + Fxas*XDS
TypeError: unsupported operand type(s) for +: 'int' and 'str'


with single quotes (FCas, 'C', XDS) to retrieve the value for that key
from the dictionary and then create the new value and replace the old value.

a


-- 
Dr. Alistair King
Research Chemist,
Laboratory of Organic Chemistry,
Department of Chemistry,
Faculty of Science
P.O. Box 55 (A.I. Virtasen aukio 1)
FIN-00014 University of Helsinki
Tel. +358 9 191 50392, Mobile +358 (0)50 5279446
Fax +358 9 191 50366 

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


dict problem

2006-10-30 Thread Alistair King
Ben Finney wrote:
> Alistair King <[EMAIL PROTECTED]> writes:
>
>   
>> Ben Finney wrote:
>> 
>>> Even better, work on a minimal program to do nothing but reproduce
>>> the unexpected behaviour. If you get to such a program and still
>>> don't understand, then post it here so others can run it
>>> themselves and explain.
>>>   
>> ive checked the values and XDS is actually returning a string where i
>> want a float ie '123.45' not 123.45.
>> 
>
> Can you please post a small, complete program that shows the behaviour
> you want explained?
>
> You get this program by writing it -- either by cutting away
> irrelevant parts of the existing program, or (better) writing a new
> program from scratch that does nothing except demonstrate the
> behaviour.
>
> Note that in the process of getting such a program behaving this way,
> you may end up understanding the problem better.
>
>   
i have seemed to work out most of the problems from the previous code,
now i have:
...

heavy = raw_input("\n\n@@\n\nPlease enter the heaviest
atom for which you obtained percentage values for, but not Oxygen, eg,
'C', 'N', 'S', 'Br'...: ")

print DSvalues

def updateDS1v(Fxas, x):
if Fxas != 0:
value = DSvalues.get(heavy)
floatvalue = float(value)
atoms = DS1v.get(x) + Fxas*floatvalue
DS1v[x] = atoms

updateDS1v(FCas, 'C')

print DS1v
...

the problem now is converting badly formatted dictionary values into floats
ive been trying something like this, where 'value' is a typical entry
into the dictionary:
...

IDLE 1.1
>>> value = "'0.0642501084'"
>>> print float(value)

and get the error, in IDLE and the code as:

Traceback (most recent call last):
File "", line 1, in -toplevel-
print float(value)
ValueError: invalid literal for float(): '0.0642501084'

...

Is there any other way of removing double and single quotes from a
number, as a string, to give the float value again?

I know it would be easier to create a properly formatted dictionary
again and i will do that but it would be good to know as i want to get
this program running properly to get some results i need for work.
Everything else seems to be working fine but this.

thanks

a

-- 
Dr. Alistair King
Research Chemist,
Laboratory of Organic Chemistry,
Department of Chemistry,
Faculty of Science
P.O. Box 55 (A.I. Virtasen aukio 1)
FIN-00014 University of Helsinki
Tel. +358 9 191 50392, Mobile +358 (0)50 5279446
Fax +358 9 191 50366 

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


pyfits problem

2006-11-16 Thread Tommy Grav
I am trying to load in a fits-image and get this error

wiyn05dec/n1 -> display -i obj062.fits
Traceback (most recent call last):
   File "/Users/tgrav/Work/Astronomy/MyCode/Python/Redspit/ 
display.py", line 48, in ?
 main()
   File "/Users/tgrav/Work/Astronomy/MyCode/Python/Redspit/ 
display.py", line 30, in main
 im  = pyfits.getdata(options.infname)
   File "/Library/Frameworks/Python.framework/Versions/2.4/lib/ 
python2.4/site-packages/pyfits/NP_pyfits.py", line 4645, in getdata
 _data = hdu.data
   File "/Library/Frameworks/Python.framework/Versions/2.4/lib/ 
python2.4/site-packages/pyfits/NP_pyfits.py", line 2058, in __getattr__
 self.data = np.array(raw_data, type=np.Float32)
AttributeError: 'module' object has no attribute 'Float32'

I am using numpy 1.0rc3 and ActivePython 2.4.3 Build 11.
Anyone know what is going on?

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


regex problem

2006-11-22 Thread km

Hi all,

line is am trying to match is
1959400|Q2BYK3|Q2BYK3_9GAMM Hypothetical outer membra29.90.00011   1

regex i have written is
re.compile
(r'(\d+?)\|((P|O|Q)\w{5})\|\w{3,6}\_\w{3,5}\s+?.{25}\s{3}(\d+?\.\d)\s+?(\d\.\d+?)')

I am trying to extract 0.0011 value from the above line.
why doesnt it match the group(4) item of the match ?

any idea whats wrong  with it ?

regards,
KM
-- 
http://mail.python.org/mailman/listinfo/python-list

Installation problem

2006-11-26 Thread Tommy Grav
Trying to update my ActivePython installation I mistakenly downloaded
the Intel Mac version (rather than the PPC version) and tried to  
install it.
The version did install but did not run of course. However, now trying
to install the PPC version of Activepython or even the 2.5 version of
macpython fails (actually macpython installs, but the installation  
program
tells me there is an error at the end). Anyone know how to completely
remove all previous python installations and all config files so that  
I can
install it from scratch? Is there also a log of the dmg-installation  
so that
I can see what fails with the installation?

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


Memory problem

2006-08-14 Thread Yi Xing
Hi,

I need to read a large amount of data into a list. So I am trying to 
see if I'll have any memory problem. When I do
x=range(2700*2700*3) I got the following message:

Traceback (most recent call last):
File "", line 1, in ?
MemoryError

Any way to get around this problem? I have a machine of 4G memory. The 
total number of data points (float) that I need to read is in the order 
of 200-300 millions.

Thanks.

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


Memory problem

2006-08-14 Thread Yi Xing
I tried the following code:

>>> i=0
>>> n=2600*2600*30
>>> a=array.array("f")
>>> while (i<=n):
.. i=i+1
.. a.append(float(i))
..
Traceback (most recent call last):
  File "", line 3, in ?
MemoryError

to see the size of the array at the time of memory error:
>>>len(a)
8539248.

I use Windows XP x64 with 4GB RAM.
-- 
http://mail.python.org/mailman/listinfo/python-list


drawingarea problem

2006-08-16 Thread Rafał Janas
Is somebody try to paint filled boxes in drawingarea?
I don't know how to paint line or someting like this.
Maybe somebody have tutorial or samples?

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


List problem

2006-08-24 Thread kevndcks
For example i write the following code in the Python command line;

>>>list = ['One,Two,Three,Four']

Then enter this command, which will then return the following;

['One,Two,Three,Four']


Now the problem, reading through the Python tutorial's, it describe's
that list's can sliced, concatenated and so on etc

So i write the following

>>>list[1:] + ['Five']

Then the error returned is that 'str' and 'list' could not be
concatenated which is where it baffles me. I'm understanding that this
mean's that the string 'Five' could not be joined onto the list, as i
havn't defined it in the array. Viewing the Python tutrial they have
the following, and working code;

>>> a[:2] + ['bacon', 2*2]
['spam', 'eggs', 'bacon', 4]

How can they have the string 'bacon' and have it returned with no
error?

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


class problem

2006-08-28 Thread fegge
when i declare a class, is there difference between the below:
class myClass():
class myClass(threading.Thread)

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


wxTimer problem

2006-09-15 Thread abcd
I have a python script which creates a wx.App, which creates a wx.Frame
(which has a wx.Timer).

looks sorta like this:

class MyProgram:
def __init__(self):
self.app = MyApp(0)
self.app.MainLoop()

class MyApp(wx.App):
def OnInit(self):
self.myframe= MyFrame()
self.myframe.Show(True)
self.SetTopWindow(self.myframe)
return True

class MyFrame(wx.Frame):
def __init__(self):
   # do some other stuff here

   # setup the timer
self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer)
self.timer.Start(100)

def killTimer(self):
self.Unbind(wx.EVT_TIMER)
self.timer.Stop()
self.timer = None


that's the jist of it.

Anyhow, so I startup python and import my script, which loads up the
wx.App, frame and all.

foo = MyProgram()


Then I close the frame.  when the frame is closed it calls killTimer.
This method gets called and no exceptions occur.

Then...I create a new instance of the app and try to load the frame
again.

foo = MyProgram()

...and I am getting this error:

"timer can only be started from the main thread"

how can I fix this??

FYI, my script is being started by a new thread each time, so
ultimately we have

def startProgram():
foo = MyProgram()

threading.Thread(target=startProgram).start()


Thanks in advance.

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


  1   2   3   4   5   6   7   8   9   10   >