ConfigParser
Is there an alternative to standard module ConfigParser, which can use delimitier symbol other than ":" and "=", preferaby just space? I need to parse such configs: [Passwords] 2:5020/758 2:5020/794 ConfigParser is not able to work with option names which contain symbol ':' It is not difficult to modify ConfigParser to resolve it, but may be another solution already exists? -- http://mail.python.org/mailman/listinfo/python-list
load_module for import entire package
Hi,
I need to import package and instantiate a class, defined in one of modules,
located in package.
Package is located in folder "tmp". basedir - path to running python script.
I'm doing it so:
import imp
def load_package_strict(p_package_name, p_package_path):
f, filename, description = imp.find_module(p_package_name, [p_package_path])
try:
result = imp.load_module(p_package_name, f, filename, description)
finally:
if f: f.close
return result
def get_obj():
pkg = load_package_strict("tmp", basedir)
from tmp import main
return main.TTT()
It is working, but if package code changes on disc at runtime and I call
get_obj again, it returns instance of class, loaded for the first time
previously.
How to replace line "from tmp import main" by getting properties of pkg?
Regards,
Sergey
--
https://mail.python.org/mailman/listinfo/python-list
load_module for loading packages
Hi, If I use load_module for loading module, I can instantiate classes, defined in that module. Is it possible to do the same, if load not a module, but package? Python documentation for load_module contains description, that load_module can load a package. But I can not find examples, how to work with result of load_module, used for loading a package. Regards, Sergey -- https://mail.python.org/mailman/listinfo/python-list
Re: load_module for import entire package
> This should work:
> def get_obj():
> tmp = load_package_strict("tmp", basedir)
> return tmp.main.TTT()
Thank you:)
I can only mention that it is working only if __init__.py of pkg contains line:
import main
To avoid modules caching I copy package to the new folder with another name and
import it using this new name.
tmp_pkg = "t" + str(randint(1,1)) + '_' +
time.strftime("%Y%m%d%H%M%S", time.localtime())
shutil.copytree(pkg_dir, basedir + '/x/' + dir_name + '/' + tmp_pkg)
pkg = load_package_strict(tmp_pkg, basedir + '/x/' + dir_name)
result = pkg.main.TTT()
What is the risk of this method? What are 3 methods of doing the same?
--
Sergey
--
https://mail.python.org/mailman/listinfo/python-list
thread and alarm
How to send alarm to a thread? I can set alarm in main thread, but how then send exception to another thread to wake it if it executes too long? -- http://mail.python.org/mailman/listinfo/python-list
file names longer than MAX_PATH under Windows 2003
Hello. I try to open file with pathname length 282 bytes: E:\files\..\something.dat On MSDN (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/fileio/fs/naming_a_file.asp) described method to access files with path length up to 32000 bytes: just add prefix \\?\ to file name. But when I try to pass prefixed name to file(), I get the same result as when I don't add the prefix: file not found. May be Python just doesn't support long unicode filenames? Is there way to open such files? -- http://mail.python.org/mailman/listinfo/python-list
Re: file names longer than MAX_PATH under Windows 2003
"Tim Golden" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] [Sergey] >But note that r prefix to the string. Is it possible >that your string didn't include it? If not, then the >backslash character which Windows uses as a separator >can be stolen by Python which sees it as an escaping >character. It's ok with backslashes, I don't use r'', but double them so string is correct: >>> print c \\?\e:\files\ -- http://mail.python.org/mailman/listinfo/python-list
Re: file names longer than MAX_PATH under Windows 2003
"Tim Golden" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] [Sergey] >Not to state the obvious, but can you cut-and-paste that long >string (the one starting with \\?\e:\...) from the Python >interpreter into the [S]tart [R]un [O]pen field to see what >comes up? I'm just trying to make sure of the most straightforward >fact: that the file you've got there definitely does exist! I cannot do this: when I paste filename there, trail of filename is missing due to length limit in input line. But I strongly suppose that file exists as its name was get through os.listdir. -- http://mail.python.org/mailman/listinfo/python-list
Re: file names longer than MAX_PATH under Windows 2003
"Steven D'Aprano" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Are you passing a unicode object to the function? > > f = file(u"E:\\files\\...\\something.dat", "r") I pass variable c into functions: >>> c u'.\\e:\\files\\\u041f\u0420\u041e\u0414\u041e \u041c\u0435\u043d\u0435\u043 [many unicode chars skipped] 44b\u0439_\u0411\u044e\u0434\u0436\u0435\u0442.xls' -- http://mail.python.org/mailman/listinfo/python-list
Re: file names longer than MAX_PATH under Windows 2003
"Tim Golden" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] [Sergey] >Not to state the obvious, but can you cut-and-paste that long >string (the one starting with \\?\e:\...) from the Python >interpreter into the [S]tart [R]un [O]pen field to see what >comes up? I'm just trying to make sure of the most straightforward >fact: that the file you've got there definitely does exist! Sorry, it was my error - there was extra backslash in the middle of path. \\?\path works OK. -- http://mail.python.org/mailman/listinfo/python-list
Re: file names longer than MAX_PATH under Windows 2003
"Tim Golden" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] [Sergey] >I see from another post that CreateFile cannot open your file. >That puts it further away from Python, although it doesn't >explain how some other program can see the files. Can you use >os.startfile (or its equivalent win32api.ShellExecute from >pywin32)? Perhaps if you were to chdir to the directory in >question you'd be able to access the file. I found error in filename (extra backslash) and now I can open file. But another trouble appeared: I cannot listdir so long name. I examined posixmodule.c... There are wcsncpy with hard limit of MAX_PATH*2+5. So... RIP, my module... -- http://mail.python.org/mailman/listinfo/python-list
Re: file names longer than MAX_PATH under Windows 2003
"Tim Golden" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] [Sergey] >Have a look at win32file.FindFilesIterator from the pywin32 extensions. >Maybe that can cope? (I haven't looked at the source). Yeah, it works! THANK YOU! (but now I must have two pieces of code, one for linux and one for windows) Interesting, why developers of python didn't use here all power of win32 API? -- http://mail.python.org/mailman/listinfo/python-list
Re: file names longer than MAX_PATH under Windows 2003
"Claudio Grondi" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Sergey wrote: > I don't know if and how it apply and can be of any help here, but in my C > programs in the very past after switching from DOS to > Windows long names a following trick solved often my problems with too long > names: > step 1: setting the current directory to the beginning part of the name > with a length which can be passed as a function > parameter > step 2: usage of the remaining part of name as name passed as parameter to > the file accessing function (relative to current > directory) It seems this method doesn't help here. -- http://mail.python.org/mailman/listinfo/python-list
module time
There is function mktime() -- convert local time tuple to seconds since Epoch in module time. But how about to convert *GMT time tuple* to seconds since Epoch? Is there such function? -- http://mail.python.org/mailman/listinfo/python-list
why? [win32com/WMI]
import win32com.client
loc = win32com.client.Dispatch("WbemScripting.SWbemLocator")
svc = loc.ConnectServer("srv", "root/cimv2", "[EMAIL PROTECTED]", "**")
sys = svc.get("Win32_Process")
sys.create("notepad.exe")
=>
Traceback (most recent call last):
File "remote.py", line 6, in ?
sys.create("notepad.exe")
TypeError: 'int' object is not callable
--
http://mail.python.org/mailman/listinfo/python-list
Re: why? [win32com/WMI]
"Tim Golden" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
[Sergey]
>import wmi
>c = wmi.WMI (computer="srv", user="[EMAIL PROTECTED]", password="")
>pid, retval = c.Win32_Process.Create (CommandLine="notepad.exe")
Wonderful... It works.
But I tryed the module, by the sample from help(wmi):
>>> remote_process = wmi.WMI (computer="pms-dc", user="...",
>>> password="...").new ("Win32_Process")
And got:
Traceback (most recent call last):
File "", line 1, in ?
File "C:\Python24\Lib\site-packages\wmi.py", line 624, in new
return getattr (self, class_name).new (**kwargs)
File "C:\Python24\Lib\site-packages\wmi.py", line 539, in new
obj.set (**kwargs)
File "C:\Python24\Lib\site-packages\wmi.py", line 394, in set
handle_com_error (error_info)
File "C:\Python24\Lib\site-packages\wmi.py", line 199, in handle_com_error
raise x_wmi, "\n".join (exception_string)
wmi.x_wmi: -0x7ffdfff7 - Exception occurred.
Error in: SWbemObjectEx
-0x7ffbefdc - Provider is not capable of the attempted operation
So I decided to fallback to clean COM.
--
http://mail.python.org/mailman/listinfo/python-list
Re: why? [win32com/WMI]
"Tim Golden" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] [Sergey] >| >import wmi >| >c = wmi.WMI (computer="srv", user="[EMAIL PROTECTED]", password="") >| >pid, retval = c.Win32_Process.Create (CommandLine="notepad.exe") >| >| Wonderful... It works. >Also, in case you haven't, have a look at the cookbook page: >http://timgolden.me.uk/python/wmi_cookbook.html >which has several useful examples. Yes, I had run it. And, just now I updated python, pythonwin and wmi.py to latest version. And got: >>> a=wmi.WMI() >>> a.Win32_Process.Create(CommandLine="notepad.exe")# --- it works >>> a.Win32_Process.new().Create(CommandLine="notepad.exe") # it still fail Traceback (most recent call last): File "", line 1, in ? File "wmi.py", line 361, in __call__ handle_com_error (error_info) File "wmi.py", line 208, in handle_com_error raise x_wmi, "\n".join (exception_string) wmi.x_wmi: -0x7ffdfff7 - Exception occurred. Error in: SWbemObjectEx -0x7ffbefff - Generic failure Without 'new' everything works. And does everything I need from it. And, I have another question. Is there way to access WMI from linux? -- http://mail.python.org/mailman/listinfo/python-list
threading.Semaphore or gevent.lock.Semaphore
Hello, I'm developing Flask app, processed by gevent.wsgi.WSGIServer. If I need to isolate some pieces of code inside request handlers, can I use threading.Lock? If I need semaphore, must I use threading.Semaphore or gevent.lock.Semaphore? What is the difference between them? Thank you! -- https://mail.python.org/mailman/listinfo/python-list
Python for Gaim
Hello everybody. We wrote a Python plugin for Gaim. Now you can write plugins for Gaim and use Python. ALL Gaim API are available for developers under Python. You can download this on http://sourceforge.net/projects/pygaim Please include it as a plugin for GAIM(like perl) Best regards, Sergey -- http://mail.python.org/mailman/listinfo/python-list
struct.(un)pack and ASCIIZ strrings
I can use string.unpack if string in struct uses fixed amount of bytes. But is there some extension to struct modue, which allows to unpack zero-terminated string, size of which is unknown? E.g. such struct: long, long, some bytes (string), zero, short, short, short. -- http://mail.python.org/mailman/listinfo/python-list
regexp weirdness (bug?)
Here's the session log:
>>> _re_pair="(?(plus).|-)"
>>> _re1=("(?P\+)"+_re_pair)
>>> _re2=("((?P\+))"+_re_pair)
>>> _re3=("(?:(?P\+))"+_re_pair)
>>> _re4="(%s)"%_re3
>>> import re
>>> print [re.match(_re, "+a") and 'match' for _re in [_re1, _re2,
_re3, _re4]]
['match', None, 'match', None]
this is not the supposed behaivour. all theese patterns should match,
right?
--
http://mail.python.org/mailman/listinfo/python-list
Re: regexp weirdness (bug?)
it's line #159 here, but it did work! thanks. so it IS a bug? -- http://mail.python.org/mailman/listinfo/python-list
Multiprocessing pool with custom process class
Hi All, I have a web-service that needs to handle a bunch of work requests. Each job involves IO call (DB, external web-services to fetch some data), so part of the time is spent on the blocking IO call. On the other side, after getting the data the job involves computational part (using numpy/pandas on time series dataframes). Service runs on multicore machine, so I want to use parallelism as much as possible (especially considering python's GIL) and due to decent number of IO, I want to use multiple threads inside each process so none of CPUs will stale due to IO delays. It'd be the best scenario to use pool of processes and thread pool (because each worker will need to keep some state, like db connections). I already have my own thread pool implementation, that uses some load-balancing and fair-scheduling techniques that are specific to my problem domain. I'm curious if there is any multiprocessing module that I missed and which I can reuse. As it turned out, the on in the multiprocessing module doesn't support custom Process class (if there were, I would be able to derive it and add the functionality I need) ( http://stackoverflow.com/questions/740844/python-multiprocessing-pool-of-custom-processes). Is there any alternative module that I can reuse? If not, what's the best way to notify caller that the task finished its execution (aka multiprocessing.Pool's apply() function behavior)? What primitives are better to use for that purpose (in case I'll have to go with my own implementation of multiprocessing pool)? Any reference to good blog/educational resource will be highly appreciated! If you believe that my solution is not optimal and have better/easier solution (hope I specified my problem good enough), please share your thoughts Thanks in advance! -- https://mail.python.org/mailman/listinfo/python-list
Re: [OT] Question about Git branches
"Frank Millman" writes: > 3. I have sympathy for Marko's position of using clones rather than > branches. I realise it does not follow the 'git' philosophy, IMHO one important thing about git that made it is so popular is the fact that it tries hard not to impose any policy or particular work-flow on you, so if clones work better for you, using them still follows git philosophy. -- Sergey. -- https://mail.python.org/mailman/listinfo/python-list
Re: [OT] Question about Git branches
m to the staging area (unless we talk about some GUI on top of Git), so it rather looks like: - choose which changes you want to commit by adding them to the staging area. - commit. You can often bypass staging by "git commit -a", but anyway, "staging area" or "index" is yet another thing in Git it's better to make yourself familiar with, as you won't be able to ignore it if you ever reabase or merge. > This seems error-prone. Am I missing something? What exactly is error-prone? Are you afraid to commit to a wrong branch? Are you afraid to commit the changes you didn't want to commit? Anyway, if you did a mistake, you should be able to examine situation and fix it rather easily, provided you didn't yet publish your history. HTH, -- Sergey. -- https://mail.python.org/mailman/listinfo/python-list
syntax enhancement
Hi, you may found this idea stupid, but nevertheless... - `[]` - used for list comprehension, - `()` - used for generators, - `[start:stop]` / `[start:stop:step]` - used for slices. The idea is to use `(start:stop)` / `(start:stop:step)` as 'lazy evaluated' slices (like itertools.islice). What do you think about it? -- Best regards, Valiev Sergey *skype:* *svaliev* *jabber:* *[email protected]* *phone:* +7 926 233-17-64 -- http://mail.python.org/mailman/listinfo/python-list
treating MIME messages
Hello all. Anybody who has idle time, please look at my version of MIME tools at http://www.fidoman.ru/prog/mime/. Questions and critical notes are welcome. If somebody will consider that interesting, I will refine these modules and put to pypi. -- http://mail.python.org/mailman/listinfo/python-list
Sql Parser
Does anybody know python module for sql parsing? -- http://mail.python.org/mailman/listinfo/python-list
subexpressions
Hello all! Please help, is there way to use sub-expressions in lambda? For example, if I want to calculate sin(x^2)+cos(x^2) I must code: lambda x: sin(x*x)+cos(x*x) How to make x*x to be evaluated once? -- http://mail.python.org/mailman/listinfo/python-list
Re: subexpressions
"Peter Otten" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] Please help, is there way to use sub-expressions in lambda? For example, if I want to calculate sin(x^2)+cos(x^2) I must code: lambda x: sin(x*x)+cos(x*x) How to make x*x to be evaluated once? >>> >> (lambda x: [sin(x2) + cos(x2) for x2 in [x*x]][0])(.5) == sin(.5*.5) >> + >>> cos(.5*.5) >>> True >>> >>> The real answer is of course: Use a function. >> >> But what about something like >> >> lambda x: sin(y)+cos(y) where y=x*x >> >> ? >> May be this could be a PEP? If there is no straight way to do this. > > def f(x): >y = x*x >return sin(y) + cos(y) > > What is not straightforward about that? This code is needed once in a map, so I don't want 3+ extra lines. Solution seemed so simple... I always considered python as languague, where simple things do not require extensive coding. Moreover, this construction is common thing in functional programming. -- http://mail.python.org/mailman/listinfo/python-list
Re: subexpressions
"Peter Otten" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Sergey Dorofeev wrote: > >> Please help, is there way to use sub-expressions in lambda? >> For example, if I want to calculate sin(x^2)+cos(x^2) I must code: >> lambda x: sin(x*x)+cos(x*x) >> How to make x*x to be evaluated once? > >>>> (lambda x: [sin(x2) + cos(x2) for x2 in [x*x]][0])(.5) == sin(.5*.5) + > cos(.5*.5) > True > > The real answer is of course: Use a function. But what about something like lambda x: sin(y)+cos(y) where y=x*x ? May be this could be a PEP? If there is no straight way to do this. -- http://mail.python.org/mailman/listinfo/python-list
Re: subexpressions
"Peter Otten" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > What syntax would you suggest for a lambda enhanced to cover your use > case? > I suppose you will end up with roughly the same number of characters, all > crammed in one line -- or broken into lines at a random position as it > happens with overambitious list comprehensions. Agree, this argument is strong. -- http://mail.python.org/mailman/listinfo/python-list
module email
Hello.
Why does not work?
--
import email.message
import smtplib
import time
m=email.message.Message()
m.set_type("multipart/mixed")
m["From"]="Sergey Dorofeev <[EMAIL PROTECTED]>"
m["To"]="Sergey Dorofeev <[EMAIL PROTECTED]>"
m["Date"]=time.asctime()
m["Subject"]="test"
p1=email.message.Message()
p1.set_payload("message text", "us-ascii")
m.attach(p1)
p2=email.message.Message()
p2.set_payload("message text 2", "us-ascii")
m.attach(p2)
del p1,p2
print m.as_string()
print "*"*50
x=email.message.Message()
x.set_type("multipart/mixed")
x["From"]="Sergey Dorofeev <[EMAIL PROTECTED]>"
x["To"]="Sergey Dorofeev <[EMAIL PROTECTED]>"
x["Date"]=time.asctime()
x["Subject"]="test"
p1=email.message.Message()
p1.set_payload("message text !", "us-ascii")
print p1
x.attach(p1)
p2=email.message.Message()
p2.set_type("message/rfc822")
p2.set_payload(m)
print p2
x.attach(p2)
print "*"*50
print x.as_string()
--
I'm using Python 2.5
--
http://mail.python.org/mailman/listinfo/python-list
Re: module email
"Rob Wolfe" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
>> p2=email.message.Message()
>> p2.set_type("message/rfc822")
>> p2.set_payload(m)
>
> Payload is a _list_ of Message objects (is_multipart() == True)
> or a _string_ object (is_multipart() == False) but never just Message
> object.
1. If I give m.as_string() into set_payload, result is the same.
2. I don't understand, how message/rfc822 section can accept a list of two
or more messages. Can you explain?
--
http://mail.python.org/mailman/listinfo/python-list
f---ing typechecking
Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> (1,)+[1] Traceback (most recent call last): File "", line 1, in TypeError: can only concatenate tuple (not "list") to tuple >>> [1]+(1,) Traceback (most recent call last): File "", line 1, in TypeError: can only concatenate list (not "tuple") to list >>> Its ugly and boring. -- http://mail.python.org/mailman/listinfo/python-list
Re: f---ing typechecking
"James Stroud" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] >[1]+(1,) >> >> Traceback (most recent call last): >> File "", line 1, in >> TypeError: can only concatenate list (not "tuple") to list >> >> >> Its ugly and boring. > > Agreed. This would be similar to: > > py> 1 + 1.0 > > Traceback: can only add int to int. Etc. > > But then again, the unimaginative defense would be that it wouldn't be > python if you could catentate a list and a tuple. Maybe, but I don't think that it is best side of the languague. If we want constant objects like tuple why not to specify it explicitly? If we want lists as dict keys, why not to use copy-on-write? -- http://mail.python.org/mailman/listinfo/python-list
Re: f---ing typechecking
<[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > It's effectively a tuple with field names. I don't know when the switch > occurred (it's in 2.2, as far back as my built interpreter versions > currently go), but back in the day os.stat used to return a plain old > tuple. posix.stat_result is CLASS, not regular tuple. classes is the only way in python to approximate records/structs (may be dict can be considered as record too, if we agree with strange syntaxis). To consider tuples as struct, one must have a GREAT imagination, as tuples functionally are _arrays_, with only difference from lists as freezeness - the have NO filed names. > I have no idea if the schizophrenic personality of tuples will improve > with > drugs^H^H^H^H^H Python 3, but I wouldn't be at all surprised if it did. I think the best thing is to be more democratic when asked to add two arrays :) -- http://mail.python.org/mailman/listinfo/python-list
Python lex settings
Hello. I'm trying to make almost-Python source to Erlang source translation tool. Are there ready ply.lex settings for parsing python source? -- http://mail.python.org/mailman/listinfo/python-list
Re: Python lex settings
On Dec 19, 2:16 am, Robert Kern wrote: > Sergey Shepelev wrote: > > Hello. > > > I'm trying to make almost-Python source to Erlang source translation > > tool. > > > Are there ready ply.lex settings for parsing python source? > > Yes! Andrew Dalke has implemented a PLY grammar for Python for experimenting > with almost-Python languages. > > http://www.dalkescientific.com/Python/python4ply.html > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > that is made terrible by our own mad attempt to interpret it as though it > had > an underlying truth." > -- Umberto Eco Wow! Thank you very much, it's exactly what i was searching for. -- http://mail.python.org/mailman/listinfo/python-list
Default __nonzero__ impl doesn't throw a TypeError exception
In Python empty container equals False in 'if' statements: # prints "It's ok" if not []: print "It's ok" Let's create a simple Foo class: class Foo: pass Now I can use Foo objects in 'if' statements: #prints "Ouch!" f=Foo() if f: print "Ouch!" So, default __nonzero__ impl is to return True. I think, this behaviour conflicts with 'Explicit is better than implicit' and 'Practicality beats purity' statements. I think, throwing a TypeError exception would be better. It will result in more explicit code with fewer errors. -- http://mail.python.org/mailman/listinfo/python-list
Re: Default __nonzero__ impl doesn't throw a TypeError exception
On 8 янв, 22:03, "Chris Rebert" wrote: > On Thu, Jan 8, 2009 at 5:53 AM, Sergey Kishchenko wrote: > > In Python empty container equals False in 'if' statements: > > > # prints "It's ok" > > if not []: > > print "It's ok" > > > Let's create a simple Foo class: > > > class Foo: > > pass > > > Now I can use Foo objects in 'if' statements: > > > #prints "Ouch!" > > f=Foo() > > if f: > > print "Ouch!" > > > So, default __nonzero__ impl is to return True. I think, this > > behaviour conflicts with 'Explicit is better than implicit' and > > 'Practicality beats purity' statements. I think, throwing a TypeError > > exception would be better. It will result in more explicit code with > > fewer errors. > > Python has a rich notion of boolean truth compared to other languages. > In this case, by default, non-None objects are considered True. It's a > reasonable default behavior since wanting to differentiate between > None and non-None objects is such a common task. > Also, I've been programming in Python for a long while and have yet to > encounter any bug due to this behavior. > Regarding the Zen, on the contrary, this is a perfect example of > "Practicality beats purity" in action. > > Cheers, > Chris > > -- > Follow the path of the Iguana...http://rebertia.com I agree with you. I completely forget about differentiating between None and non-None objects. I think, thread can be closed. -- http://mail.python.org/mailman/listinfo/python-list
PYTHONPATH var
Hi guys. I have a question regarding runtime definition of the variable PYTHONPATH. Do you know how without modifying of source code change the value for this var. Value stores in the system var sys.path, but the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. We need to change this value which allows to us import scripts first from directory containing newest hotfix scripts without replacing original project scripts. One of the variant is to create script which will modify this var and insert line with import this script into each project script. So the question does another way exist? For example, parameter or argument for python launcher. -- http://mail.python.org/mailman/listinfo/python-list
How to parse a text block?
Hi all.
I have a lot of text blocks that looks like this one
*** Layer 3 Message type: CP-Data
Device: MS1
Time: 19:57:44.71
CP-User data
length : 37
RPDU
Message type indicator (MTI) : (1) RP-DATA
The question is how to parse given text block into a dictionary that looks
like the dictionary given below?
{'Device':'MS1','Time':'Time: 19:57:44.71','CP-User
data':{'length':'37','RPDU':{'Message type indicator (MTI)':'(1) RP-DATA'}}}
Any other thoughts about reading that kind of text?
Thanks,
Sergey
--
http://mail.python.org/mailman/listinfo/python-list
Pickling/Unpickling python Exceptions
Hi all,
I'm migrating code from python 2.4 to python 2.6 and I've got into troubles
with pickling/unpickling python Exceptions.
The following code works fine in 2.4 but not in 2.6.
See Exception1 example
I have found on python mail list similar problem
http://mail.python.org/pipermail/python-list/2009-December/1228773.html
They recommend to use __reduce__. But this does not help as I'm getting
different Exception class after pickle
See Exception_with_reduce example
I also have found possible solution to this problem here
http://bugs.python.org/issue1692335
As a workaround they propose to pass Exception arguments into base class
See Exception2 example
But there is another problem. Constructor is called 2 times which is not
acceptable to me.
Could you please advice on the solution?
--
test program
--
import cPickle
class Exception1(Exception):
def __init__(self,arg1):
print "constructor called"
Exception.__init__(self)
class Exception2(Exception):
def __init__(self,arg1):
print "constructor called"
Exception.__init__(self,arg1)
class Exception_with_reduce(Exception):
def __reduce__(self):
try:
getnewargs = self.__getnewargs__
except AttributeError:
newargs = (self.__class__,)
else:
newargs = (self.__class__,) + getnewargs()
try:
getstate = self.__getstate__
except AttributeError:
state = self.__dict__
else:
state = getstate()
return (Exception, newargs, state)
def __init__(self,arg1):
print "constructor called"
Exception.__init__(self,arg1)
def test(E,args):
try:
print ">>",E.__name__
e = E(*args)
print "- pickling"
s = cPickle.dumps(e)
print "- unpickling"
e = cPickle.loads(s)
if E != e.__class__:
print "! failed: expected %s, got
%s"%(E.__name__,e.__class__.__name__)
except Exception, e:
print "! failed:",e
print "\ finished"
print
import os
if os.path.isfile("/home/ast1/blabla"):
try:
s = open("/home/ast1/blabla","r").read()
e = cPickle.loads(s)
print e.__class__
except Exception, e:
print "error:",e
test(Exception1,[1])
test(Exception2,[1])
test(Exception_with_reduce,[1])
--
--
run results on python 2.6:
--
constructor called
>> Exception1
constructor called
- pickling
- unpickling
! failed: ('__init__() takes exactly 2 arguments (1 given)', , ())
\ finished
>> Exception2
constructor called
- pickling
- unpickling
constructor called
\ finished
>> Exception_with_reduce
constructor called
- pickling
- unpickling
! failed: expected Exception_with_reduce, got Exception
\ finished
--
run results on python 2.4:
--
__main__.Exception2
>> Exception1
constructor called
- pickling
- unpickling
\ finished
>> Exception2
constructor called
- pickling
- unpickling
\ finished
>> Exception_with_reduce
constructor called
- pickling
- unpickling
\ finished
--
http://mail.python.org/mailman/listinfo/python-list
Re: Pickling/Unpickling python Exceptions
Is anybody there to help me out ?
On Thu, Jan 27, 2011 at 4:49 PM, Sergey Lukin wrote:
> Hi all,
>
> I'm migrating code from python 2.4 to python 2.6 and I've got into troubles
> with pickling/unpickling python Exceptions.
> The following code works fine in 2.4 but not in 2.6.
> See Exception1 example
>
> I have found on python mail list similar problem
> http://mail.python.org/pipermail/python-list/2009-December/1228773.html
> They recommend to use __reduce__. But this does not help as I'm getting
> different Exception class after pickle
> See Exception_with_reduce example
>
> I also have found possible solution to this problem here
> http://bugs.python.org/issue1692335
> As a workaround they propose to pass Exception arguments into base class
> See Exception2 example
> But there is another problem. Constructor is called 2 times which is not
> acceptable to me.
>
> Could you please advice on the solution?
>
> --
> test program
> --
> import cPickle
>
> class Exception1(Exception):
> def __init__(self,arg1):
> print "constructor called"
> Exception.__init__(self)
>
> class Exception2(Exception):
> def __init__(self,arg1):
> print "constructor called"
> Exception.__init__(self,arg1)
>
> class Exception_with_reduce(Exception):
> def __reduce__(self):
> try:
> getnewargs = self.__getnewargs__
> except AttributeError:
> newargs = (self.__class__,)
> else:
> newargs = (self.__class__,) + getnewargs()
>
> try:
> getstate = self.__getstate__
> except AttributeError:
> state = self.__dict__
> else:
> state = getstate()
> return (Exception, newargs, state)
>
> def __init__(self,arg1):
> print "constructor called"
> Exception.__init__(self,arg1)
>
> def test(E,args):
> try:
> print ">>",E.__name__
> e = E(*args)
> print "- pickling"
> s = cPickle.dumps(e)
> print "- unpickling"
> e = cPickle.loads(s)
>
> if E != e.__class__:
> print "! failed: expected %s, got
> %s"%(E.__name__,e.__class__.__name__)
> except Exception, e:
> print "! failed:",e
>
> print "\ finished"
> print
>
>
> import os
> if os.path.isfile("/home/ast1/blabla"):
> try:
> s = open("/home/ast1/blabla","r").read()
> e = cPickle.loads(s)
> print e.__class__
> except Exception, e:
> print "error:",e
>
> test(Exception1,[1])
> test(Exception2,[1])
> test(Exception_with_reduce,[1])
> --
>
>
> --
> run results on python 2.6:
> --
>
> constructor called
>
> >> Exception1
> constructor called
> - pickling
> - unpickling
> ! failed: ('__init__() takes exactly 2 arguments (1 given)', '__main__.Exception1'>, ())
> \ finished
>
> >> Exception2
> constructor called
> - pickling
> - unpickling
> constructor called
> \ finished
>
> >> Exception_with_reduce
> constructor called
> - pickling
> - unpickling
> ! failed: expected Exception_with_reduce, got Exception
> \ finished
>
> --
> run results on python 2.4:
> --
>
> __main__.Exception2
> >> Exception1
> constructor called
> - pickling
> - unpickling
> \ finished
>
> >> Exception2
> constructor called
> - pickling
> - unpickling
> \ finished
>
> >> Exception_with_reduce
> constructor called
> - pickling
> - unpickling
> \ finished
>
>
>
>
>
--
Media Center for TomTom - a unique video player from MobilNova.com
Be the first to watch !
http://www.MobilNova.com/
--
http://mail.python.org/mailman/listinfo/python-list
Re: How do I make python test.py work without a syntax error msg?
*when I actually * *type it I get an error msg* Did you type python commands in a bash console? In case you did, you should run python interactive console instead. Just type python in terminal window and than you'll be able interactively run statements. If you have your script saved in a file, for instance, script.py, to run it on your Mac you should type: $ python script.py It would be easier to understand you if you'll post errors messages here. -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I make python test.py work without a syntax error msg?
I see. Your script begins with a string: $ python test.py It's not a valid python code. Maybe you just copied this text to your script accidentally. Try to delete the first string. Can you send a few first strings of your script? On Thu, Aug 19, 2010 at 17:05, Agida Kerimova wrote: > this is what it looks like > > > On Thu, Aug 19, 2010 at 7:01 PM, Agida Kerimova wrote: > >> Hi, I don't know how to work in a non bash console... I typed python in a >> terminal window and all but it didn't work... >> >> >> >> >> >> >> On Thu, Aug 19, 2010 at 5:53 PM, Sergey Smirnov wrote: >> >>> *when I actually * >>> >>> *type it I get an error msg* >>> >>> Did you type python commands in a bash console? In case you did, you >>> should run python interactive console instead. Just type python in terminal >>> window and than you'll be able interactively run statements. >>> >>> If you have your script saved in a file, for instance, script.py, to run >>> it on your Mac you should type: >>> $ python script.py >>> >>> It would be easier to understand you if you'll post errors messages here. >>> >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >> >> >> >> > -- http://mail.python.org/mailman/listinfo/python-list
Subclassing Python's dict
Hi, I subclass builtin 'dict' in my application and experience some problems with it. The whole issue is that I should redefine 'setdefault' and 'update' methods after redefining '__setitem__' or/and '__delitem__', otherwise 'update' and 'setdefault' ignore redefined '__setitem__' and use builtin dict's one so dict looks kinda like a black box. Another guy have reported me that he experiences similar problems with subclassing builtin 'list'. Kind regards, Sergey. -- Написано в почтовом клиенте браузера Opera: http://www.opera.com/mail/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Subclass dynamically
On Sat, 08 Aug 2009 11:12:30 -0600, Robert Dailey wrote: How can you subclass a class from an object?.. Hey, I have a class that I want to have a different base class depending on a parameter that I pass to its __init__method. For example (pseudocode): class MyDerived( self.base ): def __init__( self, base ): self.base = base Something like that... and then I would do this: foo = MyDerived( MyBase() ) Note I'm using Python 3.1 on Windows. Thanks in advance. -- Kind regards, Sergey Simonenko. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to improve this code?
elements_present = lambda seq, match: any(((x in match) for x in seq)) On Mon, 14 Sep 2009 19:08:59 -0600, Oltmans wrote: Hello, Is there someway I can improve the following code(pythonically)? (Copying from IDLE) match=[1,2,3,4,5] def elementsPresent(aList): result=False if not aList: return False for e in aList: if e in match: result=True else: result = False return result elementsPresent([6,7,8,9,5]) # should return True because 5 is present in list named match. Is there somehow I can improve code in elementsPresent()? I'm not a very good programmer but I sense that idea of using a variable named 'result' inside elementsPresent() doesn't sound very good. Any ideas will be highly appreciated. Thanks, Oltmans -- Kind regards, Sergey Simonenko. -- http://mail.python.org/mailman/listinfo/python-list
need reading file in binary mode
this part of my code: f = file(work_dir + filename,'r') n = int(totalSize/recordLenth) i = 0 while i < n: buf = f.read(recordLenth); sometime (when find something like \0A\00\00 in data) returm less bytes then file have. Q: how-to read all data from binary file with constant_length portions? -- http://mail.python.org/mailman/listinfo/python-list
Re: need reading file in binary mode
Problem solved. "Sergey P. Vazulia" <[EMAIL PROTECTED]> ÓÏÏÂÝÉÌ/ÓÏÏÂÝÉÌÁ × ÎÏ×ÏÓÔÑÈ ÓÌÅÄÕÀÝÅÅ: news:[EMAIL PROTECTED] > this part of my code: > > f = file(work_dir + filename,'rb') ^ > n = int(totalSize/recordLenth) > i = 0 > while i < n: > buf = f.read(recordLenth); > > sometime (when find something like \0A\00\00 in data) returm less bytes then > file have. > > Q: how-to read all data from binary file with constant_length portions? > > -- http://mail.python.org/mailman/listinfo/python-list
