Re: logging in omniORB for python
Birgit Rahm wrote:
Hello newsgroup,
Hello Birgit,
I haven't found any way to do logging in a standard way.
The solution i've implemented is to decorate each method you want to log
the call, using the logging module (included in python since 2.3)
For example :
import logging
def loggedmethod(method):
logger = logging.getLogger('mylogger')
def _loggedmethod(self, *args, **kw):
logger.debug('## %s was called ##' % method.func_name)
return method(self, *args, **kw)
return _loggedmethod
# imagine A is your corba object
class A:
def foo(self):
return 'foo'
foo = loggedmethod(foo)
if __name__ == '__main__':
logger = logging.getLogger("mylogger")
logger.addHandler(logging.StreamHandler())
logger.setLevel(logging.DEBUG)
a = A()
print a.foo()
when running :
bash-2.05b$ python plop.py
## foo was called ##
foo
--
http://mail.python.org/mailman/listinfo/python-list
Re: Chanelling Guido - dict subclasses
I can't speak for Guido but I think it is messy and unnatural and will lead to user frustration. As a user, I would expect a dict to take any hashable as key and any object as value when using one. I would probably just provide a __getitem__ method in a normal class in your case. This said I have overriden dict before, but my child class only added to dict, I didn't change it's underlying behaviour so you can use my class(es) as a vanilla dict everywhere, which enforcing types would have destroyed. On 01:27 15/01 , Steven D'Aprano wrote: >Over on the Python-Dev mailing list, there is an ENORMOUS multi-thread >discussion involving at least two PEPs, about bytes/str compatibility. >But I don't want to talk about that. (Oh gods, I *really* don't want to >talk about that...) > >In the midst of that discussion, Guido van Rossum made a comment about >subclassing dicts: > >[quote] >From: Guido van Rossum >Date: Tue, 14 Jan 2014 12:06:32 -0800 >Subject: Re: [Python-Dev] PEP 460 reboot > >Personally I wouldn't add any words suggesting or referring >to the option of creation another class for this purpose. You >wouldn't recommend subclassing dict for constraining the >types of keys or values, would you? >[end quote] > >https://mail.python.org/pipermail/python-dev/2014-January/131537.html > >This surprises me, and rather than bother Python-Dev (where it will >likely be lost in the noise, and certain will be off-topic), I'm hoping >there may be someone here who is willing to attempt to channel GvR. I >would have thought that subclassing dict for the purpose of constraining >the type of keys or values would be precisely an excellent use of >subclassing. > > >class TextOnlyDict(dict): >def __setitem__(self, key, value): >if not isinstance(key, str): >raise TypeError >super().__setitem__(key, value) ># need to override more methods too > > >But reading Guido, I think he's saying that wouldn't be a good idea. I >don't get it -- it's not a violation of the Liskov Substitution >Principle, because it's more restrictive, not less. What am I missing? > > >-- >Steven > -- yrNews Usenet Reader for iOS http://appstore.com/yrNewsUsenetReader -- https://mail.python.org/mailman/listinfo/python-list
Open Office and Python
Hello there! I'd like to load a .csv file to the Open Office spreadsheet from the command line using an arbitrary delimiter through Python. I don't need any fancy formatting and stuff like that, just putting the values in the spreadsheet will do. Is there a relatively simple way to do that? Sorry for the unfocused nature of this question. I wouldn't have asked it if this weren't a one-off task and if I didn't need this urgently. Any help and pointers would be greatly appreciated. Thanks and best regards, F. -- http://mail.python.org/mailman/listinfo/python-list
Re: query progress bar
Timothy Smith wrote: > is it possible to mke a progress bar for queries? say i have a query > that will take 20 seconds, i'd like to give some feed back to users on > how long this will take. it is strictly impossible to predict that cause of network load, server load, query complexity i recommend you put an activity widget, something moving (ie throbber in wxPython) while waiting for the result (like the rotating circle in firefox). once query is finished stop your moving stuff, so the user knows it's completed. So you don't need a progress bar, but an activity widget. in gtk, i saw that progress bar could be put in activity mode. And don't forget to add a timeout ... François -- http://mail.python.org/mailman/listinfo/python-list
Problems compiling on CentOS Python 2.5
Hello, I have problems making python on CentOS 5. Seems that can not find something. I can not find the problem. Where is the problem? > case $MAKEFLAGS in \ > *-s*) CC='gcc -pthread' LDSHARED='gcc -pthread -shared' > OPT='-DNDEBUG -fwrapv -march=i686 -mmmx -msse -msse2 -msse3 -O3 -pipe > -fomit-frame-pointer -Wall -Wstrict-prototypes' ./python -E ./setup.py -q > build;; \ > *) CC='gcc -pthread' LDSHARED='gcc -pthread -shared' OPT='-DNDEBUG > -fwrapv -march=i686 -mmmx -msse -msse2 -msse3 -O3 -pipe -fomit-frame-pointer > -Wall -Wstrict-prototypes' ./python -E ./setup.py build;; \ > esac > running build > running build_ext > db.h: found (4, 3) in /usr/include > db lib: using (4, 3) db-4.3 > INFO: Can't locate Tcl/Tk libs and/or headers > building '_ssl' extension > gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -fwrapv -march=i686 -mmmx > -msse -msse2 -msse3 -O3 -pipe -fomit-frame-pointer -Wall -Wstrict-prototypes > -I. -I/home/unStable/progC/exLibs/Python-2.5.2/Python-2.5.2/./Include -I. > -IInclude -I./Include -I/usr/local/include > -I/directory/Python-2.5.2/Python-2.5.2/Include > -I/directory/Python-2.5.2/Python-2.5.2 -c > /directory/Python-2.5.2/Python-2.5.2/Modules/_ssl.c -o > build/temp.linux-i686-2.5/directory/Python-2.5.2/Python-2.5.2/Modules/_ssl.o > gcc -pthread -shared -fno-strict-aliasing -DNDEBUG -fwrapv -march=i686 -mmmx > -msse -msse2 -msse3 -O3 -pipe -fomit-frame-pointer -Wall -Wstrict-prototypes > build/temp.linux-i686-2.5/directory/Python-2.5.2/Python-2.5.2/Modules/_ssl.o > -L/usr/local/lib -lssl -lcrypto -o build/lib.linux-i686-2.5/_ssl.so > *** WARNING: renaming "_ssl" since importing it failed: > build/lib.linux-i686-2.5/_ssl.so: undefined symbol: krb5_auth_con_getrcache > running build_scripts -- -- Publicidad http://www.pas-world.com -- http://mail.python.org/mailman/listinfo/python-list
Retrieving result from embedded execution
Hello everyone, We are trying to implement our own interactive interpreter in our applicationusing an embedded Python interpreter. I was wondering what would be the best way to retreive as text the result of executing Python code. The text must be exactly the same as it would be in thestandalone interpreter. We used to do this by changing the embedded interpreter's sys.stdout and sys.stderrwith a FILE created in C++. We could then execute code using the PyRun_InteractiveOnefunction and easily retrieve the result from the FILE. The problem is, our applicationshouldn't create any files if possible. We also tried replacing sys.stdout and sys.stderr with a custom made Python objectwhich could be more easily read from C++. We then used the function PyRun_Stringto execute the code. The problem here is that using the Py_file_input start tokendoesn't write everything we need to sys.stdout. (i.e. executing 2+2 does not write 4).It also doesn't print a traceback to sys.stderr when there is an exception. Using theother two start tokens is impossible since we need to be able to execute more than one instruction at once. We also tried using the function PyRun_SimpleString but weencounter the same problems. We are using python 2.7. Any suggestions? Thank you for your time. Also, I'm new to mailling lists, what is the proper way to reply to someone? Should Ireply directly to someone's email adress or is there a way to answer trough the server. F. Lab -- http://mail.python.org/mailman/listinfo/python-list
RE: Embedded python console and FILE* in python 3.2
> Is the `code` module (http://docs.python.org/library/code.html) an
> insufficiently exact copy of an interpreter for you?
The problem isn't really to emulate the behavior of the interpreter as to
obtain the result of the execution as a string in c++. The code module doesn't
seem to help with this matter.
> I assume you could simply use PyFile_FromFd?
According to the documentation using PyFile_FromFd seems unadvised, but I'll
give it a try.
> The more elegant solution might be to create custom Python file-like> objects
> for std{in,out,err} that communicate directly with your application.I thought
> about this, but I need the console window to be non-modal and I'm afraid that
> replacing stdin witha custom file-like object would cause a blocking call.
> Executing python in a second thread would solve this problembut our
> application isn't multi-threaded and executing python in another thread
> causes errors.
Maybe I could use a file-like object to communicate the results to my c++
application and use the code module to execute code only when the c++
application needs it.
Thanks a lot for the tips, have a nice day.
F.L. --
http://mail.python.org/mailman/listinfo/python-list
RE: Embedded python console and FILE* in python 3.2
> If you use the same workflow as you do currently, it won't
You're right it shouldn't cause a blocking call.
> Come to think of it, you might as well just use StringIO.
Yes I could probably replace std{in, out, err} with stringIO objects and
retrieve their contents throughthe api.
I'll look into it, thank again.
F.L.
> Date: Mon, 8 Aug 2011 19:52:14 +0200
> From: [email protected]
> To: [email protected]
> Subject: Re: Embedded python console and FILE* in python 3.2
>
> On 08/08/11 19:44, Thomas Jollans wrote:
>
> >
> > 1. Feed input to your custom stdin object, which will buffer the code.
> > 2. Call PyRun_IteractiveOne - it will read from your object, which will
> >return the buffer contents.
> > 3. The result is somehow handled by custom stdout and stderr objects.
> >
>
> Come to think of it, you might as well just use StringIO.
> --
> http://mail.python.org/mailman/listinfo/python-list
--
http://mail.python.org/mailman/listinfo/python-list
request fails on wikipedia (https) - certificate verify failed (_ssl.c:748)
Hi,
I would like to get information from Wikipedia articles and I am testing the
connection to Wikipedia.
I am running Python 3.6.2 on Windows 10.
I get certificate errors for all pages with https.
Any suggestions are welcome!
Here my code:
import requests, bs4
from bs4 import BeautifulSoup
res = requests.get('https://en.wikipedia.org/wiki/Stethoscope')
type(res)
res.status_code == requests.codes.ok
wiki = bs4.BeautifulSoup(res.text)
type(wiki)
len(res.text)
print(res.text[:250])
Here the error message:
Traceback (most recent call last):
File "c:\Program Files
(x86)\Python36-32\lib\site-packages\urllib3\connectionpool.py", line 601, in
urlopen
chunked=chunked)
File "c:\Program Files
(x86)\Python36-32\lib\site-packages\urllib3\connectionpool.py", line 346, in
_make_request
self._validate_conn(conn)
File "c:\Program Files
(x86)\Python36-32\lib\site-packages\urllib3\connectionpool.py", line 850, in
_validate_conn
conn.connect()
File "c:\Program Files
(x86)\Python36-32\lib\site-packages\urllib3\connection.py", line 326, in connect
ssl_context=context)
File "c:\Program Files
(x86)\Python36-32\lib\site-packages\urllib3\util\ssl_.py", line 329, in
ssl_wrap_socket
return context.wrap_socket(sock, server_hostname=server_hostname)
File "c:\Program Files (x86)\Python36-32\lib\ssl.py", line 401, in wrap_socket
_context=self, _session=session)
File "c:\Program Files (x86)\Python36-32\lib\ssl.py", line 808, in __init__
self.do_handshake()
File "c:\Program Files (x86)\Python36-32\lib\ssl.py", line 1061, in
do_handshake
self._sslobj.do_handshake()
File "c:\Program Files (x86)\Python36-32\lib\ssl.py", line 683, in
do_handshake
self._sslobj.do_handshake()
ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed
(_ssl.c:748)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\Program Files
(x86)\Python36-32\lib\site-packages\requests\adapters.py", line 440, in send
timeout=timeout
File "c:\Program Files
(x86)\Python36-32\lib\site-packages\urllib3\connectionpool.py", line 639, in
urlopen
_stacktrace=sys.exc_info()[2])
File "c:\Program Files
(x86)\Python36-32\lib\site-packages\urllib3\util\retry.py", line 388, in
increment
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='en.wikipedia.org',
port=443): Max retries exceeded with url: /wiki/Stethoscope (Caused by
SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify
failed (_ssl.c:748)'),))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "web_1.py", line 3, in
res = requests.get('https://en.wikipedia.org/wiki/Stethoscope')
File "c:\Program Files (x86)\Python36-32\lib\site-packages\requests\api.py",
line 72, in get
return request('get', url, params=params, **kwargs)
File "c:\Program Files (x86)\Python36-32\lib\site-packages\requests\api.py",
line 58, in request
return session.request(method=method, url=url, **kwargs)
File "c:\Program Files
(x86)\Python36-32\lib\site-packages\requests\sessions.py", line 508, in request
resp = self.send(prep, **send_kwargs)
File "c:\Program Files
(x86)\Python36-32\lib\site-packages\requests\sessions.py", line 618, in send
r = adapter.send(request, **kwargs)
File "c:\Program Files
(x86)\Python36-32\lib\site-packages\requests\adapters.py", line 506, in send
raise SSLError(e, request=request)
requests.exceptions.SSLError: HTTPSConnectionPool(host='en.wikipedia.org',
port=443): Max retries exceeded with url: /wiki/Stethoscope (Caused by
SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify
failed (_ssl.c:748)'),))
--
https://mail.python.org/mailman/listinfo/python-list
Re: request fails on wikipedia (https) - certificate verify failed (_ssl.c:748)
Am Dienstag, 12. Dezember 2017 14:33:42 UTC+1 schrieb Jon Ribbens: > On 2017-12-11, F Massion wrote: > > ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed > > (_ssl.c:748) > > Try `pip install certifi` certifi was installed. If I make the following changes I do not have the error message. I don't understand why, but this makes a difference: #import requests --> import urllib.request url = 'https://en.wikipedia.org/wiki/Stethoscope' #res = requests.get(url) --> res = urllib.request.urlopen(url).read() -- https://mail.python.org/mailman/listinfo/python-list
Variable number of arguments
My script is used by a web interface which gets some parameters from a form. The parameters are passed on as arguments like this: (...) def start(self, _Inputfile ,_Outputfile ,_Stopwordsfile) As long as the number of arguments is set (i.e. 3), there are no problems running the script. Currently I have e.g. ARGV[0] = _Inputfile ARGV[1] = _Outputfile ARGV[2] = _Stopwordsfile Now I want to allow a variable number of arguments, i.e. 1..n input files or stopwords lists. In this case ARGV[0] would become [filename1.txt, filename2.txt,...], but I wonder how ARGV[1] would still remain _Outputfile. I thought of using the argparse module with nargs='+' for a variable number arguments but it seems to work only with Python 2.7 and I have 3.6 running. Any suggestions? -- https://mail.python.org/mailman/listinfo/python-list
Re: Python 2.4 under WinXP, free VC71 toolkit and VC6 libraries
Le Tue, 27 Sep 2005 17:48:47 +0200, Berthold Höllmann a écrit : > I have wrapped some inhouse libraries for Python. How ? Directly coding C code ? > The development team > uses VC6 and DF6.1 for development of these libraries under WinXP. DF6.1 is Digital FORTRAN 6.1 ? > I > would like to wrap the libraries for Python and use the official Win > Python from python.org. Now I get a segmentation fault in (access > violation in NTDLL.DLL). The code used to work on Python 2.3, so I > am afraid I have a plroblem in mixing the code generated by different > VC versions. Is this the probable cause of my problem, or should the > combination work in general (some libraries seem to work). > > Kind regards > Berthold A possible solution would be to write any VC6 and DF6.1 code to generate some DLLs (black boxes) and to use these DLLs from Python by using ctypes, to build your applications. All the CPU intensive code should be in DLLs and the high level stuff (GUI, presentation, application logic, ...) could be in python. (GUI with wnd or venster for example). Regards. -- http://mail.python.org/mailman/listinfo/python-list
Re: tachometer diagram
Could it be http://xoomer.virgilio.it/infinity77/eng/freeware.html#speedmeter you are looking for? HTH Franz GEIGER "Andreas Kaiser" <[EMAIL PROTECTED]> schrieb im Newsbeitrag news:[EMAIL PROTECTED] > Hello, > > I'am searching for a python solution for display a tachometer diagram. > I prefer a solution for wxPython. > The plot libraries I've found do not implement this diagram type. > Any hints welcome! > > Thanks > Andreas > -- http://mail.python.org/mailman/listinfo/python-list
nanothreads: Want to use them from within wxPython app
I've def'ed a handler for EVT_IDLE in the app's main frame. There I'd like to call the nanothreads' __iter__ method, somehow. When I copy the __iter__ method into a, say, runOnce() method and call the next() method of the generator returned by runOnce(), it works. But I can't get at the __iter__ method, which is already there and therefore should be used instead of messing up nanothreads with changes of mine. Any hint welcome Kind regards Franz GEIGER -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter Puzzler
Le 07 Jan 2005 05:28:31 EST, Tim Daneliuk a écrit :
> I am trying to initialize a menu in the following manner:
>
> for entry in [("Up", KeyUpDir), ("Back", KeyBackDir), ("Home", KeyHomeDir),
> ("Startdir", KeyStartDir), ("Root",
> KeyRootDir)]:
>
> func = entry[1]
> UI.ShortBtn.menu.add_command(label=entry[0], command=lambda: func(None))
The problem is that you *call* the callback : the command parameter is
bound to the result of func(None)
>
> However, at runtime, each of the menu options binds to the *last* function
> named in the list (KeyStartDir).
>
> Explicitly loading each entry on its own line works fine:
>
> UIcommand=lambda:KeyWHATEVERDir(None)
>
> Any ideas why the first form does not fly?
I would simplify the code like ;
add_cmd = UI.ShortBtn.menu.add_command
for label, func in (("Up", KeyUpDir), ):
add_cmd(label=label, command=func)
And have
def KeyUpDir(arg=None):
# whatever
>
>
> TIA,
>
> Tim Daneliuk [EMAIL PROTECTED]
> PGP Key: http://www.tundraware.com/PGP/
--
http://mail.python.org/mailman/listinfo/python-list
Re: java 5 could like python?
"vegetax" <[EMAIL PROTECTED]> schrieb im Newsbeitrag news:[EMAIL PROTECTED] > I was a java developer one year ago ,before i moved to python i realy liked > it at the beggining, but i got very disapointed lately since my > previus two python proyects where relatively big,and python didnt feel > well suited for the task. > > The reasons are mainly due to the standard library,the language > performance was aceptable, but the library, in my opinion has several grave > issues: > > -No naming convention. The speech of "it fits in my head" is no longer valid > when i use a lot of functionality,modules,classes in a large proyect. > > For example if i remember a function i want ie:get attribute, i dont > remember if the module implementer coded it as > getAttribute,GetAttribute,get_attribute, then i have to go and check the > doc, every time,which is a waste of time. Too many getters indicate bad design. But, ok, that's not the point here. I ask myself all the time, how people can dev software in *any* language w/o an IDE offering Intellisense (besides a decent clas browser, of course). You simply type "myObj.get" and the IDE looks the proper names up for you. Then you choose the right one and you are done with. WingIDE is such an IDE, and Kommodo too, I think. HTH Franz GEIGER -- http://mail.python.org/mailman/listinfo/python-list
Re: import problems *newbie*
Le 13 Jan 2005 21:58:36 -0800, mike kreiner a écrit : > I am having trouble importing a module I created. I'm running PythonWin > on Windows XP if that helps. I saved my module in a folder called > my_scripts in the site-packages directory. I edited the python path to > include the my_scripts folder (it now reads > C:\Python23\Lib;C:\Python23\DLLs;C:\Python23\Lib\lib-tk;C:\Python23\Lib\site-packages\my_scripts). Not a very godd idea to mess with the python path > When I try to import the module, I get this error: > from PolyDraw import * > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named PolyDraw > > When I select Browse PythonPath from the tools menu, I'm able to locate > my module, PolyDraw.py. > > The problem goes away if I open PolyDraw.py from PythonWin, which I'm > assuming is because opening the module makes my_scripts the current > working directory. This is just a quick workaround, but I'd like to > know how to fix the problem. Thanks. A quick fix is to promote your my_scripts folder to be a python package, by creating a python module (file) named __init__.py right in the package directory. The content of __init__.py can be for instance #!/usr/bin/env python # -*- coding: Latin-1 -*- """ my_scripts package containing miscellaneous modules PolyDraw """ __author__ = 'mike kreiner' To import from this package the syntax is from my_scripts import PolyDraw > > -Mike > -- http://mail.python.org/mailman/listinfo/python-list
Re: a sequence question
Le Fri, 28 Jan 2005 13:59:45 GMT, Chris Wright a écrit : > Hi, > > 1) I want to iterate over a list "N at a time" > > > Is there a nifty way to do with with list comprehensions, > or do I just have to loop over the list ? > > cheers and thanks seq = xrange(1, 9) # an iterable [1, 2, ... 8] N = 2 it = (iter(seq,)*N # a tuple containing N times the *same* iterator on seq print zip(*it) # the list you are after from itertools import izip help(izip) it = (iter(seq),)*2 for tup in izip(*it): print tup > > chris wright -- http://mail.python.org/mailman/listinfo/python-list
Re: Dynamic class methods misunderstanding
Le Fri, 28 Jan 2005 10:20:30 -0500, Bill Mill a écrit : > Hello all, > > I have a misunderstanding about dynamic class methods. I don't expect > this behavior: > > In [2]: class test: >...: def __init__(self, method): >...: self.method = method >...: self.method() >...: > > In [3]: def m(self): print self >...: > > In [4]: test(m) > --- > exceptions.TypeError Traceback (most recent > call > last) > > /cygdrive/c/Documents and Settings/Wmill/ > > /cygdrive/c/Documents and Settings/Wmill/ in __init__(self, method) > > TypeError: m() takes exactly 1 argument (0 given) > - > > Why doesn't m get the implicit self parameter in the self.method() > call? How would I make it a proper member of the class, so that a > self.method() call would work with the above "m" function? The "def m(self):" was not properly indented. So here, "m" is a module level function, not a method of your class. > > Peace > Bill Mill > bill.mill at gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: boa constructor & mysql
Look at the wx demos. Another idea: Use a virtual list control. In the OnGetItemText() you could do the appropriate SQL query. Workedpretty well for me. HTH Franz GEIGER "Michele" <[EMAIL PROTECTED]> schrieb im Newsbeitrag news:[EMAIL PROTECTED] > I've search a lot to found how visualize a mysql table in a gui (wxpython). > I think to use wxgrid to visualize this table...but I don't know how... > > Anyone help me? > > Thanks a lot for the patience. > > Michele > -- http://mail.python.org/mailman/listinfo/python-list
Crude statistics on the standard library
I have written a script to find the modules which export the largest
number of names. The gc.getreferrers(*objs) function gives also an idea
of the dependencies between the modules.
The code (statsmod.py) :
#!/usr/bin/env python
# -*- coding: latin-1 -*-
"""
statsmod.py module rudimentaire de statistiques des noms exportés
par les modules de la bibliothèque standard
"""
import sys
import gc
from glob import glob
import os, os.path
from os.path import basename
def browse_stdlib():
"""browse the standard library
returns list of names of modules
"""
pyver = 'python%s' % (sys.version[:3],)
pyglob = os.path.join(sys.prefix, 'lib', pyver, '*.py')
# lpys = glob(pyglob)
if os.path.exists(os.path.join(sys.prefix, 'Lib', 'os.pyc')):
pyglob = os.path.join(sys.prefix, 'Lib', '*.py')
lpys = map(basename, glob(pyglob))
names = [ name[:-3] for name in lpys ]
# remove some obsolete modules ('this' + DeprecationWarning)
for dontparse in ("this", "tzparse", 'FCNTL', 'posixfile', 'pre', 'regsub',
'statcache', 'TERMIOS', 'xmllib'):
try:
names.remove(dontparse)
except ValueError:
continue
return names
def exports(names, with_modules=False):
"""imports all the modules in names
returns a 2-tuple :
- list of tuples : NumberOfExternalNames len(dir(module)) nodname
- list of modules (if with_modules is true)
"""
res = []
add = res.append
_all = []
modules = []
# this simple minded method (__import__) doesn't include sys ?
for name in names:
print name, " ",
try:
module = __import__(name, globals(), locals(), _all)
ldir = len(dir(module))
if hasattr(module, '__all__'):
nexports = len(module.__all__)
else:
nexports = ldir
add((nexports, ldir, name))
if with_modules:
modules.append(module)
# del sys.modules[name]
except ImportError, msg:
print "cannot import module", name, msg
return res, modules
def pm_histo(values, nbins=20):
"""a poor man histogram
Return a list of nbins tuples (left, right) such that
the union of the consecutive ranges(left, right) is range(len(values)+1)
values[k]
"""
vlo, vhi = values[0], values[-1]+1
nbins = min(nbins, vhi-vlo)
deltax = int((vhi - vlo)/nbins)
assert deltax > 0
ranges = []
add = ranges.append
left = 0 # left index first bin
val = vlo + deltax
while val < vhi:
for right in range(left, len(values)):
if values[right] > val:
break
add((left, right))
left = right
val = val + deltax
return ranges
def basic_stat(seq):
"""basic statistics on the values in seq
Returns NumberOfItems, MeanValue, StandardDeviation, variance
"""
s0, s1, s2 = 0, 0, 0
for indx, item in enumerate(seq):
s0 = s0 + 1 # seq may be an iterable without len
Xi = float(item)
if not indx:
Xmin = Xi
s1 = s1 + Xi
s2 = s2 + Xi*Xi
# s0 = len(seq) # sum of 0 order
Xm = s1/s0 # mean value
Xmax = Xi
median = (Xmin + Xmax)*0.5
variance = (s2 - s0*Xm*Xm)/s0 # ecart-type ** 2
import math
stddev = math.sqrt(variance) # ecart-type
return s0, Xmin, Xmax, median, Xm, stddev # , variance
if __name__ == '__main__':
names = ['cStringIO', 'sys', 'gc' ]
names.extend(browse_stdlib())
freqs, modules = exports(names, True)
print# exports() prints without new line
print "%d imported modules and %d in sys.modules" % (
len(freqs), len(sys.modules))
print "number of unreachable objects", gc.collect()
simples = []
while modules:
module = modules.pop()
# print module.__name__, sys.getrefcount(module)
items = gc.get_referrers(module)
litems = len(items)
if litems <= 2:
simples.append(module.__name__)
del sys.modules[module.__name__], module, items
else:
print "referrers of %s" % (module.__name__,)
for item in items[2:]:
name = item.get('__file__', 'unknown')
if name.endswith('__init__.pyc'):
pslash = name.rfind(os.sep)
pslash = name[:pslash].rfind(os.sep)
name = name[pslash+1:][:-4] # strip .pyc
elif name.endswith('__init__.py'):
pslash = name.rfind(os.sep)
pslash = name[:pslash].rfind(os.sep)
name = name[pslash+1:][:-3] # strip .py
elif name.endswith('.pyc'):
pslash = name.rfind(os.sep)
name = name[pslash+1:][:-4] # strip .pyc
elif name.endswith('.py'):
pslash = name.rfind(os.sep)
name = name[pslash
Re: Python's idiom for function overloads
> > Since Python doesn't have static typing, how is the same result as
traditional
> > function overloads results in acheived?
The more you program in Python, the less you are missing it.
As Philippe already said, use objects that support the protocol or decide
what to do with it after having checked its type. I do that, if I have to,
like so:
def doIt(arg):
if type(arg) == type([]):
map(doIt, arg)
else:
# Do it on a scalar type
# ...
return result
HTH
Franz GEIGER
"Philippe Fremy" <[EMAIL PROTECTED]> schrieb im Newsbeitrag
news:[EMAIL PROTECTED]
> Hi Frans,
>
> > Since Python doesn't have static typing, how is the same result as
traditional
> > function overloads results in acheived?
>
> With dynamic typing obviously. :-)
>
> You can not reproduce the C++ overload idiom but you can get something
> close with manual type testing.
>
> > To in a
> > function do an if statement with the type() function?
>
> I am not aware of any other method.
>
> def a( arg1 ):
> if type(arg1) == types.IntType: return aWithInt(arg1)
> if type(arg1) == types.ListType: return aWithList(arg1)
> ...
>
> As you see, it is a bit tedious sometimes.
>
> If you want to juggle with completely different signatures, you have to
> play with variable argument lists. But I have found in my experience
> that the best way to get close to the C++ idiom, while improving
> readbility, is by using kwparams:
>
> def a(**kwparams):
> if kwparams.has_key('argInt'): aWithInt(kwparams['argInt'])
> if kwparams.has_key('argString'): aWithString(kwparams['argString'])
>
> The parsing code is the same, but the intent of the user is better
> expressed and you can catch misuse in a better fashion:
> if kwparams.has_key('argInt') and kwparams.has_key('argString'):
> print "You stupid moron, a can be used only with string or int but not
> both at the same time!"
> sys.exit(1)
>
> The example speaks better in a real case. Imagine a processPixmap
function:
> processPixmap( pixmap=QPixmap(...) )
> processPixmap( filename='my_pixmap.png' )
> processPixmap( buffer=my_pixmap_string_content )
>
> It works actually even better with multiple arguments.
>
> regards,
>
> Philippe
--
http://mail.python.org/mailman/listinfo/python-list
Re: Python's idiom for function overloads
Le Tue, 01 Feb 2005 12:10:47 +0100, Philippe Fremy a écrit : > >> Frequently, in Python, code which checks for types, rather than >> checking for features, ends up being excessively restrictive and >> insufficiently general. > snip > > Enforcing types also brings the benefit that the program is more > deterministic. In my experience, there is a lot more benefits to have an > object whose type is clearly identified than to have function that > accepts generic objects. If you insist to always have only clearly identified types of variables you will use the Hungarian notation : bool bIsDir = blah const char *lpszMessage = "It's a directory"; > > I would go as far as saying that variables should have immutable types. > It is more restricting that what python provides currently, but leads to > clearer programming practice: the intent of the developer shows up in > the type he uses. clearer programming practice which goes with unreadable code ? > > > While Python's dynamic typing liberty is enjoyable, I think it harms > when you start to work on big projects. It prevents you to put many > safety assumptions which might bite you back. Python is strongly typed (at run-time). You can get a traceback sure but it is rather difficult to get unreliable results. > > regards, > > Philippe -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie: Syntax error
Le Fri, 4 Feb 2005 12:49:51 -0600, Chad Everett a écrit :
> Hi Everyone,
>
> I am new to Python and programming in general. I bought the book "Python
> Programming for the Absolute Beginner" by michael Dawson.
>
> I am trying to make a coin flip program and keep geting a Synax Error
> "invalid syntax".
>
> If anyone has a moment could you please look at it and tell me what I am
> doing wrong.
>
> thanks for your time and patience.
>
> Chad
>
> # Coin Flip Program
> # This program flips a coin 100 times and tells the number of heads and
> tails.
> # Chad Everett 2/3/2005
>
>
> print "\t\tCoin Flip Game*\n"
> import random
>
> # heads = 1
> # tails = 2
>
> tries = random.randrange(2) + 1
> count = 1
>
> while count != 100:
> if tries == 1:
> heads = 1
> count += 1
>
> else tries == 2: # I AM GETTING THE SYNTAX ERROR HERE
elif tries == 2: # should be better
> tails = 1
> count += 1
>
> print "heads: " + heads
> print "tails: " + tails
>
> raw_input("Press enter to quit")
>
>
--
http://mail.python.org/mailman/listinfo/python-list
Re: how to use more than 1 __init__ constructor in a class ?
Le 22 Jun 2005 11:44:09 -0700, [EMAIL PROTECTED] a écrit :
> You also could use a list to represent your data, then you get more
> dimensions supported, e.g:
> import math
> class Point:
> def __init__(self, *args):
> self.points = list(args)
>
> def dist(x, y):
> if len(x.points) != len(y.points):
> raise RuntimeError('dimensions not the same')
> d = 0
> for i in range(len(x.points)):
> d += (x.points[i] - y.points[i])**2
> return math.sqrt(d)
>
My rewrite (same idea) :-)
class Point(object):
def __init__(self, *args):
self.coords = list(args) # or even args ?
def dist(self, other):
d2 = sum([ (c1-c2)*(c1-c2) for c1, c2 in zip(self.coords,
other.coords)])
return math.sqrt(d2)
--
http://mail.python.org/mailman/listinfo/python-list
Re: Package organization
Le Wed, 22 Jun 2005 20:42:24 +0200, Thomas Lotze a écrit : > Hi, > > I've two questions concerning organizing and naming things when writing > a Python package. > > Assume I have a package called PDF. Should the classes then be called > simply File and Objects, as it is clear what they do as they are > imported from PDF? Or should they be called PDFFile and PDFObjects, as > the names would be too undescriptive otherwise? As you whish :-) if in the package ie in the __init__.py (not the best idea) from PDF import File as PDFFile # always possible if File is defined in a module Objects from PDF.Objects import File # as PDFFile is always possible. Have you installed the reportlab package ? It is full of from ... import .. and it generates PDF. -- http://mail.python.org/mailman/listinfo/python-list
Re: os.system(cmd) isn't working
Le Thu, 23 Jun 2005 01:19:11 -0500, Paul Watson a écrit : > "Gregory Piñero" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] > Hi guys, > > I'm trying to run this statement: > > os.system(r'"C:\Program Files\Mozilla Firefox\firefox.exe"' + ' > "www.blendedtechnologies.com"') > > The goal is to have firefox open to that website. I suggest to use the subprocess module. You don't have insert " around a path with embedded spaces and you can give the exact executable pathname, set the directory for the child process, etc import os import os.path import subprocess path_exe = r'C:\Program Files\Mozilla Firefox\firefox.exe' assert os.path.exists(path_exe) url = "http://www.blendedtechnologies.com"; child = subprocess.Popen( (path_exe, url), executable = path_exe) rc = child.wait() > I'm using Python 2.3 on Windows XP pro service pack 2. I think that subprocess is a new Python2.4 module, but you should be able to find a 2.3 version (perhaps effbot.org) > > I'd greatly appriciate any help. -- http://mail.python.org/mailman/listinfo/python-list
Re: turn text lines into a list
[En-tête "Followup-To:" positionné à comp.lang.python.] Le Mon, 27 Jun 2005 14:27:28 -, Grant Edwards a écrit : > On 2005-06-27, Xah Lee <[EMAIL PROTECTED]> wrote: >> i have a large number of lines i want to turn into a list. >> In perl, i can do >> >> @corenames=qw( >> rb_basic_islamic >> sq1_pentagonTile >> sq_arc501Tile >> sq_arc503Tile >> ); >> >> use Data::Dumper; >> print Dumper([EMAIL PROTECTED]); >> >> -- >> is there some shortcut to turn lines into list in Python? > > corenames = [ "rb_basic_islamic", > "sq1_pentagonTile", > "sq_arc501Tile", > "sq_arc503Tile"] > Another way : (less typing of quotes) all_names = """ rb_basic_islamic sq1_pentagonTile sq_arc501Tile sq_arc503Tile """ corenames = all_names.split() Regards. -- http://mail.python.org/mailman/listinfo/python-list
Re: map vs. list-comprehension
Le Wed, 29 Jun 2005 09:46:15 + (UTC), Mandus a écrit : > Hi there, > > inspired by a recent thread where the end of reduce/map/lambda in Python was > discussed, I looked over some of my maps, and tried to convert them to > list-comprehensions. > > This one I am not sure how to conver: > > Given three tuples of length n, b,i and d, I now do: > > map(lambda bb,ii,dd: bb+ii*dd,b,i,d) > > which gives a list of length n. res = [ bb+ii*dd for bb,ii,dd in zip(b,i,d) ] Hoping that zip will not be deprecated. -- http://mail.python.org/mailman/listinfo/python-list
Re:
Le Fri, 01 Jul 2005 20:47:45 +0200, Andreas Kostyrka a écrit : about C++ templates > And they are a kind of "compile-time" late binding. You get the worst > from both worlds. All the complication of a static typing system, and at > the same time no safety. +1 QOTW -- http://mail.python.org/mailman/listinfo/python-list
Re: [PythonWin] how to stop execution in interactive window?
Right-click on the Pythonwin icon in the tray and select "Break into running code". HTH Franz GEIGER <[EMAIL PROTECTED]> schrieb im Newsbeitrag news:[EMAIL PROTECTED] > Hi All, > (sorry for my bad english) > I wrote a __tiny__ and __stupid__ recursive script directly into > pythonwin > interactive window with a time.sleep(1) and a print before each > recursion... > I should have taken a closer look at the ending condition (never > satisfied!), > anyway I was quite confident that a control-C would have stopped the > intepreter as it is (incidentally?) when this break sequence is entered > during a screen-i/o of the python interpreter in a CMD prompt... > Instead I discovered my pythonwin session no more responding even > though the output shows that it was still working correctly... and my > other > open files in pythonwin still needing to be saved - my salvation was > that > while I was searching a solution with google, after 984 nested call > ~ more than a quarter later, the recursion stack was full and > an exception was raised! ;-P). > So my question is: is there a keystroke combination to stop the > interpreter > in pythonwin interactive window? Or even better > Is there a "pythonwin interactive window" keystrokes list? > (btw: I remember an old post explaining the keystroke to > reset interactive window memory without being forced to > close and open pythonwin - very usefull but I could not find it > anymore...) > TIA! > bye, >PiErre > -- http://mail.python.org/mailman/listinfo/python-list
Re: J-Integra for COM (Java COM interoperability)
Le 18 Jul 2005 13:39:41 -0700, [EMAIL PROTECTED] a écrit : snip > > J-Integra for COM Features: snip > > For a free evaluation, visit our website at > http://j-integra.intrinsyc.com/ > > Regards, > > Shane Sauer Q: What are the Vikings singing in the background ? A: Spam, spam, spam ! -- http://mail.python.org/mailman/listinfo/python-list
Creating a graphical interface on top of SSH. How?
I want to write a client app in Python using wxWindows that connects to my FreeBSD server via SSH (using my machine account credentials) and runs a python or shell script when requested (by clicking a button for instance). Can someone give me some advice on how to create a "graphical shell" per se? -- http://mail.python.org/mailman/listinfo/python-list
Twisted Conch for emulating a terminal?
I'm trying to figure out how to emulate a terminal with twisted conch (I want to be able to send the client information with the 'write' command in freebsd). I have played with ssshsimpleclient.py on the twistedmatrix site and it works but I need to keep the connection open, not just execute a single command and exit. Can someone point me to some sample code or provide some advice? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Pointers and ctypes
Le 29 Aug 2005 06:19:17 -0700, [EMAIL PROTECTED] a écrit : > Hello, > i've got a problem with pointers in the following function which i want > to use: > > I16 __stdcall DO_ReadPort (U16 CardNumber, U16 Port, U32 *Value) > > The function is supposed to read out the status of a digital port of > analog digital interface card. > I got this function from Dask.h which came with the card. The relevant > lines concerning this function are the following: > > typedef short I16; > typedef unsigned short U16; > typedef unsigned long U32; > > I16 __stdcall DO_ReadPort (U16 CardNumber, U16 Port, U32 *Value) > > I tried to implement this function into python: > # I16 __stdcall DO_ReadPort (U16 CardNumber, U16 Port, U32 *Value); > ReadOPort = dask.DO_ReadPort > ReadOPort.argtypes = [c_ushort, c_ushort, c_ulong] > ReadOPort.restype = c_short > > I can't handle the pointer "Value" which should be an unsigned long > pointer. I'd be very happy, if u could give me a hint how to implement > this pointer into python. You can use the ctypes.byref() function (as it is in an argulent list): ReadOPort.argtypes = (c_ushort, c_ushort, ctypes.POINTER(c_ulong) ) ReadOPort.restype = c_short status = c_ulong() # status value to be read number = c_ushort(1) # CardNumber = 1 port = c_ushort(11) rc = ReadOPort(number, port, ctypes.byref(status)) print rc, ststus > > Thanks a lot > > Carlo and Pierre > -- http://mail.python.org/mailman/listinfo/python-list
Re: changing __call__ on demand
Le Sun, 13 Feb 2005 13:19:03 -0500, Hans Nowak a écrit :
> Stefan Behnel wrote:
>> Hi!
>>
>> This somewhat puzzles me:
>>
>> Python 2.4 (#1, Feb 3 2005, 16:47:05)
>> [GCC 3.3.4 (pre 3.3.5 20040809)] on linux2
>> Type "help", "copyright", "credits" or "license" for more information.
>>
>> .>>> class test(object):
>> ... def __init__(self):
>> ... self.__call__ = self.__call1 # self.__call__ is bound
>> ... def __call1(self):
>> ... print 1
>> ... def __call__(self): # self.__call__ is rebound
>> ... print 2
>> ...
>> .>>> t = test()
>> .>>> t()
>> 2
2 because the last defined __call__ wins. Try dir(t)
>>
>> If I take out the __call__ method completely and only set it in
>> __init__, I get a TypeError saying that test is not callable.
This seems logical.
>
> Note that it works just fine if you don't use a new-style class:
>
> >>> class Test:
> ... def __init__(self):
> ... self.__call__ = self.foobar
> ... def foobar(self, *args, **kwargs):
> ... print "Called with:", args, kwargs
> ...
> >>> t = Test()
> >>> t()
> Called with: () {}
> >>> t(3, 4)
> Called with: (3, 4) {}
> >>> t(42, x=0)
> Called with: (42,) {'x': 0}
Are you sure that if you add a __call__() method, it will still work
fine ?
Regards
>
--
http://mail.python.org/mailman/listinfo/python-list
Re: starting windows program from python based on file extension ?
Le 3 Mar 2005 02:53:51 -0800, [EMAIL PROTECTED] a écrit :
> Hi everybody,
>
> I used python to build a HTML file and now I would like to
> automatically start my browser to display this file. I guess I could
> use os.system(), but then I had to specify a specific path to the
> browser.
>
> I wonder if it is possible to tell windows to open "myFile.html" using
> the program that is registered to open html files (similar to double
> clicking on the file).
>
> Any idea how to do that from python ??
import os
os.startfile("myFile.html")
# on windows only
>
> Many thanks,
>
>Alex
>
--
http://mail.python.org/mailman/listinfo/python-list
[Job - Part Time - Local] Seeking Python Coder in South Alabama area.
Startup company in Fairhope, AL is seeking a strong python programmer in the Mobile, AL or Eastern Shore, AL area to assist in the development of legal practice management systems. Candidate must reside in the area. Position will be initially part time. Must be proficient with Freebsd/Postgresql/Python/WxGlade(WxPython). Must have real world experience and be ready to contribute effectively. Please send resume to HikenbootsAtyahoo.com -- http://mail.python.org/mailman/listinfo/python-list
Re: autoexecution in Windows
Le Mon, 07 Mar 2005 13:25:35 -0700, Earl Eiland a écrit : > How does one make a Python program auto-execute in Windows? > > Earl > write a virus ? :-) What do you mean by « auto-execute » ? Regards -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a short-circuiting dictionary "get" method?
Le Wed, 09 Mar 2005 09:45:41 -0800, Dave Opstad a écrit :
> In this snippet:
>
> d = {'x': 1}
> value = d.get('x', bigscaryfunction())
>
> the bigscaryfunction is always called, even though 'x' is a valid key.
> Is there a "short-circuit" version of get that doesn't evaluate the
> second argument if the first is a valid key? For now I'll code around
> it, but this behavior surprised me a bit...
def scary():
print "scary called"
return 22
d = dict(x=1)
d.get('x', lambda *a : scary())
# print 1
d.get('z', (lambda *a : scary())())
scary called
22
First (wrong) version :
d.get('z', lambda *a : scary())
at 0x40598e9c>
>
> Dave
--
http://mail.python.org/mailman/listinfo/python-list
Re: Iterate using tuple as index
Le Thu, 10 Mar 2005 13:12:31 -0800, James Stroud a écrit : > Hello, > > Its not obvious to me how to do this. I would like to iterate using a tuple > as > an index. Say I have two equivalently sized arrays, what I do now seems > inelegant: > > for index, list1_item in enumerate(firstlist): > do_something(list1_item, secondlist[index]) > > I would like something more like this: > > for list1_item, list2_item in (some_kind_of_expression): > do_something(list1_item, list2_item) > > Practically, I'm not so sure B is better than A, but the second would be a > little more aesthetic, to me, at least. > > Any thoughts on what "some_kind_of_expression" would be? It is called "zip" for list1_item, list2_item in zip(firstlist, secondlist): try: help(zip) > > James > -- http://mail.python.org/mailman/listinfo/python-list
Re: why this error?
Le Wed, 16 Mar 2005 17:53:57 -0500, spencer a écrit :
> Hi,
> I'm not sure why I can't concatenate dirname() with basename().
>
> Traceback (most recent call last):
> File "showDir.py", line 50, in ?
> print 'somthing new...', os.path.join(os.path.dirname(os.getcwd)) +
> os.path.basename(os.getcwd())
The problem is here : os.path.join() take at least one parameter, but it
is silly to use it with only one. Replace the « + » by a comma.
> File "/usr/lib/python2.3/posixpath.py", line 119, in dirname
> return split(p)[0]
> File "/usr/lib/python2.3/posixpath.py", line 77, in split
> i = p.rfind('/') + 1
> AttributeError: 'builtin_function_or_method' object has no attribute
> 'rfind'
> Thanks,
> Wayne
>
>
--
http://mail.python.org/mailman/listinfo/python-list
Re: code for Computer Language Shootout
Le Tue, 15 Mar 2005 23:21:02 -0800, Michael Spencer a écrit :
> Jacob Lee wrote:
>> On Tue, 15 Mar 2005 21:38:48 -0800, Michael Spencer wrote:
>>
>> Good call.
>>
>>
>
> How about this then:
>
> basetable = string.maketrans('ACBDGHKMNSRUTWVYacbdghkmnsrutwvy',
> 'TGVHCDMKNSYAAWBRTGVHCDMKNSYAAWBR')
>
> from collections import deque
> from itertools import islice
>
> def output(seq, linelength = 60):
> if seq:
> iterseq = iter(seq)
> while iterseq:
> print "".join(islice(iterseq,linelength))
I suppose you mean :
print "".join( str(item) for item in islice(iterseq, linelength) )
# using python 2.4 genexp
>
> def revcomp(input = sys.stdin):
> seqlines = deque()
> for line in input:
> if line[0] in ">;":
> output(seqlines)
> print line,
> seqlines.clear()
> else:
> seqlines.extendleft(line.translate(basetable, "\n\r"))
> output(seqlines)
>
>
> It would be nice to inline the output function, and re-arrange the iteration
> so
> that EOF triggers the same suite as line[0] in ">;"
>
> Michael
>
--
http://mail.python.org/mailman/listinfo/python-list
minidom get Element value
Hi all,
Today's embarassingly simple question goes like this.
I have a file, testdoc.xml, to parse.
Inside the file is an element
Yo, Ho, Ho
So, starting with
[code]
from xml.dom import minidom
xmldoc = minidom.parse('home\me\testdoc.xml')
[/code]
therefrain = getTagsByName('refrain')
print therefrain.toxml()
does print the whole Element
What code do I need to merely print the *value* of the element, i.e.,
I would like to see
Yo, Ho, Ho
printed out.
I can get Attribute values, the whole Element with tags, etc., and
could do a substring search on the Element, but surely something
exists within minidom to do this.
Thanks.
Scott
--
http://mail.python.org/mailman/listinfo/python-list
Re: metaclass error
Le 17 Mar 2005 12:27:07 -0800, [EMAIL PROTECTED] a écrit : > dear readers, > > i have a very simple package organized as follows: > > !-! > bgp/ > __init__.py > managers/ > __init__.py > ManagerInterface.py > TestManager.py > !-! > > and here's ManagerInterface.py and TestManager.py: > > !-! > # ManagerInterface.py > class ManagerInterface(object): > def __init__(self): pass > def process(self, recset, operation): > print 'In ManagerInterface.process()...' > > # TestManager.py > import ManagerInterface # ManagerInterface is a module not a class ! # try from ManagerInterface import ManagerInterface > class TestManager(ManagerInterface): # you can also define __init__ method with a super call > def process(self, recset, operation): > print 'In TestManager.process()...' > super(TestManager,self).process(recset,operation) > !---! > > > thanks! > aaron > -- http://mail.python.org/mailman/listinfo/python-list
Re: [question] Event Handeling Between Two wxPanles in A wxNotebook
That's the Visual Basic way to do it. I prefer it this way: Controls work on models. If a control has to store a value it does so by calling MyDataPool.storeMyValue(self.GetValue()). When the NotebookPage is changed, the new page tells all controls to update themeselves: self.SetValue(str(MyDataPool.myValue())). Recently I even prefer controls doing that by theirselves. They all have a timer, to periodically check whether or not they have to update themselves. But such a design is necessary only if the controls display current values, coming e.g. from an OPC server. HTH Franz GEIGER <[EMAIL PROTECTED]> schrieb im Newsbeitrag news:[EMAIL PROTECTED] > Ok i have a wxFrame with a wxNotebook that has two wxPanels, lets call > them panel_1 and panel_2 > > i have wxTextCtrl in panel_1 (call it panel_1_ctrl) that i want the > user to be able to fill up. I then want the user to be able to click a > button (i.e. create an EVT) and have Value() of panel_1_ctrl be sent a > wxTextCtrl in panel_2. > > So can i do this directly, i.e. is there a way to tell panel_2 that > something has happended in panel_1 and to send panel_2 that data? Or do > i have to go through the wxFrame i.e (panel_1 tells wxFrame that EVT > happened, wxFrame then tells panel_2). > > > in short panel_1_ctrl sends Value() to panel_2_ctrl. > > > > Thanks for any help that you can give me. > -- http://mail.python.org/mailman/listinfo/python-list
PIL for Windows for Python 2.4
As there is no build for Python 2.4, I attempted to put it together
from source. Running
setup.py build
gives this error:
Traceback (most recent call last):
File "C:\tmp\PIL\Imaging-1.1.4\setup.py", line 60, in ?
for line in open(os.path.join("libImaging",
"ImConfig.h")).readlines():
IOError: [Errno 2] No such file or directory: 'libImaging\\ImConfig.h'
Appears to be putting in two backslashes.
Can anyone give me a clue to fix this?
Scott
--
http://mail.python.org/mailman/listinfo/python-list
Re: PIL for Windows for Python 2.4
Peter Hansen <[EMAIL PROTECTED]> wrote in news:[EMAIL PROTECTED]: > Actually, you're just seeing the repr() of the filename. > You really are missing that file in the place where it's > looking. > > -Peter > Give the man a beer! Thanks. I had ImConfig.h.win so I changed setup.py to that and off we go. Scott -- http://mail.python.org/mailman/listinfo/python-list
Re: PIL for Windows for Python 2.4
"Fuzzyman" <[EMAIL PROTECTED]> wrote in news:[EMAIL PROTECTED]: > So you've built PIL for windows, Python 2.4 ? > > Any chance of sharing it ? What compiler have you configured > distutils to use ? I'm very sorry I spoke too soon. After making the initial change, the setup.py took off on a run. But it soon quit, informing me that I needed the Visual Studio 7 tools. So, I have no PIL either. -- http://mail.python.org/mailman/listinfo/python-list
[Parsing] How do I process loops with PLY?
I'm rather new to high level parsing with lex/yacc (and realy impressed so far). I'd like to parse *and execute* files like this: A=12 B=23 G X=A Y=B Z=34 # Move to X, Y, Z G Z=0 etc. No problems so far. But when loops enter the game, things seem to become more difficult: A=12 B=23 C=45 D=56 DX=0 FOR C # Exec the following lines C times G X=A+DX Y=B Z=34 # Move to X, Y, Z # more statements... DX=DX+67 NEXT How can I tell PLY to go back to the beginning of the FOR-loop's body to execute it C-1 more times? A syntax checker would not need to do that, but an interpreter (which actually I am building) has to. Any hints are welcome. Kind regards Franz GEIGER -- http://mail.python.org/mailman/listinfo/python-list
Re: More elegant way to cwd?
On Mon, 27 Dec 2004 11:53:57 -0500, Peter Hansen <[EMAIL PROTECTED]> wrote:
> Kamilche wrote:
>> Is there a more elegant way to change the working directory of Python
>
> That depends on how you define "elegant", I guess.
>
>> to the directory of the currently executing script, and add a folder
>> called 'Shared' to the Python search path?
>>
>> This is what I have. It seems like it could be shorter, somehow.
>
> It could be shorter if you were willing to combine several
> function calls on the same line, but I get the impression
> you wouldn't consider that more elegant...
>
>> # Switch Python to the current directory
>> import os, sys
>> pathname, scriptname = os.path.split(sys.argv[0])
>> pathname = os.path.abspath(pathname)
>> os.chdir(pathname)
>> s = os.path.realpath('..')
>> s = os.path.join(s, 'Shared')
>> sys.path.append(s)
>>
>> Thanks for any enhancements you can suggest!
>
How about ?
import os, sys
pathname, scriptname = os.path.split(sys.argv[0])
pathname = os.path.abspath(pathname)
os.chdir(pathname) # only if you really need to cwd
parent = os.path.dirname(pathname)
parent = os.path.join(parent, 'Shared')
if parent not in sys.path:
sys.path.append(parent)
Or even :
pathname, scriptname = os.path.split(__file__)
# pathname should be an absolute path
--
http://mail.python.org/mailman/listinfo/python-list
Re: python metrics program/script sample
On Mon, 27 Dec 2004 12:09:16 -0500, Peter Hansen <[EMAIL PROTECTED]> wrote: > Philippe C. Martin wrote: >> I am looking for an eric3/linux compatible alternative to checking code >> metrics (ex: true lines of code count) > > I don't know what "eric3/linux compatible" might be, I'm not sure > what this would be an alternative _to_, and I don't know what you > mean by "true" lines of code count, but the only thing I've > noticed lately that counts lines of Python code, and I'm fairly > sure it would run fine on Linux, is pycount. Google for it... > > -Peter You can also use pylint (logilab.org) which print something like : Report == 57 statements analysed. [snip] Raw metrics --- type number % previous difference ::: code 61 64.21 61 = docstring 22 23.16 22 = comment 3 3.16 3= empty 9 9.47 9= As it is pure python it should not be difficult to adapt to your needs. (but do not feed pylint with a module with tabs, the final 'Global evaluation' will be deceitfull) Sorry for bad english, I'm not a native speaker. -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter vs wxPython
"Esmail Bonakdarian" <[EMAIL PROTECTED]> schrieb im Newsbeitrag news:[EMAIL PROTECTED] > Hi > > I have found ALL of the posts useful, thank you so much. > > Please keep them coming! I am learning a lot. > > I will probably play a bit with Tkinter and wxPython and see how > each feels, just as Peter Hansen suggested). PyQt also looks It couldn't have been said better than Peter has. I might add this: Try both *and learn both*. Despite the fact, that I do most GUI stuff with wxPython, I sometimes face situations, where I need to be able to do some Tkinter stuff (mostly by use of PMW). This could happen to you too, more likely than you might think now. As for the wxPython path: I recently prototyped a GUI-app for Windows with wxPython and then (alas) had to port it to C++. I simply could download the wxWidgets (which wxPython is built upon) and kind of simply translate the Python stuff into C++! It really helped me *a lot* having a working wx/Python app, and saved me a lot of time, of course (but no as much as I had saved, if I hadn't to port it to C++). And while I am at it: It was a big benefit for me to *not* use a GUI builder (which could be the next thing you might ask for), when I started Python programming. When I started Python programming with 1.5.2 there wasn't a descent GUI builder for wx (or at least I couldn't find one). And today, where there are a few options (wxDesigner, Boa, to be concrete), I'm really glad never having used one: Everything I do is under *my* full control, and I guess this is the only way to get the most out of wx/Python. And for sure, it's the only way knowing what you do. As Peter said, the wxPython demo is a bonanza - use it. Summary: Taking all my experience into account, I'd advise you to learn Tkinter, to learn wxPython and to not use a GUI builder (which could be not what a newbie likes to hear). HTH Franz GEIGER P.S.: Concerning PyQt: Yes, so far I only can speak for Tkinter and wxPython. But as soon as I will be on Linux (hopefully next year), I'll try PyQt. So if you would have asked me next year, I had said (phew, is that correct English?): Learn Tkinter and wxPython and/or PyQt and no GUI builder :-) > interesting, so I will take a look at that at some point down the > line aswell. > > Thanks again, this is a great resource. > > Esmail -- http://mail.python.org/mailman/listinfo/python-list
Re: GUI with sophisticated Table support
"Torsten Mohr" <[EMAIL PROTECTED]> schrieb im Newsbeitrag news:[EMAIL PROTECTED] > Hi, > > i want to write an application where i need a Table to > display some values. > > The table should display a list of objects, so to say, > a column for each attribute of the object. > I'd also like the user to be able to change the width > of each column, like in Excel. > > I'd prefer to use Tkinter, but i think it can't do all > that. Do a group-google search for *tkinter table*. That shows up quite a few hits. > > Is there a way for Tkinter to handle this? > > If not, what other GUI can do that? (wxPython?) What you are looking for is contained in the wxPython demo app. > > > Thanks for hints, > Torsten. > HTH Franz GEIGER -- http://mail.python.org/mailman/listinfo/python-list
Re: GUI with sophisticated Table support
"Torsten Mohr" <[EMAIL PROTECTED]> schrieb im Newsbeitrag news:[EMAIL PROTECTED] > Hi, > > > Do a group-google search for *tkinter table*. That shows up quite a few > > hits. > > thanks for that hint, but nearly every hit shows the Table of contents > for Tkinter", which is not what i search for. Do a *group* google serach (i.e. a search w/i groups indexed by Google, formerly known as DejaNews). Then you'll get for example http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52266 http://tkinter.unpythonic.net/wiki/SortableTable http://groups.google.at/groups?hl=de&lr=&selm=tkjjrtr89f687e%40news.supernew s.com to name a few. But even if I do a normal (i.e.. web) google search I get http://pmwcontribd.sourceforge.net/PmwContribD-r2_0_1/Table.py.html for example. HTH Franz GEIGER > > My question here is rather in detail about Tkinters Table and if it can > show resizable columns tho easily display a list of objects. > > I did not find any help searching for this with google, but i'd really > rather like to use Tkinter over wxPython, that's the background of the > question. > > Thanks for your help anyway, sorry if my question was unclear. > > > Best regards, > Torsten. > -- http://mail.python.org/mailman/listinfo/python-list
Re: Why tuples use parentheses ()'s instead of something else like <>'s?
On Thu, 30 Dec 2004 15:58:07 GMT, Roel Schroeven wrote: > Rocco Moretti wrote: >> So to summarize: >> >> Commas define tuples, except when they don't, and parentheses are only >> required when they are necessary. >> >> I hope that clears up any confusion. > > You have my vote for QOTW. > +1 :-) -- Un sens interdit ne l'est formellement et réellement que s'il est, non moins formellement et non moins réellement, unique en sens inverse. (Pierre Dac) -- http://mail.python.org/mailman/listinfo/python-list
Re: Event Handeling Between Two wxPanles in A wxNotebook
My DataPool then is a singleton, well, actually, a Borg. See Alex Martelli's recipe for that. If you use new style classes, then you have to look for "Singleton" in the cookbook. HTH Franz GEIGER "MyHaz" <[EMAIL PROTECTED]> schrieb im Newsbeitrag news:[EMAIL PROTECTED] > so you run data pool as like a sruct that contains all your global > objects? That sounds like an iteresting way of doing things. i try to > stay away from gloabs as much as possible but this might be a good time > to queue up that particular tool > > thanks for your reply > -- http://mail.python.org/mailman/listinfo/python-list
Re: Pattern matching from a text document
Le 24 Mar 2005 06:16:12 -0800, Ben a écrit :
>
> Below is a few sample lines. There is the name followed by the class
> (not important) followed by 5 digits each of which can range 1-9 and
> each detail a different ability, such as fitness, attacking ability
> etc. Finally the preferred foot is stated.
>
> Freddie Ljungberg Player 02808right
> Dennis Bergkamp Player 90705either
> Thierry Henry Player 90906either
> Ashley Cole Player 17705left
filename = 'players' # to adapt
players = {} # mapping of name to abilities
fin = open(filename)
for line in fin:
firstname, lastname, type_, ability = line.split()
players[(lastname, firstname)] = Ability(ability)
fin.close()
where Ability can be e simple function which return processed the
information in the last word(string) of each line, or a class which
stores/manages such information
class Ability(object):
def __init__(self, ability):
digits = ability[:5]
self.details = map(int, list(digits)) # list of details
self.preferred_foot = ability[5:]
# and so on
>
>
> Thanks for your help
>
> ben
>
--
http://mail.python.org/mailman/listinfo/python-list
Re: Problem in designing a global directory in python
Le 29 Mar 2005 09:50:46 -0800, Tian a écrit :
> I want to create a object directory called Context in my program, which
> is based on a dict to save and retrieve values/objects by string-type
> name. I have the definition like this:
>
> utils.py
>
> global sysctx
# you are in the global scope of the utils module. This "global sysctx"
# has no meaning, replace by
sysctx = None # create a global 'sysctx' name in utils namespace
>
> class Context:
class Context(object): # why not use "new-style" classes, we are in
2005
> def __init__(self):
# I suppose that there is some __doc__ and code :-)
> def set(self, name, obj, overwrite=True):
> def get(self, name):
> def has(self, name):
>
> def init():
> global sysctx
> sysctx = Context()
>
> def getContext():
> global sysctx
> return sysctx
> -
>
> init() is called somewhere at the beginning of the program.
> In other modules, i want to use this in the following manner,
>
>from utils import *
Please do not use the from module import * form
from utils import getContext
>getContext().set(...)
You can also restrict the exported names of utils.py by adding a
__all__ = ('getContext',)
in utils.py.
>
> but SOMETIMES I met following error located in "getContext()"
> NameError: global name 'sysctx' is not defined
>
> I found that when a module is in the same directory as utils.py, when I
> can simply use "utils" for importing, there is no such problem. But
> when i was writing a module in a deeper directory than utils.py, which
> has to use the full module name for importing, such as:
>
>from myproj.utils import *
>getContext().set(...)
>
> I got this error.
>
> What should I do to correct that?
See above :-) and post a follow-up to report if the issue is solved.
>
PS sorry for bad english. I am not a native speaker.
--
http://mail.python.org/mailman/listinfo/python-list
that is it is not it (logic in Python)
I want to know if iter(iterator) returns always its argument (when argument is an iterator) So : >>> iterable = range(10) >>> it = iter(iterable) >>> that = iter(it) >>> that is it True# Good! >>> that is it is not it False # What ? >>> >>> Python = map(bool, it) >>> logic = True >>> logic in Python is not it True # That was close! >>> >>> that is it or it is not it True >>> >>> # from physics.constant import N >>> N = 6.02e+27 >>> big = 192 # cm 1.92 meter is big for me (see my name) >>> N is big False # what ? >>> -- Seriously on an April fool's day. -- http://mail.python.org/mailman/listinfo/python-list
Re: that is it is not it (logic in Python)
Le Fri, 1 Apr 2005 13:39:47 -0500, Terry Reedy a écrit : > > "F. Petitjean" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] > >>>>> iterable = range(10) >>>>> it = iter(iterable) >>>>> that = iter(it) >>>>> that is it >> True# Good! >>>>> that is it is not it > > This is equivalent to '(that is it) and (it is not it)' which is clearly > false. > >> False # What ? > > Reread the ref manual on chained comparison operators. And see the date of the post :-) that is it isn't it ? > > Terry J. Reedy > > > -- http://mail.python.org/mailman/listinfo/python-list
Re: that is it is not it (logic in Python)
Le Fri, 01 Apr 2005 17:42:30 -0500, Jeremy Bowers a écrit : > On Fri, 01 Apr 2005 22:01:25 +0000, F. Petitjean wrote: > >> Le Fri, 1 Apr 2005 13:39:47 -0500, Terry Reedy a écrit : >>> This is equivalent to '(that is it) and (it is not it)' which is clearly >>> false. >>> >>>> False # What ? >>> >>> Reread the ref manual on chained comparison operators. >> >> And see the date of the post :-) >> that is it isn't it ? > > Nope, nothing to do with it. Read the ref manual on chained comparision > operators. > > http://www.python.org/doc/2.4/ref/comparisons.html#l2h-430 > > For proof, run the given code in the original post. It's not faked in the > slightest, and the manual holds the key to understanding. *I* wrote the original post. and am pretty sure it is not faked. And I run it before posting to be sure not to say anything wrong. it is a kind of relief to learn that computers in 2005 (even Python powered) are humor-impaired and follow the « ref manual » every time even on first April. >>> There = True >>> Python = map(bool, range(5)) >>> logic = True >>> There is logic in Python True # naturally -- http://mail.python.org/mailman/listinfo/python-list
Re: check interpreter version before running script
Le Tue, 05 Apr 2005 08:57:12 -0400, rbt a écrit : > Is there a recommended or 'Best Practices' way of checking the version > of python before running scripts? I have scripts that use the os.walk() > feature (introduced in 2.3) and users running 2.2 who get errors. > Instead of telling them, 'Upgrade you Python Install, I'd like to use > sys.version or some other way of checking before running. > > > I thought of sys.version... but getting info out of it seems awkward to > me. First 5 chars are '2.4.1' in string format have to split it up and > convert it to ints to do proper checking, etc. It doesn't seem that > sys.version was built with this type of usage in mind. So, what is the > *best* most correct way to go about this? try: from os import walk as os_walk except ImportError: os_walk = None # raise some exception or implement a fallback solution # use os_walk instead of os.walk > > Thanks, > > rbt -- http://mail.python.org/mailman/listinfo/python-list
Re: How to name Exceptions that aren't Errors
Le 7 Apr 2005 19:23:21 GMT, Leo Breebaart a écrit : > I've recently become rather fond of using Exceptions in Python to > signal special conditions that aren't errors, but which I feel > are better communicated up the call stack via the exception > mechanism than via e.g. return values. > > For instance, I'm thinking of methods such as: > > > def run(self): > """ Feed the input file to the simulator. """ > > for linenr, line in enumerate(self.infile): > try: > current_values = self.parse_line(linenr, line) >==> except CommentLineException: > continue > results = self.do_one_simulation_step(current_values) > self.process_simulation_results(results) > > > which I use in order to discard comments from a file I'm parsing > line-by-line. > [snip] > 'Exception' prefix seems a bit redundant and pointless too. I > suppose I could just call the exception "CommentLine" and leave > it at that, but I don't know, maybe there's something better I'm > overlooking. You are overlooking the fact the flow of information is pretty much linear. The comments lines can be safely ignored (filtered out) on the fly. enumerate filter-out infile(producer) > linenr, line ---> linenr, line ---> > > Any suggestions? From your parse_line() method extract the logic to detect a comment line put this code in a predicate function and use itertools.ifilter(pred, iterable). Much more explicit. parse_line() is simplified. The client code run() does not have to deal with bogus inputs anymore if you feed it with the filtered out stream. > -- http://mail.python.org/mailman/listinfo/python-list
Re: Doubt regarding sorting of a list specific field
Le Wed, 13 Apr 2005 01:13:40 -0600, Steven Bethard a écrit : > praba kar wrote: >> list = [[1234,'name1'],[2234,'name2'],[0432,'name3']] >> >> I want to sort only numeric value having array field. >> How I need to do for that. > > In Python 2.4: > > py> import operator > py> seq = [(1234,'name1'),(2234,'name2'),(1432,'name3')] > py> seq.sort(key=operator.itemgetter(0)) > py> seq > [(1234, 'name1'), (1432, 'name3'), (2234, 'name2')] > > Note that I've changed your name 'list' to 'seq' since 'list' is > shadowing the builtin list function in your code, and I've changed your > nested lists to tuples because they look like groups of differently > typed objects, not sequences of similarly typed objects. See: > > STeVe nice explaination. But, if the items of the list are tuples the default rule for comparing tuples is such that seq.sort() would be sufficient here. -- http://mail.python.org/mailman/listinfo/python-list
Re: preallocate list
Le Wed, 13 Apr 2005 16:46:53 +0100, Jim a écrit : > > What I really want is a Numeric array but I don't think Numeric supports > importing files. Numeric arrays can be serialized from/to files through pickles : import Numeric as N help(N.load) help(N.dump) (and it is space efficient) > > Jim -- http://mail.python.org/mailman/listinfo/python-list
Re: module to parse "pseudo natural" language?
Le Sun, 17 Apr 2005 13:38:09 +0200, Andrew E a écrit : > Hi all > > I've written a python program that adds orders into our order routing > simulation system. It works well, and has a syntax along these lines: > > ./neworder --instrument NOKIA --size 23 --price MARKET --repeats 20 > > etc > > However, I'd like to add a mode that will handle, say: > > ./neworder buy 23 NOKIA at MKT x 20 > > I could enter several orders either by running multiple times, or use a > comma-separated approach, like: > > ./neworder buy 23 NOKIA at MKT on helsinki, sell 20 NOKIA at market on > helsinki It would be simpler to have the rule : one line == one order, action, command wahtever. > > The thing about this is that its a "tolerant" parser, so all of these > should also work: > > # omit words like "at", "on" > ./neworder buy 23 NOKIA mkt helsinki > > # take any symbol for helsinki > ./neworder buy 23 mkt helsinki > > # figure out that market=helsinki > ./neworder buy 23 NOKIA at market price You have some variation of the same « buy » order. If you want to detail the semantics : you arrive to determine the different parameter of a BuyCommand : what, where, how (many) ... This semantic is expressed differently in english, US-english, french ... If you base your parser on regex you see that the same BuyOrder is represented by a number of variant : Please, buy 23 NOKIA at market Helsinki Acheter 40 actions Bouygues à la Bouse de Paris So you have for a given environment (orders management module) a number of commands expressed in pseudo-natural languages. Each command has a certain number of attributes name, module_name, parameters, variants(list of regexps for instance), description, short description, sample sentence (to be presented to the user in an interactive session if requested). An important attribute is naturally the action taken when the parser/interpreter matches the current line. So you group the description of the Commands in an easy to parse file and write an interpreter which on startup read such a file for the Commands it understands : command to load a module, to list the commands in the currently loaded module or in the interpreter, command to display the sample, short or long description (help about cmd or how to spell cmd)., command to stop the interpreter (and the program) ... command to read/include a file containings commands to parse and execute. Python is dynamic, with setattr() you can easily construct a Command object from its description. Here is what could be the description of a command to compute the equilibrium position in a stability module (using a «here» shell like syntax ): command equilibre << eoc description << eod La commande « equilibre » permet de lancer le calcul de la position d'équilibre du flotteur couramment décrit. position equilibre en partant de pqr 0.0/0.0/1.0 et h=8.500 les mots-clés sont equilibre pqr et h[=] eod sample < # The regexpes variants << eov # the following regexp is with re.I (ignore case flag) : variant I << eovi equilibrer?\spqr\s+(?P\d*\.\d*/\d*\.\d*/\d*\.\d*)\s+(?P\d*\.\d*) eovvi # syntax of regexp untested :-) variant << eovi equilibrium\spqr\s+(?P\d*\.\d*/\d*\.\d*/\d*\.\d*)\s+(?P\d*\.\d*) eovvi eov eoc > Thanks for any suggestions :) > > Andrew -- http://mail.python.org/mailman/listinfo/python-list
Re: distutils question: different projects under same namespace
Le 16 Apr 2005 01:20:34 -0700, Qiangning Hong a écrit :
> To avoid namespace confliction with other Python packages, I want all
> my projects to be put into a specific namespace, e.g. 'hongqn' package,
> so that I can use "from hongqn.proj1 import module1", "from
> hongqn.proj2.subpack1 import module2", etc.
That makes sense
>
> These projects are developed and maintained and distributed seperately,
> so I should not make a whole 'hongqn' package with one setup.py. I
> must write setup.py scripts for each project. I meet a problem here.
>
> For instance, I am writing setup.py script for proj1. I use the
> following parameters when calling distutils.core.setup:
>
> setup(
> ...
> package_dir = {'hongqn.proj1': 'proj1'},
> packages = ['hongqn.proj1'],
> ...
> )
>
> "python setup.py install" will create /usr/lib/python2.3/hongqn/proj1
> directory and copy proj1/*.py there. But this is UNUSABLE! There is
> NO __init__.py file under /usr/lib/python2.3/hongqn/ so that import
> hongqn.proj1 will fail!
You can detect if there is __init__.py in the hongqn directory.
>
> I am considering manually create this __init__.py by hacking the
> install_lib command. But before making my hands dirty, I want to know
> if there is an "official" solution exists or others have already
> success stories on this matter.
It seems that this problem is tackled in the logilab packages : for
example, you install first the logilab common libraries and then pylint.
So the problem is to define the dependencies of your projects and hence
the order of installation.
>
> As a note, I wish the solution can handle setup.py bdist and
> bdist_wininst well.
>
--
http://mail.python.org/mailman/listinfo/python-list
Re: packages
Le Mon, 18 Apr 2005 20:29:39 +0200, Mage a écrit : >Hello, > > I read about modules and packages in the tutorial. I think I understand > how to use packages and modules, even I know how to create a module (as > far I understand it's a simple .py) file , but I don't know how can I > create a package and when should I do it. The standard library contains some packages : email, xml, distutils ... Read the __init__.py in the directory "package-name". > > Where should I look for more information? > >Mage > example of use : import distutils help(distutils) help(distutils.sysconfig) Traceback (most recent call last): File "", line 1, in ? AttributeError: 'module' object has no attribute 'sysconfig' import distutils.sysconfig help(distutils.sysconfig) distutils.sysconfig.get_python_lib(standard_lib=True) '/home/fp2x/local/lib/python2.4' distutils.sysconfig.get_python_lib(standard_lib=False) '/home/fp2x/local/lib/python2.4/site-packages' -- http://mail.python.org/mailman/listinfo/python-list
Re: XML-RPC -- send file
Le 19 Apr 2005 11:02:47 -0700, codecraig a écrit :
> Experient I have been :)
>
> Here is what I am getting now
>
> CLIENT
> ---
> d = xmlrpclib.Binary(open("C:\\somefile.exe").read())
open the file with mode "rb"
fin = open(r'C:\somefile.exe', 'rb')
contents = fin.read()
fin.close()
d = xmlrpclib.Binary(contents)
> server.sendFile(d)
>
> any ideas?
>
--
http://mail.python.org/mailman/listinfo/python-list
trying to understand unicode
Python has a very good support of unicode, utf8, encodings ... But I
have some difficulties with the concepts and the vocabulary. The
documentation is not bad, but for example in reading
http://docs.python.org/lib/module-unicodedata.html
I had a long time to figure out what unicodedata.digit(unichr) would
mean, a simple example is badly lacking.
So I wrote the following script :
#!/usr/bin/env python
"""Example of use of the unicodedata module
http://docs.python.org/lib/module-unicodedata.html
"""
import unicodedata
import sys
# outcodec = 'latin_1'
outcodec = 'iso8859_15'
if len(sys.argv) > 1:
outcodec = sys.argv[1]
for c in range(256):
uc = unichr(c)
uname = unicodedata.name(uc, None)
if uname:
unfd = unicodedata.normalize('NFD', uc).encode(outcodec,
'replace')
unfc = unicodedata.normalize('NFC', uc).encode(outcodec,
'replace')
print str(c).ljust(3), uname.ljust(42), unfd.ljust(2),
unfc.ljust(2), \
unicodedata.category(uc), unicodedata.numeric(uc, None)
and here are some samples of output
44 COMMA , , Po None
45 HYPHEN-MINUS - - Pd None
46 FULL STOP . . Po None
47 SOLIDUS/ / Po None
48 DIGIT ZERO 0 0 Nd 0.0
49 DIGIT ONE 1 1 Nd 1.0
50 DIGIT TWO 2 2 Nd 2.0
It seems that 'Nd' category means Numerical digit doh!
64 COMMERCIAL AT @ @ Po None
65 LATIN CAPITAL LETTER A A A Lu None
66 LATIN CAPITAL LETTER B B B Lu None
'Lu' should read 'Letter upper' ?
94 CIRCUMFLEX ACCENT ^ ^ Sk None
95 LOW LINE _ _ Pc None
96 GRAVE ACCENT ` ` Sk None
97 LATIN SMALL LETTER A a a Ll None
98 LATIN SMALL LETTER B b b Ll None
'Ll' == Letter lower
124 VERTICAL LINE | | Sm None
125 RIGHT CURLY BRACKET} } Pe None
126 TILDE ~ ~ Sm None
160 NO-BREAK SPACE Zs None
161 INVERTED EXCLAMATION MARK ¡ ¡ Po None
What a gap !
245 LATIN SMALL LETTER O WITH TILDEo? õ Ll None
246 LATIN SMALL LETTER O WITH DIAERESISo? ö Ll None
247 DIVISION SIGN ÷ ÷ Sm None
248 LATIN SMALL LETTER O WITH STROKE ø ø Ll None
'Sm' should read 'sign mathematics' ?
I think that such code snippets should be included in the documentation
or in a Wiki.
Regards
Sorry for bad english, I'm not a native speaker.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Python or PHP?
Le Sat, 23 Apr 2005 19:11:19 +0200, Fredrik Lundh a écrit : > in PHP, good programmers are able to write bad programs without > even noticing. +1 QOTW --- The use of COBOL cripples the mind; its teaching should, therefore, be regarded as a criminal offense. Dr. E.W. Dijkstra -- http://mail.python.org/mailman/listinfo/python-list
[OT] Graphic editor within an MFC app. I have a wxPython prototype, that...
I have built a wxPython prototype of an app, that lets me place rectangles o a wxPanel, move them and change their size. How the rects are added and placed has to follow certain rules. The final goal is to merge this "graphical editor" into a MFC app. Converting a standalone wxPython app into a wxWidget app ist not that complicated. But how about merging it into a MFC app? Has anybody achieved that already? All the functionality lies in my wxPanel-subclass "EditorWidget" and in the few widgets I can place on it. So it boils down to place that "EditorWidget" an a MFC-Panel. But what about the mainloops? If that's not possibel at all, I'd consider getting an ActiveX that offers to me what I need. It does not need to be a full blown CAD ActiveX but should be customizeable. Does anyone know a source for such things? Many thanks in advance and kind regards Franz GEIGER -- http://mail.python.org/mailman/listinfo/python-list
Re: Generating equally-spaced floats with least rounding error
>>> import numpy >>> numpy.arange(0, 3, 0.3) array([ 0. , 0.3, 0.6, 0.9, 1.2, 1.5, 1.8, 2.1, 2.4, 2.7]) -- http://mail.python.org/mailman/listinfo/python-list
Re: nanothreads: Want to use them from within wxPython app
<[EMAIL PROTECTED]> schrieb im Newsbeitrag news:[EMAIL PROTECTED] > F. GEIGER wrote: >> I've def'ed a handler for EVT_IDLE in the app's main frame. There I'd >> like >> to call the nanothreads' __iter__ method, somehow. >> >> When I copy the __iter__ method into a, say, runOnce() method and call >> the >> next() method of the generator returned by runOnce(), it works. But I >> can't >> get at the __iter__ method, which is already there and therefore should >> be >> used instead of messing up nanothreads with changes of mine. >> >> Any hint welcome > > The latest version of nanothreads is now in the fibranet package, which > you can download from the cheeseshop: > > http://cheeseshop.python.org/pypi/FibraNet > > To iterate nanothreads from wx, I call the nanothreads.poll() function Yeah, that's what I was looking for. But poll() is new, isn't it? > from the EVT_IDLE handler, making sure that I call event.RequestMore() Good hint, thanks, I always tend to forget that. > from within the handler, to iterate nanothreads as fast as possible. > > HTH, Simon WIttber. > Thanks for your response and kind regards Franz GEIGER -- http://mail.python.org/mailman/listinfo/python-list
Re: [OT] How can I change Debian's default Python version?
Diez B. Roggisch wrote: > Franz GEIGER wrote: > >> When I call the Python interpreter, the Python 2.4.1 version is called, >> because I installed it weeks ago from source by myself. That means the >> symlink /usr/bin/python points to 2.4. Fine. >> >> Now, when I install Python packages using the convenient Synaptic Package >> Manager, everything goes into the 2.3-directory-tree. How can I change >> that? > > You can't, and shouldn't. However, most packages come with a > python-2.4-version. Install these. That of course means you need the > python-2.4 package installed using debian, not by yourself. Agreed, so I took another Linux box to make sure to not make "custom version" mistakes. Same here. Yes, there are 2.4-packages of all kind. But there's also a dependency package "python" telling the whole box that Python is 2.3.5. And when I want to install wxWidgets into Python 2.4, I am told that it depends on Python 2.3. I guess I'll copy the appropriate directories into my 2.4.-tree as suggested by Heiko... > > > Regards, > > Diez Many thanks and kind regards Franz -- http://mail.python.org/mailman/listinfo/python-list
Re: [OT] How can I change Debian's default Python version?
Ganesan Rajagopal wrote: >> Franz GEIGER <[EMAIL PROTECTED]> writes: > >> Now, when I install Python packages using the convenient Synaptic Package >> Manager, everything goes into the 2.3-directory-tree. How can I change >> that? > > That's because synaptic installs packages compiled for the default debian > python. You have two alternatives: > > 1. Compile the python packages manually. > 2. Debian already has python 2.4. Install python2.4 using synaptic. Also >install any required python2.4-* packages. You will need a symlink to >make sure you get python2.4 by default. How does this symlink have to look like? Is it the one in /usr/bin ? Is this one enough or are there others to be set as well? I did sudo ln -sf python2.4 python but still don't have wx in 2.4, but only in 2.3! > > Ganesan > > > Ganesan > > > Many thanks and kind regards Franz -- http://mail.python.org/mailman/listinfo/python-list
[Python for .NET] Any plans for supporting CLR2.0?
I'm on .NET/CLR2.0 and would like to use some stuff from w/i Python. The "Python for .NET" file name suggests that CLR1.1 is needed. Is that right? Any known plans to change this? Kind regards Franz GEIGER -- http://mail.python.org/mailman/listinfo/python-list
Re: [Python for .NET] Any plans for supporting CLR2.0?
Terry Reedy wrote: > > "F. GEIGER" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] >> I'm on .NET/CLR2.0 and would like to use some stuff from w/i Python. The >> "Python for .NET" file name suggests that CLR1.1 is needed. Is that >> right? Any known plans to change this? > > Most responders here use CPython. The IronPython users mailing list, > mirrored as gmane.comp.python.ironpython.users (see gmane.org) would more > likely give you an authoritative answer. Sorry, for not being precise about "Python for .NET": I didn't mean IronPython, which I'am aware of, I meant http://www.zope.org/Members/Brian/PythonNet > > Terry J. Reedy Kind regards Franz GEIGER -- http://mail.python.org/mailman/listinfo/python-list
easy string formating question
I have kind of an interesting string, it looks like a couple hundred letters bunched together with no spaces. Anyway, i'm trying to put a "?" and a (\n) newline after every 100th character of the string and then write that string to a file. How would I go about doing that? Any help would be much appreciated. -- http://mail.python.org/mailman/listinfo/python-list
trouble with replace
I have a string (xdata) and theres a newline after every 17 characters
of the string. I was wondering how I can replace multiple substrings
multiple times within a string? To put it another way, this is what i
want to do.
Substring to find ("abcdef") replace it with ("highway")
search again, substring to find ("defgef") replace it with
("news").Search again and find ("effwer") replace it with
("monitor").Example string to search under is '''defgefabcdefy
effwerbyuuuterrfr'''
I've tried using replace but its not working for me.
xdata.replace('abcdef', 'highway')
xdata.replace('defgef', 'news')
xdata.replace('effwer', 'monitor')
Basically I would want to get the output of "newshighwayy
monitorbyuuuterrfr"
Thanks, any help would be appreciated.
--
http://mail.python.org/mailman/listinfo/python-list
Re: trouble with replace
Marc 'BlackJack' Rintsch wrote:
> In <[EMAIL PROTECTED]>, f pemberton
> wrote:
>
> > I've tried using replace but its not working for me.
> > xdata.replace('abcdef', 'highway')
> > xdata.replace('defgef', 'news')
> > xdata.replace('effwer', 'monitor')
>
> `replace()` does not work in place. You have to bind the result to a name
> like::
>
> xdata = xdata.replace('abcdef', 'highway')
>
> Ciao,
> Marc 'BlackJack' Rintsch
lol, you probably will not believe me but I actually knew that already.
I just forgot to add that part in my original post. When I try and
replace what happens is the first replace works fine but when I try and
do a second replace on a different part of the same string, the program
will print the string a second time(which I do not want). How can you
do 2 or more replaces in one line of code?
--
http://mail.python.org/mailman/listinfo/python-list
Fw: [wxPython-users] 1>make_buildinfo.obj : error LNK2019: unresolved external symbol [EMAIL PROTECTED] referenced in function _make_buildinfo2
- Forwarded Message From: Josiah Carlson <[EMAIL PROTECTED]> To: f rom <[EMAIL PROTECTED]>; [EMAIL PROTECTED] Sent: Monday, December 4, 2006 10:03:28 PM Subject: Re: [wxPython-users] 1>make_buildinfo.obj : error LNK2019: unresolved external symbol [EMAIL PROTECTED] referenced in function _make_buildinfo2 Ask on [email protected] . - Josiah f rom <[EMAIL PROTECTED]> wrote: > I am trying to debug a segfault which I can not pin down with a simple pytjon > script. > For this I have downloaded the free Microsoft visual express c++. > However I am having problems building python2.5. > Anyone have experience with this ? > > 1>-- Rebuild All started: Project: make_buildinfo, Configuration: Debug > Win32 -- > 1>Deleting intermediate and output files for project 'make_buildinfo', > configuration 'Debug|Win32' > 1>Compiling... > 1>make_buildinfo.c > 1>d:\python-2.5\pcbuild8\make_buildinfo.c(43) : warning C4996: 'strcat' was > declared deprecated > 1>c:\program files\microsoft visual studio 8\vc\include\string.h(78) > : see declaration of 'strcat' > 1>Message: 'This function or variable may be unsafe. Consider using > strcat_s instead. To disable deprecation, use _CRT_SECURE_NO_DEPRECATE. See > online help for details.' > 1>d:\python-2.5\pcbuild8\make_buildinfo.c(47) : warning C4996: 'strcat' was > declared deprecated > 1>c:\program files\microsoft visual studio 8\vc\include\string.h(78) > : see declaration of 'strcat' > 1>Message: 'This function or variable may be unsafe. Consider using > strcat_s instead. To disable deprecation, use _CRT_SECURE_NO_DEPRECATE. See > online help for details.' > 1>d:\python-2.5\pcbuild8\make_buildinfo.c(63) : warning C4996: 'strcat' was > declared deprecated > 1>c:\program files\microsoft visual studio 8\vc\include\string.h(78) > : see declaration of 'strcat' > 1>Message: 'This function or variable may be unsafe. Consider using > strcat_s instead. To disable deprecation, use _CRT_SECURE_NO_DEPRECATE. See > online help for details.' > 1>d:\python-2.5\pcbuild8\make_buildinfo.c(66) : warning C4996: 'strcat' was > declared deprecated > 1>c:\program files\microsoft visual studio 8\vc\include\string.h(78) > : see declaration of 'strcat' > 1>Message: 'This function or variable may be unsafe. Consider using > strcat_s instead. To disable deprecation, use _CRT_SECURE_NO_DEPRECATE. See > online help for details.' > 1>d:\python-2.5\pcbuild8\make_buildinfo.c(69) : warning C4996: 'strcat' was > declared deprecated > 1>c:\program files\microsoft visual studio 8\vc\include\string.h(78) > : see declaration of 'strcat' > 1>Message: 'This function or variable may be unsafe. Consider using > strcat_s instead. To disable deprecation, use _CRT_SECURE_NO_DEPRECATE. See > online help for details.' > 1>d:\python-2.5\pcbuild8\make_buildinfo.c(72) : warning C4996: 'strcat' was > declared deprecated > 1>c:\program files\microsoft visual studio 8\vc\include\string.h(78) > : see declaration of 'strcat' > 1>Message: 'This function or variable may be unsafe. Consider using > strcat_s instead. To disable deprecation, use _CRT_SECURE_NO_DEPRECATE. See > online help for details.' > 1>d:\python-2.5\pcbuild8\make_buildinfo.c(73) : warning C4996: 'strcat' was > declared deprecated > 1>c:\program files\microsoft visual studio 8\vc\include\string.h(78) > : see declaration of 'strcat' > 1>Message: 'This function or variable may be unsafe. Consider using > strcat_s instead. To disable deprecation, use _CRT_SECURE_NO_DEPRECATE. See > online help for details.' > 1>d:\python-2.5\pcbuild8\make_buildinfo.c(81) : warning C4996: 'strcat' was > declared deprecated > 1>c:\program files\microsoft visual studio 8\vc\include\string.h(78) > : see declaration of 'strcat' > 1>Message: 'This function or variable may be unsafe. Consider using > strcat_s instead. To disable deprecation, use _CRT_SECURE_NO_DEPRECATE. See > online help for details.' > 1>d:\python-2.5\pcbuild8\make_buildinfo.c(83) : warning C4996: 'strcat' was > declared deprecated > 1>c:\program files\microsoft visual studio 8\vc\include\string.h(78) > : see declaration of 'strcat' > 1>Message: 'This function or variable may be unsafe. Consider using &g
Re: What am I supposed to do with an egg?!
<[EMAIL PROTECTED]> schrieb im Newsbeitrag news:[EMAIL PROTECTED] > Type "sudo easy_install myeggfile.egg." Sorry for not being clear. I did exec easy_install - no errors so far. But the egg was still there. I'd expected, that it was converted into .py-files somehow, which could be imported by my modules. Kind regards Morpheus > > If that gives you an error, then you don't have easy_install installed. > Install it this way: > > sudo apt-get install python-setuptools > > On Dec 19, 3:44 pm, Morpheus <[EMAIL PROTECTED]> wrote: >> On Windows I'm used to install packages by setup.py install. So did I >> with >> Fibranet nanothreads - a few seconds and it was installed. >> >> On Linux (ubuntu 6.06) all I could get at is an egg file. I found out >> that >> I have to exec easy_install, which didn't much help here (seems to me, at >> least - sorry, Linux newbie). >> >> So, what am I supposed to do here now? >> >> Kind regards >> Morpheus > -- http://mail.python.org/mailman/listinfo/python-list
Re: GDI in python>?
Le 17 Feb 2006 22:02:23 -0800, al pacino a écrit : > hi, > > is it possible to address the 'screen pixels' using python , like > analogous to older dos( functions that graphics.h provides') or win api > calls for gdi. Some possibilities (all on Win32 only): ctypes by Thomas Heller venster (uses ctypes) on sourceforge win32all by Marc Hammond > > what i want is to display clusters (in differetn colours) on screen > using python. > > thanks. > -- http://mail.python.org/mailman/listinfo/python-list
Re: Komodo - Will it Lock Me In?
Le Fri, 17 Feb 2006 18:14:26 -0800, Trent Mick a écrit : > > Nope. Komodo adds no goo to your code (TM). > TM's my name, not a trademark on "Komodo adds no goo to your code" -- > but I'm thinking about it. :) +1 JOTW (Joke of the week) > > Cheers, > Trent > -- http://mail.python.org/mailman/listinfo/python-list
Re: editor for Python on Linux
Le Sun, 19 Feb 2006 21:33:59 +0100, Rene Pijlman a écrit : > Mladen Adamovic: >>I wonder which editor or IDE you can recommend me for writing Python >>programs. > > vi I beg to disagree :-) Use ed "Ed is the standard text editor." http://www.gnu.org/fun/jokes/ed.msg.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Writing an OPC client with Python ?
About a year ago I dev'ed a host app in Python (2.3 at that time) to control a KUKA KR16 robot. Comm was over OPC. The OPC 2.0 server was inst'ed on the KRC2. What I was needed to do, was to install the appropriate (i.e. delivere together w/ the server) client software and to take Mark Hammonds COM Makepy utility to to create the wrapper. The rest of the story was fun, pure fun, as Python programming always is. So, register the client software, fire up PythonWin, start the COM Makepy utility and wrap that DLL. If you are completely new to this stuff, it might help to look at all that from w/i MSVB 6.0 or something like that. HTH Franz GEIGER "pierlau" <[EMAIL PROTECTED]> schrieb im Newsbeitrag news:[EMAIL PROTECTED] > Hello, > > I use an OPC server for connection to DC Drive. > I would like to write a small OPC client. > I have the dll OPCDAAuto.dll which contains all class and method but I > wonder if its possible to instance in python the class that are in the dll > ? > > Thanks for your help . > > Pierre > > > -- http://mail.python.org/mailman/listinfo/python-list
Re: sorting list and then return the index of the sorted item
Le 3 May 2005 06:37:14 -0700, custard_pie a écrit : > I need help sorting a list...I just can't figure out how to sort a list > and then return a list with the index of the sorted items in the list > for example if the list I want to sort is [2,3,1,4,5] > I need [2,0,1,3,4] to be returned > Can someone help please If you have Python version 2.4 (or 2.4.1): lst = [2,3,1,4,5] import operator sorted(enumerate(lst), key=operator.itemgetter(1)) [(2, 1), (0, 2), (1, 3), (3, 4), (4, 5)] But *why* do you want the indices ? Most of the time dealing with the indices is the wrong way in Python (perhaps the right way in FORTRAN :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: get file modification time in mm/dd/yyyy format?
Le 7 May 2005 08:23:48 -0700, [EMAIL PROTECTED] a écrit :
> Using Python 2.4 on Windows, for me the command
>
> print os.stat("temp.txt")[stat.ST_MTIME]
>
> gives
>
> 1115478343 ,
>
> which is "seconds since the epoch". How can I get the modification time
> in a format such as
>
> 05/07/2005 11:05 AM
>
> as in Windows with the dir command? Ideal would be a tuple of 6 values,
> (year,month,day,hour,minute,second). Thanks.
>
I type
import time
dir(time)
lot of stuff
help(time.localtime)
localtime([seconds]) ->
(tm_year,tm_mon,tm_day,tm_hour,tm_min,tm_sec,tm_wday,tm_yday,tm_isdst)
Convert seconds since the Epoch to a time tuple expressing local time.
When 'seconds' is not passed in, convert the current time instead.
>>> time.localtime(1115478343)
(2005, 5, 7, 17, 5, 43, 5, 127, 1)
it seems to be 7 may 2005 17h 5 minutes 43 seconds
To have such a formatting you have to type help(time.strptime) which
sadly will say
See the library reference manual for formatting codes (same as strftime()).
---
there is no perfect world
--
http://mail.python.org/mailman/listinfo/python-list
Re: Shell Commands in Python Code
Le Sat, 7 May 2005 08:55:35 -0700 (PDT), Sara Khalatbari a écrit : > There are a lot of commands that I need to use in my > code & I don't know how to do it > > Is there a way to use shell commands in Python code? Python is a scrpting language. So you can substitute most shell scripts idioms with pythonic ones. A large number of shell scripts can be replaced with python scripts without any semantic loss. > -- http://mail.python.org/mailman/listinfo/python-list
Re: Trouble saving unicode text to file
Le Mon, 09 May 2005 08:39:40 +1000, John Machin a écrit :
> On Sun, 08 May 2005 19:49:42 +0200, "Martin v. Löwis"
><[EMAIL PROTECTED]> wrote:
>
>>John Machin wrote:
>>> Martin, I can't guess the reason for this last suggestion; why should
>>> a Windows system use iso-8859-1 instead of cp1252?
>>
>>Windows users often think that windows-1252 is the same thing as
>>iso-8859-1, and then exchange data in windows-1252, but declare them
>>as iso-8859-1 (in particular, this is common for HTML files).
>>iso-8859-1 is more portable than windows-1252, so it should be
>>preferred when the data need to be exchanged across systems.
>
> 1. When exchanging data across systems, should not utf-8 be
> preferred???
>
> 2. If the Windows *users* have been using characters that are in
> cp1252 but not in iso-8859-1, then attempting to convert to iso-8859-1
> will cause an exception.
>
euro_win = chr(128)
euro_uc = euro_win.decode('cp1252')
euro_uc
> u'\u20ac'
unicodedata.name(euro_uc)
> 'EURO SIGN'
euro_iso = euro_uc.encode('iso-8859-1')
> Traceback (most recent call last):
> File "", line 1, in ?
> UnicodeEncodeError: 'latin-1' codec can't encode character u'\u20ac'
> in position 0: ordinal not in range(256)
>
> I find it a bit hard to imagine that the euro sign wouldn't get a fair
> bit of usage in Swedish data processing even if it's not their own
> currency.
For western Europe countries, another codec exists which includes the
'EURO SIGN'. It is spelled 'iso8859_15' (with an alias 'iso-8859-15'
according to the 4.9.2 Standard Encodings page of the python library
reference).
euro_iso = euro_uc.encode('iso8859_15')
>>> euro_iso
'\xa4'
>
> 3. How portable is a character set that doesn't include the euro sign?
I think it is due to historical constraints : isoLatin1 existed before
that the EURO SIGN appeared.
>
> Regards,
> John
--
http://mail.python.org/mailman/listinfo/python-list
Re: Python Documentation (should be better?)
Le Wed, 11 May 2005 15:58:04 -0400, rbt a écrit : > Christopher J. Bottaro wrote: > Because PHP is such a 'thrown together' and 'bolted-on' language. If it > didn't have *outstanding* documentation (which it does BTW), no one > could even begin to understand how they got from a little HTML language > to a kinda/sorta OO language. +1 QOTW -- http://mail.python.org/mailman/listinfo/python-list
Re: Can get reference of a part of a list?
Le Fri, 13 May 2005 00:58:49 +0800, flyaflya a écrit : > I want make a 2-D array from a list,all elements is references of > list's,like this: > a = [1,2,3,4] > b = [ [1,2], [3,4] ] > when change any elements of a, the elements of b will change too, so I > can use some function for list to change b. > c/c++ can work in this way,I think let b[0] = a[0:2], b[1] = a[2:3],but > it's not reference,it's copy. If the original list contains only numeric values of the same type, i.e only integers or only floats, the Numeric array reshape() function is what you need : import Numeric as N aa = N.array([1, 2, 3, 4]) bb = N.reshape(aa, (2, 2)) print bb array([[1, 2], [3, 4]]) bb[0][:] = (7, 8) aa array([7, 8, 3, 4]) That is there is only one homogeneous list of values, no copy. -- http://mail.python.org/mailman/listinfo/python-list
Re: wxTimer problem
As Jp asked already: "indepenedent" from what? I do such things all the time in a wx-App that controls a 6-axes robot. For example, there I have a LED-Widget for displaying the actual pos. and orient. of the tool. In a wxTimer handler I read OPC variables, whose values are displayed in the LED-Widgets (the 6 LED-widgets make up a compound widget that does the data retreival in a wxTimer handler). My app is full of widgets that own a timer to display current values. As for "independent": If you wrote a GUI app in wx you'll want to display those values coming from some COM objects. So simply tie a timer to the widget that should display it and - do it. Or tie it to the frame containing your widget. It's up to you - plenty of possibilities in wx/Python, and total freedom (I know what I'm speakin' of, I started that app in VB...). Kind regards Franz GEIGER "Jp Calderone" <[EMAIL PROTECTED]> schrieb im Newsbeitrag news:[EMAIL PROTECTED] > On Fri, 13 May 2005 14:57:26 +0800, Austin <[EMAIL PROTECTED]> wrote: > >I wrote a GUI program on windows. (python & wxPython) > >One function is to refresh the data from the COM Object continously. > >In the beginning, I used the thread.start_new_thread(xxx,()) > >But no matter how i try, it will cause the win32com error. > > > >After that, i use the wx.Timer to do the refresh function. > >It works fine, but i find one problem. > >I think timer should be independant, just like thread, but wxTimer doesn't. > > > >1. Does python have timer function( not included by thread)? > >2. About the wxTimer, does any parameter to let it be independent? > > > > What does "independent" mean? > > Jp -- http://mail.python.org/mailman/listinfo/python-list
Re: os.popen vs os.system
Le Tue, 17 May 2005 13:50:08 -0400, rbt a écrit : > Is it more appropriate to use os.popen or os.system on a windows XP > client? Nope. use the subprocess module :-) Microsoft had the great idea to embed white space inside a lot of directories (compare C:\Program Files\ to /usr/bin ) which means that you must find the right way to quote the command line string of os.system() and this quoting is very tricky and under-documented. A nightmare to thousands of developers which has a cost of millions of dollars :-( Exercice for the reader : write a windows application which can only be invoked from the command line (or from another program) not by clicking on a cute icon. Extra bonus points if the path to this executable contain (after Program Files) a company name with some characters hard to type on some keyboards (or with some locales), if the executable name has also difficult to type characters and if the case is checked (windows file system is case preserving). -- http://mail.python.org/mailman/listinfo/python-list
pysqlite2.dbapi2.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 0, and there are -1 supplied.
Im on Python 2.3.4, using pysqlite 2.0.0 (final). When I try to execute self._dbc.execute(q, data) where q is 'select count(*) from Difflets ' and date is None I get the following exception: pysqlite2.dbapi2.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 0, and there are -1 supplied. Any ideas? Many thanks in advance and kind regards Franz GEIGER -- http://mail.python.org/mailman/listinfo/python-list
Re: pysqlite2.dbapi2.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 0, and there are -1 supplied.
Arrgh, sorry for that post! self._dbc.execute(q, data) where data is None, works with MySQL. For SQLite I have to write if data is not None: self._dbc.execute(q, data) else: self._dbc.execute(q) Sorry again, Franz GEIGER "F. GEIGER" <[EMAIL PROTECTED]> schrieb im Newsbeitrag news:[EMAIL PROTECTED] > Im on Python 2.3.4, using pysqlite 2.0.0 (final). > > When I try to execute > > self._dbc.execute(q, data) > > where q is 'select count(*) from Difflets ' and date is None > > I get the following exception: > > pysqlite2.dbapi2.ProgrammingError: Incorrect number of bindings supplied. > The current statement uses 0, and there are -1 supplied. > > Any ideas? > > Many thanks in advance and kind regards > Franz GEIGER > > > -- http://mail.python.org/mailman/listinfo/python-list
Re: pysqlite2.dbapi2.ProgrammingError: Incorrect number of bindingssupplied. The current statement uses 0, and there are -1 supplied.
Thank you Gerhard, "Gerhard Häring" <[EMAIL PROTECTED]> schrieb im Newsbeitrag news:[EMAIL PROTECTED] > F. GEIGER wrote: > > Arrgh, sorry for that post! > > > > self._dbc.execute(q, data) > > > > where data is None, works with MySQL. For SQLite I have to write > > > > if data is not None: > > self._dbc.execute(q, data) > > else: > > self._dbc.execute(q) > > No, you have to write: > > self._dbc.execute(q, (data,)) > > in both drivers. > > i. e. the second parameter to execute *must* be a sequence. Some drivers > (maybe MySQLdb, too) automatically correct the wrong call and transform a: > Okay, that makes sense. > execute(sql, single_param) > > into a > > execute(sql, (single_param,)) > > for you if they notice that "!PySequence_Check(single_param)". > > pysqlite 2 does not do this. > > HTH, > > -- Gerhard Many thanks again Franz -- http://mail.python.org/mailman/listinfo/python-list
[pysqlite] pysqlite2.dbapi2.OperationalError: cannot commit transaction - SQL statements in progress
I've troubles to let my app take off using pysqlite.
What I wonder most for now is that "pysqlite2.dbapi2.OperationalError:
cannot commit transaction - SQL statements in progress" when I do this:
t = time.time()
n = len(self)
while len(self):
del self[0]
self.commit()
print "%d items deleted in %.3f secs. " % (n, time.time() - t)
self is of class DbTable which lets db tables be used like ordinary Python
objects (after an idea of Scott Scriven):
def __len__(self):
self._query_("select count(*) from %s %s" % (self._name,
self._whereClause))
r = int(self._dbc.fetchone()[0])
return r
and
def __delitem__(self, i):
'''Enables you to remove rows this way: del movies[58]
'''
q = "select %s from %s %s %s limit %s, 1" % (self._nameOfIdCol,
self._name, self._whereClause, self._orderClause, i)
self._query_(q)
rid = self._dbc.fetchone()[0]
q = "delete from %s where %s='%s'" % (self._name, self._nameOfIdCol,
rid)
self._query_(q)
return
So it boils down to SELECT and DELETE statements called in a loop. After
that a commit is made.
What does pysqlite try to tell me here?
Kind regards
Franz GEIGER
PS.: I use pysqlite 2.0.1 on Python 2.3.4
--
http://mail.python.org/mailman/listinfo/python-list
