Re: idiomatic analogue of Perl's: while (<>) { ... }
Peter Otten wrote:
> A quick look into fileinput.py reveals that it uses readlines() and slurps
> in the complete "file". I'm not sure that was a clever design decision...
Correction:
>>> with open("tmp.txt") as f: lines = f.readlines(0)
...
>>> len(lines)
100
>>> with open("tmp.txt") as f: lines = f.readlines(1)
...
>>> len(lines)
301
>>> len("".join(lines))
8208
So on my system file.readlines(size) stops after about 2**13 bytes which is
not a problem memorywise. Sorry for the confusion.
--
http://mail.python.org/mailman/listinfo/python-list
Constructors...BIIIIG PROBLEM!
Hey guys...
I think we have a problem with my _init_ method and the constructor
When I create a class and its _init_ method and try to create an object of
it outside the class,
Say, something like
class S:
def _init_(self, name=None):
self.name = name
s = S("MyName")
It says that the constructor takes no arguments!! I have to explicitly call
the _init_ method which, I think is not the right way of doing things...
Could you tell me if that is what is supposed to happen or is something
wrong with my code?
--
http://mail.python.org/mailman/listinfo/python-list
Re: Constructors...BIIIIG PROBLEM!
Amogh M S wrote:
> Hey guys...
> I think we have a problem with my _init_ method and the constructor
> When I create a class and its _init_ method and try to create an object of
> it outside the class,
> Say, something like
>
> class S:
>def _init_(self, name=None):
Your __init__() method needs two leading and two trailing underscores.
>self.name = name
> s = S("MyName")
>
> It says that the constructor takes no arguments!! I have to explicitly
> call the _init_ method which, I think is not the right way of doing
> things... Could you tell me if that is what is supposed to happen or is
> something wrong with my code?
--
http://mail.python.org/mailman/listinfo/python-list
Re: Constructors...BIIIIG PROBLEM!
On Sep 1, 2011, at 09:48, Amogh M S wrote:
> Hey guys...
> I think we have a problem with my _init_ method and the constructor
> When I create a class and its _init_ method and try to create an object of it
> outside the class,
> Say, something like
>
> class S:
>def _init_(self, name=None):
>self.name = name
> s = S("MyName")
Two things: Derive your class from object, and the constructor function should
be '__init__', that is, with *two* underscores before and after it. Are you
reading a book or tutorial which does use a badly chosen font which doesn't
distinguish two consecutive underscores well?
class S(object):
def __init__(self, name=None):
self.name = name
s = S("MyName")
print s.name
Greetings,
--
"If you don't know, the thing to do is not to get scared, but to learn." - Ayn
Rand
--
http://mail.python.org/mailman/listinfo/python-list
Re: Constructors...BIIIIG PROBLEM!
hello,
On Thu, Sep 01, 2011 at 10:00:27AM +0200, Michiel Overtoom wrote:
> On Sep 1, 2011, at 09:48, Amogh M S wrote:
[...]
> > class S:
> >def _init_(self, name=None):
> >self.name = name
> > s = S("MyName")
>
> Two things: Derive your class from object,
why's that better than just create a simple class, without
derive?
thanks:
a.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Constructors...BIIIIG PROBLEM!
On Sep 1, 2011, at 10:24, Hegedüs Ervin wrote: > On Thu, Sep 01, 2011 at 10:00:27AM +0200, Michiel Overtoom wrote: >> Derive your class from object, > > why's that better than just create a simple class, without > derive? Amongst other things, fixes to the type system and the method resolution order. http://docs.python.org/reference/datamodel.html#new-style-and-classic-classes http://unspecified.wordpress.com/2010/11/18/pythons-new-classes-vs-old-classes/ http://www.cafepy.com/article/python_types_and_objects/python_types_and_objects.html http://www.python.org/download/releases/2.2.3/descrintro/ Greetings, -- "If you don't know, the thing to do is not to get scared, but to learn." - Ayn Rand -- http://mail.python.org/mailman/listinfo/python-list
Regex to match all trailing whitespace _and_ newlines.
In the terrific Anki [1] application I am trying to remove trailing whitespace from form fields. This is my regex: [\n+\s+]$ Actually, even simplifying it to [\n] or [\r\n] is not matching any newlines! What might be the cause of this? Note that I am not entering the regex in Python code, I am entering it in a regex-supporting Find/Replace dialogue in Anki. Anki is written in Python. Thanks. [1] ankisrs.net -- Dotan Cohen http://gibberish.co.il http://what-is-what.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Regex to match all trailing whitespace _and_ newlines.
Dotan Cohen wrote:
> In the terrific Anki [1] application I am trying to remove trailing
> whitespace from form fields. This is my regex:
> [\n+\s+]$
My attempt:
>>> sub = re.compile(r"\s*?(\n|$)").sub
>>> sub("", "alpha \nbeta \r\n\ngamma\n")
'alphabetagamma'
>>> sub("", "alpha \nbeta \r\n\ngamma")
'alphabetagamma'
>>> sub("", "alpha \nbeta \r\n\ngamma\t")
'alphabetagamma'
--
http://mail.python.org/mailman/listinfo/python-list
Re: Installing WebDAV server
"Dennis Lee Bieber" wrote in message news:[email protected]... > On Wed, 31 Aug 2011 14:18:00 +0200, "Fokke Nauta" > declaimed the following in > gmane.comp.python.general: > >> >> I also configured config.ini in D:\Python27\WebDAV\PyWebDAV\DAVServer >> >> In this file it says: >> "# Auth Database Table, Must exists in database prior to firstrun >> dbtable=webDav >> >> # Create User Database Table and Insert system user" >> >> I created in MySQL a database called webDav. >> I can create a table called User, but how many fields? >> > After looking at the config file. > > I presume you have specified the MySQL username/password Sure > (personally, and out of paranoia, I'd create a webDAV user/password that > only has access rights to the specified webDAV database). > > Next, if you'd read further and didn't take the comment as the > instruction. set > firstrun=1 I did > to tell the server this is the first time it is being run - IT WILL > create the database table (after the first start, reset the flag to 0 to > speed up later runs). It didn't create the table. The database kept empty. > Later in the config file set > mysql_auth=1 > to enable the use of MySQL, and set the admin user/password to what you > plan to have it use. I did > You probably want to set > daemonize=1 > (maybe after first run) I left this to 0. > Oh, and don't forget to set the main data directory and any > port/host changes. I left host and port as they were. The main directory is e:\wwwroot > Start the server - it should connect to MySQL, create the table, and > add the admin user to the table. I started the server with server.py (in D:\Python27\WebDAV\PyWebDAV\DAVServer) -D e:/wwwroot -m -c config.ini The seems to work as I get a login screen in the browser. Later on I changed the ini file: # disable auth noauth = 1 # Enable mysql auth mysql_auth=0 No login screen anymore but I got an error message "fshandler:get_data: e:\wwwroot not found" Fokke -- http://mail.python.org/mailman/listinfo/python-list
Re: Installing WebDAV server
"Paul Kölle" wrote in message news:[email protected]... > Hi, answers below... > > Am 31.08.2011 14:18, schrieb Fokke Nauta: >> "Paul Kölle" wrote in message >> news:[email protected]... >>> Hi, >>> >>> Am 30.08.2011 22:00, schrieb Fokke Nauta: Hi all, I am completely new to Python, but I'm confronted with a problem I can't solve. >>> Welcome to python. >>> This is my question: >>> [snip] >>> I installed Python 3.2.1 and extracted the packages PyWebDAV and PyXML. Now I have a working Python app and 2 directories called PyWebDAV-0.9.4.1 and PyXML-0.8.4. In the PyWebDAV README it says: Installation and setup of server can be as easy as follows: $ easy_install PyWebDAV $ davserver -D /tmp -n -J But of course it doesn't work like that. When I start up Python GUI I see the ">>>" prompt instead of the "$" prompt. But where do I place the two directories? And there is no easy_install script in the PyXML-0.8.4 directory, only a setup.py and ez_setup.py script. I guess the latter is the one to use. But how? >>> You dont install from "Python GUI", use normal cmd, navigate to the >>> folder >>> you downloaded PyXML and PyWebDAV and run "python setup.py install" >>> (python.exe has to be in your PATH). Then you have to find the >>> startup-script "davserver". Find your python installation directory and >>> look into/Tools/Scripts, in my computer this is >>> E:\python27\Tools\Scripts. PyXML and PyWebDAV get installed in the >>> site-packages folder i.e. E:\python27\Lib/site-packages. You might have >>> to >>> look for "davserver" there... >>> >> >> Thanks, Paul. >> >> I ran "python setup.py install" in both the PyXML and PyWebDAV >> directories. >> A lot of things happened and are added into those directories and I guess >> it >> will be OK. >> Next step, the startup-script "davserver". There is no script as such, >> also >> not in \python27\tools\scripts. >> I found 2 similar scripts: >> 1. server.py in D:\Python27\WebDAV\PyWebDAV\DAVServer >> 2. WebDAVServer.py in D:\Python27\WebDAV\PyWebDAV\DAV >> >> Which one is the one to use? > Your install locations look odd, but it might work nevertheless. The > server is in DAVServer\server.py, you can look at the file and you will > see: > > if __name__ == '__main__': > run() > > at the bottom. This is the "entry point" of a python script if called from > the command line. Yes, it was server.py. > My install looks a bit different but I can start the server as follows: > python.exe > E:\Python27\Lib\site-packages\pywebdav-0.9.4.1-py2.7.egg\DAVServer\server.py > -D c:\home -n > WARNING:pywebdav:Authentication disabled! > Listening on localhost (8008) I used server.py e:/wwwroot -m -c config.ini >> I also configured config.ini in D:\Python27\WebDAV\PyWebDAV\DAVServer > I would use a config file outside the program directory and use the -c > or --config switch, run server.py without arguments to see possible > startup options. > >> >> In this file it says: >> "# Auth Database Table, Must exists in database prior to firstrun >> dbtable=webDav >> >> # Create User Database Table and Insert system user" >> >> I created in MySQL a database called webDav. >> I can create a table called User, but how many fields? > Don't know if that's documented somewhere but you can just look at the > code in mysqlauth.py in the same directory as server.py. Seems it needs > three columns, (User,Pass,can_write<0|1>) but I haven't > tried. > I have understood that the database will be configured with the first run, but in my case it didn't. In my congig.ini there was # Create User Database Table and Insert system user # Disable after the Table is created; for performance reasons firstrun=1 Fokke -- http://mail.python.org/mailman/listinfo/python-list
Re: How to daemonize a HTTPServer
On 01/09/2011 04:16, babbu Pehlwan wrote: I have written a http server using BaseHTTPServer module. Now I want to instantiate it through another python script. The issue here is after instantiate the control doesn't come back till the server is running. Please suggest. Sounds like something you could use the multiprocessing module for, but then again my crystal ball is a bit fuzzy today. -- mph -- http://mail.python.org/mailman/listinfo/python-list
Re: Why do class methods always need 'self' as the first parameter?
On Aug 31, 5:35 pm, "T. Goodchild" wrote: > I’m new to Python, and I love it. The philosophy of the language (and > of the community as a whole) is beautiful to me. > > But one of the things that bugs me is the requirement that all class > methods have 'self' as their first parameter. On a gut level, to me > this seems to be at odds with Python’s dedication to simplicity. > > For example, consider Python’s indent-sensitive syntax. Although > other languages didn’t use indentation to specify scope, programmers > always used indentation anyways. Making indentation took a common > practice, made it a rule, and the result was a significantly improved > signal-to-noise ratio in the readability of Python code. > > So why is 'self' necessary on class methods? It seems to me that the > most common practice is that class methods *almost always* operate on > the instance that called them. It would make more sense to me if this > was assumed by default, and for "static" methods (methods that are > part of a class, but never associated with a specific instance) to be > labelled instead. > > Just curious about the rationale behind this part of the language. It's required to make distinction between objects inside the calss and outside of it. Seems pretty logical to me. -- http://mail.python.org/mailman/listinfo/python-list
Invoking profile from command line prevent my sys.path modification
Hi, I am new to profile module, so I am sorry if this is an absolute beginner question. In order to my code to run, I need to add a directory to sys.path. When I invole python -m profile myfile.py, my code won't work, saying that the thing that is supposed to be in path, isn't. Code works fine without profiling. Profiling works if I write it into the file, but I don't prefer doing that, if that is possible. -- http://yasar.serveblog.net/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Why do class methods always need 'self' as the first parameter?
> On Aug 31, 5:35 pm, "T. Goodchild" wrote: >> So why is 'self' necessary on class methods? >> >> Just curious about the rationale behind this part of the language. When instance variables are accessed with the 'self.varname' syntax, it is clear to the programmer that an instance variable is accessed, and not some global. Other languages have weird syntax conventions like that you have to prepend all instance attributes with an '@', and in languages like C++ where there is not necessarily such a syntactic requirement, many programmers use ad-hoc constructs like '_varname' or 'm_varname' to make the distinction clear. >> It seems to me that the >> most common practice is that class methods *almost always* operate on >> the instance that called them. It would make more sense to me if this >> was assumed by default, and for "static" methods (methods that are >> part of a class, but never associated with a specific instance) to be >> labelled instead. Yes, you have a point there. My personal preference would be to optimize for the most common case, while exceptions to the norm are still possible, but perhaps a bit more verbose. Greetings -- "Learn to value yourself, which means: fight for your happiness." - Ayn Rand -- http://mail.python.org/mailman/listinfo/python-list
Re: Why do class methods always need 'self' as the first parameter?
On Aug 31, 8:35 am, "T. Goodchild" wrote: > I’m new to Python, and I love it. The philosophy of the language (and > of the community as a whole) is beautiful to me. > > But one of the things that bugs me is the requirement that all class > methods have 'self' as their first parameter. On a gut level, to me > this seems to be at odds with Python’s dedication to simplicity. > > For example, consider Python’s indent-sensitive syntax. Although > other languages didn’t use indentation to specify scope, programmers > always used indentation anyways. Making indentation took a common > practice, made it a rule, and the result was a significantly improved > signal-to-noise ratio in the readability of Python code. > > So why is 'self' necessary on class methods? It seems to me that the > most common practice is that class methods *almost always* operate on > the instance that called them. It would make more sense to me if this > was assumed by default, and for "static" methods (methods that are > part of a class, but never associated with a specific instance) to be > labelled instead. > > Just curious about the rationale behind this part of the language. I personally consider this to be a wart. Some time ago I did an implementation analysis. The gist is that, if self and cls were made special variables that returned the current instance and class respectively, then the compiler could determine whether a function was an instance or class method. If it then marked the code object appropriately you could get rid of all of the wrappers and the attendant run-time overhead. I've never published the analysis because that train has already left the shed. The earliest it could be considered would be 4.0, which isn't even on the horizon. John Roth -- http://mail.python.org/mailman/listinfo/python-list
Re: [Python-ideas] allow line break at operators
Hi Matt, === From: Matt Joiner The "trailing \" workaround is nonobvious. Wrapping in () is noisy and already heavily used by other syntactical structures. === How about only require indentation to freely break lines? Here is an example: x = firstpart * secondpart #line breaks here + anotherpart #continue by indentation + stillanother #continue on. #until here, another line starts by dedentation y = some_expression - another_one All this would be completely compatible with former code, while having almost free line breaking! Plus, indentation makes it pretty. Really hope Python can have freedom in breaking lines. Yingjie-- http://mail.python.org/mailman/listinfo/python-list
Re: Constructors...BIIIIG PROBLEM!
On Thu, Sep 1, 2011 at 3:04 AM, Michiel Overtoom wrote: > > On Sep 1, 2011, at 10:24, Hegedüs Ervin wrote: > >> On Thu, Sep 01, 2011 at 10:00:27AM +0200, Michiel Overtoom wrote: >>> Derive your class from object, >> >> why's that better than just create a simple class, without >> derive? > > Amongst other things, fixes to the type system and the method resolution > order. > > http://docs.python.org/reference/datamodel.html#new-style-and-classic-classes > http://unspecified.wordpress.com/2010/11/18/pythons-new-classes-vs-old-classes/ > http://www.cafepy.com/article/python_types_and_objects/python_types_and_objects.html > http://www.python.org/download/releases/2.2.3/descrintro/ That is for Python 2. For Python 3, old-style classes are gone, all classes derive from object by default, and writing it explicitly is merely good style for compatibility. -- http://mail.python.org/mailman/listinfo/python-list
Re: fun with nested loops
Hi Steve, Thanks for your comments, I appreciate any input. > Do you think the software in the Apple iPod is "simple"? Or Microsoft No, that's much more complicated that what I am doing. But the iPod probably (?) doesn't get new algorithms based on a specification discussed with non-programmers once a month. I didn't explain enough of what I am doing. This is a fairly complex application that has been running for a few years now, I am just trying to improve it. The code runs a big test machine, that runs >10 individual tests in one run on something like semiconductor chips. The specification of these tests is already very complex, it has the form of the nested loops, for all these configurations try these steps, if they fail try them again n times, if it still doesn't work give up this configuration, if it works continue on to the next steps etc. That's the form the specification is in, and it makes sense and is very readable. In pseudocode it looks like this, I am using @ to give loops a name: @loop1 for c in configurations: @loop2 while not_done: @loop3 while step1_did_not_work: @loop4 for substeps in step1 # loop 4a if hopeless(): continue loop1 # run next configuration if substepsFailed(): restart loop4 # try again if substepsWorked(): break loop3 # go on to next steps, like loop4 That format is fine, everyone involved can understand it, even the people in charge. I'd like to make this executable without changing too much of the form. It would be possible to do this as a FSM, but then you'd loose the line to line correspondence with the specification, and of course some errors always creep in. > non-CS people to be hacking the source code, they only interact with the This is a research setting, so the person running the machine will have to change the source from time to time if he gets a new specification. The specifications are far to complex to be entered into a user interface because of all the loops. > the code by splitting it into functions appropriately, instead of the > spaghetti code you have (apparently) written with jumps all over the place. I wouldn't call the example above spaghetti code in the sense of old Fortran or Basic full of gotos. In a language that can break out of nested loops this is highly structured code. I am not jumping forward to labels, not jumping into functions, not using jumps to replace loops etc. It is like the Fortran example (just to show the syntax, has an infinite loop), everyone can understand that right away, even non Fortran people: 10 loop1: do I=1,3 loop2: do J=1,4 print *,I,J goto 10 ! redo loop1 cycle loop1 exit loop1 enddo loop2 enddo loop1 There is no wild jumping her. The only problem is that Fortran does not allow to restart a loop, so instead of restart loop1 you have to do a goto 10. Otherwise you could do entirely without gotos (like in Ruby with the redo, which is of course much much better) > To take the most obvious, simple example: any time you have a loop that you > might want to redo, the right solution is to put the loop inside a > function, and then "redo the loop" becomes "call the function again". Doesn't work, because it can only redo one level, to break out of the next loop, I'd need exceptions anyway. And having all of these exceptions as gotos doesn't make it more readable. Replacing loop4 by a function makes it possible to replace the restart loop4 by a return, but then I still need an exception to continue loop1 and one to break out of loop4 to indicate that we can go on to the next step. > I suppose that, just possibly, your application really would benefit from > named labels to jump to. But if so, you've stumbled across something rarer > than iridium. Don't think so. I am doing that all of the time in other languages, and I am convinced the named loops (not raw labels+gotos, which are just a necessary evil) are beautiful and clean things. They have a lot of symmetry, break is always break, not sometimes break, sometimes return and sometimes raise breakSomeLoopExcept(). Rewriting the simple Fortran example above in Python would be much, much uglier and more difficult to comprehend. You always call break and continue with a label, searching for that label will tell you right away which loop the break breaks. I am always doing that, even if there is only one loop. break and continue (without label) are IMO (please no flame war about that) worse than goto, at least the goto tells you where it goes, with break/ continue you always have to scan the surroundings to find the right loop. I know I am not the only one who is trying to solve that problem, I was hoping someone has come up with a hack to solve it, like this goto Chis has come up with. I have to play with that a bit. Dan -- http://mail.python.org/mailman/listinfo/python-list
Re: Why do class methods always need 'self' as the first parameter?
On Thu, Sep 1, 2011 at 6:45 AM, John Roth wrote:
> I personally consider this to be a wart. Some time ago I did an
> implementation analysis. The gist is that, if self and cls were made
> special variables that returned the current instance and class
> respectively, then the compiler could determine whether a function was
> an instance or class method. If it then marked the code object
> appropriately you could get rid of all of the wrappers and the
> attendant run-time overhead.
I don't see how you could get rid of the wrappers. Methods would
still need to be bound, somehow, so that code like this will work:
methods = {}
for obj in objs:
if obj.is_flagged:
methods[obj.user_id] = obj.do_work
else:
methods[obj.user_id] = obj.do_other_work
# ...
methods[some_user_id]()
Without method wrappers, how does the interpreter figure out which
instance is bound to the method being called?
Cheers,
Ian
--
http://mail.python.org/mailman/listinfo/python-list
Re: fun with nested loops
Am 01.09.2011 16:05 schrieb Daniel:
In pseudocode it looks like this, I am using @ to give loops a name:
@loop1
for c in configurations:
@loop2
while not_done:
@loop3
while step1_did_not_work:
@loop4
for substeps in step1 # loop 4a
if hopeless(): continue loop1 # run next configuration
if substepsFailed(): restart loop4 # try again
if substepsWorked(): break loop3 # go on to next
steps, like loop4
let me have a try:
def loop(f):
def wrapper(*a, **k):
while True:
try:
ret = f(*a, **k):
return ret
except wrapper.restart:
continue # next try
except wrapper.stop:
return None
return ret
wrapper.restart = type('restart', (Exception,), {})
wrapper.stop = type('stop', (Exception,), {})
return wrapper
@loop
def level1():
for c in configurations:
level2(c)
@loop
def level2():
while not_done:
level3()
@loop
def level3():
while step1_did_not_work:
level4()
@loop
def level4a():
for substeps in step1
if hopeless: raise level2.stop
if substepsFailed: raise level4a.restart
if substepsWorked: return ok
I don't know if I have the levels right, but that should be a way which
works, without too many indentations.
Another approach could be a decorator which immediately runs the given
functions, after adding the needed exception classes.
Thomas
--
http://mail.python.org/mailman/listinfo/python-list
Re: idiomatic analogue of Perl's: while (<>) { ... }
Sahil Tandon writes: > I've been tasked with converting some programs from Perl -> Python, and > am (as will soon be obvious) new to the language. If it's any help, I have usually done handling of standard input line by line with this kind of thing: for inputline in sys.stdin: -- http://mail.python.org/mailman/listinfo/python-list
Listing HAL devices
Hello all
I am trying to write a python script which detects usb pen drive and
copy all the data into my home directory. After bit of searching , i
found these two links 1] http://en.wikibooks.org/wiki/Python_Programming/Dbus
and 2]
http://stackoverflow.com/questions/469243/how-can-i-listen-for-usb-device-inserted-events-in-linux-in-python
. I just copied the wiki program but after running it , i got error
import dbus
class BusListener:
def __init__( self ):
self.bus = dbus.SystemBus()
self.hal_obj =
self.bus.get_object('org.freedesktop.Hal' , '/org/freedesktop/Hal/
Manager' )
print self.proxy
if __name__ == "__main__":
obj = BusListener()
Traceback (most recent call last):
File "Mount.py", line 13, in
obj = BusListener()
File "Mount.py", line 7, in __init__
self.hal_obj = self.bus.get_object('org.freedesktop.Hal' , '/org/
freedesktop/Hal/Manager' )
File "/usr/lib/pymodules/python2.7/dbus/bus.py", line 244, in
get_object
follow_name_owner_changes=follow_name_owner_changes)
File "/usr/lib/pymodules/python2.7/dbus/proxies.py", line 241, in
__init__
self._named_service = conn.activate_name_owner(bus_name)
File "/usr/lib/pymodules/python2.7/dbus/bus.py", line 183, in
activate_name_owner
self.start_service_by_name(bus_name)
File "/usr/lib/pymodules/python2.7/dbus/bus.py", line 281, in
start_service_by_name
'su', (bus_name, flags)))
File "/usr/lib/pymodules/python2.7/dbus/connection.py", line 630, in
call_blocking
message, timeout)
dbus.exceptions.DBusException:
org.freedesktop.DBus.Error.ServiceUnknown: The name
org.freedesktop.Hal was not provided by any .service files
Kindly some one please tell me why i am getting this error .
Thank you
--
http://mail.python.org/mailman/listinfo/python-list
Detecting Ctrl-Alt-Del in Windows
Obviously, this is a windows-based question. I know that Ctrl-Alt-Del is handled deep inside the OS, and I'm not trying to interrupt that. But is there some way to detect that a C-A-D has been pressed? Also, is there a corresponding key-sequence in Mac and Linux? And how might one detect those too? Den -- http://mail.python.org/mailman/listinfo/python-list
Re: Listing HAL devices
On Sep 1, 8:46 pm, mukesh tiwari wrote:
> Hello all
> I am trying to write a python script which detects usb pen drive and
> copy all the data into my home directory. After bit of searching , i
> found these two links 1]http://en.wikibooks.org/wiki/Python_Programming/Dbus
> and 2]http://stackoverflow.com/questions/469243/how-can-i-listen-for-usb-de...
> . I just copied the wiki program but after running it , i got error
>
> import dbus
>
> class BusListener:
> def __init__( self ):
> self.bus = dbus.SystemBus()
> self.hal_obj =
> self.bus.get_object('org.freedesktop.Hal' , '/org/freedesktop/Hal/
> Manager' )
> print self.proxy
>
> if __name__ == "__main__":
> obj = BusListener()
>
> Traceback (most recent call last):
> File "Mount.py", line 13, in
> obj = BusListener()
> File "Mount.py", line 7, in __init__
> self.hal_obj = self.bus.get_object('org.freedesktop.Hal' , '/org/
> freedesktop/Hal/Manager' )
> File "/usr/lib/pymodules/python2.7/dbus/bus.py", line 244, in
> get_object
> follow_name_owner_changes=follow_name_owner_changes)
> File "/usr/lib/pymodules/python2.7/dbus/proxies.py", line 241, in
> __init__
> self._named_service = conn.activate_name_owner(bus_name)
> File "/usr/lib/pymodules/python2.7/dbus/bus.py", line 183, in
> activate_name_owner
> self.start_service_by_name(bus_name)
> File "/usr/lib/pymodules/python2.7/dbus/bus.py", line 281, in
> start_service_by_name
> 'su', (bus_name, flags)))
> File "/usr/lib/pymodules/python2.7/dbus/connection.py", line 630, in
> call_blocking
> message, timeout)
> dbus.exceptions.DBusException:
> org.freedesktop.DBus.Error.ServiceUnknown: The name
> org.freedesktop.Hal was not provided by any .service files
>
> Kindly some one please tell me why i am getting this error .
> Thank you
I am using Ubuntu 11.04 .
--
http://mail.python.org/mailman/listinfo/python-list
Microphone Input
I want to have a microphone input in a python program on cross platform. I don't want to use any third party module rather I want to have a module of my own. Please guide me in this direction. -- http://mail.python.org/mailman/listinfo/python-list
Re: Listing HAL devices
On Thu, Sep 1, 2011 at 9:46 AM, mukesh tiwari wrote: > dbus.exceptions.DBusException: > org.freedesktop.DBus.Error.ServiceUnknown: The name > org.freedesktop.Hal was not provided by any .service files > > Kindly some one please tell me why i am getting this error . > Thank you It looks like you don't have HAL installed. In any case, this is a Ubuntu / DBus issue, not really a Python issue, so you might find better support at those fora. By the way, HAL is deprecated. I believe current best practice is to interface with udev directly, but I don't know exactly what that entails. -- http://mail.python.org/mailman/listinfo/python-list
Re: Help parsing a text file
On Monday, August 29, 2011 1:21:48 PM UTC-5, William Gill wrote: > > I have a text file with XML like records that I need to parse. By XML > like I mean records have proper opening and closing tags. but fields > don't have closing tags (they rely on line ends). Not all fields appear > in all records, but they do adhere to a defined sequence. lxml can parse XML and broken HTML (see http://lxml.de/parsing.html). - James -- Bulbflow: A Python framework for graph databases (http://bulbflow.com) -- http://mail.python.org/mailman/listinfo/python-list
Re: Help parsing a text file
On 9/1/2011 1:58 PM, JT wrote: On Monday, August 29, 2011 1:21:48 PM UTC-5, William Gill wrote: I have a text file with XML like records that I need to parse. By XML like I mean records have proper opening and closing tags. but fields don't have closing tags (they rely on line ends). Not all fields appear in all records, but they do adhere to a defined sequence. lxml can parse XML and broken HTML (see http://lxml.de/parsing.html). - James Thanks to everyone. Though I didn't get what I expected, it made me think more about the reason I need to parse these files to begin with. So I'm going to do some more homework on the overall business application and work backward from there. Once I know how the data fits in the scheme of things, I will create an appropriate abstraction layer, either from scratch, or using one of the existing parsers mentioned, but I won't really know that until I have finished modeling. -- http://mail.python.org/mailman/listinfo/python-list
Re: fun with nested loops
On 9/1/2011 10:05 AM, Daniel wrote: You seems to be requesting one of the options in http://python.org/dev/peps/pep-3136/ Labeled break and continue (The 'Other languages' section omits Fortran.) The rejection post is at http://mail.python.org/pipermail/python-3000/2007-July/008663.html I basically agree with it. Your use case seems to be valid, extreme, and rare. You would probably use the proposed feature responsibly. But you are not everyone. I am not sure what Python-solution I would recommend. I might just stick with whatever you are doing that works for your group. However, I can also understand the desire to improve. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: fun with nested loops
On Wednesday, August 31, 2011 8:51:45 AM UTC-7, Daniel wrote: > Dear All, > > I have some complicated loops of the following form > > for c in configurations: # loop 1 > while nothing_bad_happened: # loop 2 > while step1_did_not_work: # loop 3 > for substeps in step1 # loop 4a > # at this point, we may have to > -leave loop 1 > -restart loop 4 > -skip a step in loop 4 > -continue on to loop 4b > > while step2_did_not_work: # loop 4b > for substeps in step2: > # at this point, we may have to > -leave loop 1 > -restart loop 2 > -restart loop 4b > ... > ...many more loops... > > > I don't see any way to reduce these nested loops logically, they > describe pretty well what the software has to do. > This is a data acquisition application, so on ever line there is > a lot of IO that might fail or make subsequent steps useless or > require a > retry. > > Now every step could need to break out of any of the enclosing loops. I feel your pain. Every language, even Python, has cases where the trade-offs made in the language design make some legitimate task very difficult. In such cases I typically throw out the guidebook and make use of whatever shameless Perlesque thing it takes to keep things manageable. In your example you seem like you're trying to maintain some semblance of structure and good habit; I'd it's probably no longer worth it. Just store the level to break to in a variable, and after every loop check the variable and break if you need to break further. Something like this, for example: break_level = 99 while loop1: while loop2: while loop3: if some_condition: break_level = (1, 2, or 3) break if break_level < 3: break break_level = 99 if break_level < 2: break break_level = 99 Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: Text file with mixed end-of-line terminations
You can use f.read() to read the entire file's contents into a string,
providing the file isn't huge. Then, split on "\r" and replace "\n"
when found.
A simple test:
input_data = "abc\rdef\rghi\r\njkl\r\nmno\r\n"
first_split = input_data.split("\r")
for rec in first_split:
rec = rec.replace("\n", "")
print rec
--
http://mail.python.org/mailman/listinfo/python-list
OSX application built with py2app can't see bundled PySide module?
I'm trying to deploy a Python app on OSX that was built with PySide. py2app
packages it without issue, copying and linking a lot of PySide and Qt files in
the process. But then, when I try to run the built app, I get this error:
Traceback (most recent call last):
File
"/Users/sequence/Desktop/code/dailies/dist/dailies_v02.app/Contents/Resources/__boot__.py",
line 31, in
_run('dailies_v02.py')
File
"/Users/sequence/Desktop/code/dailies/dist/dailies_v02.app/Contents/Resources/__boot__.py",
line 28, in _run
execfile(path, globals(), globals())
File
"/Users/sequence/Desktop/code/dailies/dist/dailies_v02.app/Contents/Resources/dailies_v02.py",
line 9, in
from PySide.QtCore import *
File "PySide/__init__.pyc", line 2, in
File "PySide/private.pyc", line 2, in
File "PySide/QtCore.pyc", line 18, in
File "PySide/QtCore.pyc", line 15, in __load
ImportError: '/usr/lib/python2.6/lib-dynload/PySide/QtCore.so' not found
The weird thing is, QtCore.so IS included in the application bundle: py2app
copied it to the build under
Contents/Resources/lib/python2.6/lib-dynload/PySide/. Is there a reason the
application isn't seeing this?
--
http://mail.python.org/mailman/listinfo/python-list
Re:Python thread
Hi, Why doesn't python threads show an associated PID? On spawning python threads using the threading module I can only see the main thread's pid on using top or ps unix command, no subprocesses are displayed. In otherwords top or ps in not aware of any subprocesses created using threading module in python. Whereas in Java , creating threads will result in separate pid , these subprocesses can be listed using top or ps. Java threads get mapped to the cores in the system. Does it mean that python threads are not mapped to the core in the system. On using multiprocessing module, separate processes are created with unique PID. Any input would be great George -- http://mail.python.org/mailman/listinfo/python-list
Optparse buggy?
Hello,
I'm on python3.2, trying some experiment with OptionParser but no success
>>> from optparse import OptionParser as parser
>>> parser.add_option('-n','--new', dest='new')
>>>
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib/python3.2/optparse.py", line 1001, in add_option
option = self.option_class(*args, **kwargs)
AttributeError: 'str' object has no attribute 'option_class'
>>>
>>>
Any futher item in the option won't make any better.
--
Archlinux on $(uname -a) :P
--
http://mail.python.org/mailman/listinfo/python-list
Re: Optparse buggy?
On Thu, Sep 1, 2011 at 3:12 PM, Fulvio wrote:
> Hello,
>
> I'm on python3.2, trying some experiment with OptionParser but no success
>
from optparse import OptionParser as parser
parser.add_option('-n','--new', dest='new')
> Traceback (most recent call last):
> File "", line 1, in
> File "/usr/lib/python3.2/optparse.py", line 1001, in add_option
> option = self.option_class(*args, **kwargs)
> AttributeError: 'str' object has no attribute 'option_class'
>
> Any futher item in the option won't make any better.
You're trying to call the method from the OptionParser class -- you
need to instantiate it first.
from optparse import OptionParser
parser = OptionParser()
parser.add_option('-n', '--new', dest='new')
...
Cheers,
Ian
--
http://mail.python.org/mailman/listinfo/python-list
Re: Optparse buggy?
On Thu, Sep 1, 2011 at 5:12 PM, Fulvio wrote:
> Hello,
>
> I'm on python3.2, trying some experiment with OptionParser but no success
>
> >>> from optparse import OptionParser as parser
> >>> parser.add_option('-n','--new', dest='new')
>
Here you've imported parser as an alias to the OptionParser class. You can
only use add_option() on an instance of that class. Try this:
from optparse import OptionParser
parser = OptionParser()
parser.add_option('-n','--new',dest='new')
However, I think argparse has replaced optparse since Python 2.7 and
higher...
HTH,
Jason
--
http://mail.python.org/mailman/listinfo/python-list
Re:PythonThreading
Hi, Why doesn't python threads show an associated PID? On spawning python threads using the threading module I can only see the main thread's pid on using top or ps unix command, no subprocesses are displayed. In otherwords top or ps in not aware of any subprocesses created using threading module in python. Whereas in Java , creating threads will result in separate pid , these subprocesses can be listed using top or ps. Java threads get mapped to the cores in the system. Does it mean that python threads are not mapped to the core in the system. On using multiprocessing module, separate processes are created with unique PID. Any input would be great George -- http://mail.python.org/mailman/listinfo/python-list
Re:Threads in Python
Hi, Why doesn't python threads show an associated PID? On spawning python threads using the threading module I can only see the main thread's pid on using top or ps unix command, no subprocesses are displayed. In otherwords top or ps in not aware of any subprocesses created using threading module in python. Whereas in Java , creating threads will result in separate pid , these subprocesses can be listed using top or ps. Java threads get mapped to the cores in the system. Does it mean that python threads are not mapped to the core in the system. On using multiprocessing module, separate processes are created with unique PID. Any input would be great George -- http://mail.python.org/mailman/listinfo/python-list
Re: Optparse buggy?
On 9/1/2011 5:12 PM, Fulvio wrote: I'm on python3.2, trying some experiment with OptionParser but no success Do note "The optparse module is deprecated and will not be developed further; development will continue with the argparse module." -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Python thread
On 9/1/2011 5:14 PM, George wrote: Hi, Why doesn't python threads show an associated PID? On spawning python threads using the threading module I can only see the main thread's pid on using top or ps unix command, no subprocesses are displayed. In otherwords top or ps in not aware of any subprocesses created using threading module in python. Perhaps because threads are not subprocesses? Whereas in Java , creating threads will result in separate pid , these subprocesses can be listed using top or ps. Java threads get mapped to the cores in the system. Does it mean that python threads are not mapped to the core in the system. They all run on the same core. On using multiprocessing module, separate processes are created with unique PID. That is why multiprocessing was added. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Python thread
So what exactly does threading module do, if it doesn't create a subprocess. Does each thread have its own stack and PC. What advantage would a threading module provide over sequential execution. On 01/09/2011 22:54, "Terry Reedy" wrote: > On 9/1/2011 5:14 PM, George wrote: >> Hi, >> Why doesn't python threads show an associated PID? On spawning python >> threads using the threading module I can only see the main thread's pid on >> using top or ps unix command, no subprocesses are displayed. In otherwords >> top or ps in not aware of any subprocesses created using threading module in >> python. > > Perhaps because threads are not subprocesses? > >> Whereas in Java , creating threads will result in separate pid , these >> subprocesses can be listed using top or ps. Java threads get mapped to the >> cores in the system. >> >> Does it mean that python threads are not mapped to the core in the system. > > They all run on the same core. > >> On using multiprocessing module, separate processes are created with unique >> PID. > > That is why multiprocessing was added. > -- http://mail.python.org/mailman/listinfo/python-list
RE: Python thread
>So what exactly does threading module do, if it doesn't create a subprocess. >Does each thread have its own stack and PC. >What advantage would a threading module provide over sequential execution. I believe it merely simulates multiple processes through scheduling (like the CPU). >From http://docs.python.org/library/threading.html: CPython implementation >detail: Due to the Global Interpreter Lock, in CPython only one thread can >execute Python code at once (even though certain performance-oriented >libraries might overcome this limitation). If you want your application to >make better of use of the computational resources of multi-core machines, you >are advised to use multiprocessing. However, threading is still an appropriate >model if you want to run multiple I/O-bound tasks simultaneously. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. -- http://mail.python.org/mailman/listinfo/python-list
Re: Threads in Python
On 9/1/11 2:45 PM, George Kovoor wrote: > Hi, > Why doesn't python threads show an associated PID? On spawning python > threads using the threading module I can only see the main thread's pid on > using top or ps unix command, no subprocesses are displayed. In otherwords > top or ps in not aware of any subprocesses created using threading module in > python. > > Whereas in Java , creating threads will result in separate pid , these > subprocesses can be listed using top or ps. Java threads get mapped to the > cores in the system. I think you're confused about what threads and subprocesses are. They are completely different mechanisms for concurrent code. Threads never show up on top or ps, in any language ... or the language isn't offering threads. I don't know Java, so I can't really comment on it much, but it may be misusing the 'thread' word, but I somehow doubt it. I suspect you're just mistaken about what Java is offering. Threads are separate operating ..er, chains-of-instructions within a single process... Notably with threads, they share the same address space so you can easily share objects amongst threads, without any copying and with no overhead ... Also notably with threads, this can be dangerous, so you often end up wrapping lots of locks around those shared objects and have to take extreme care to make sure nothing goes haywire. Subprocesses are different; they are a whole, separate process with its own address space and no shared memory (unless you go out of your way to do it manually). Heck, each subprocess can have any number of threads. Anything you want to share between them you have to take special care to set up and do -- multiprocessing exists to make this easier and make subprocesses easier to use, like threads are. They're very distinct. Threads are a lot more lightweight and start up a lot faster, but doing multithreaded programming right with any sort of shared objects is really, really, really hard to get right. Some say you can't. But, in Python, only one thread actually ever executes actual Python code at any given time. This does not actually make threading useless as some people claim; if you're making a lot of calls into C-code, for instance, the lock gets released while said C-code runs and other Python code can continue along. Its just not useful if your program is CPU-bound and wants to take advantage of multiple cores. But there's lots of other reasons to go concurrent. But if you do need lots of CPU power, multiprocessing lets you chew up multiple cores and does so /fairly/ easily. Communication between the processes can be expensive depending on the types of objects you need to pass back and forth, but it depends on how you're designing your app. They're just different ways of achieving concurrency, and the two primary ways Python provides. (Greenlets is another, available as a third-party module; Twisted's asynch dispatching isn't really exactly concurrency, but it does a better job then concurrency does for some operations; someone's always working on coroutines in some fashion or another, which is another kind of concurrency.) Lots of different ways to go concurrent, depending on your needs. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Threads in Python
On 01Sep2011 15:27, Stephen Hansen wrote: | On 9/1/11 2:45 PM, George Kovoor wrote: | > Why doesn't python threads show an associated PID? On spawning python | > threads using the threading module I can only see the main thread's pid on | > using top or ps unix command, no subprocesses are displayed. In otherwords | > top or ps in not aware of any subprocesses created using threading module in | > python. | > | > Whereas in Java , creating threads will result in separate pid , these | > subprocesses can be listed using top or ps. Java threads get mapped to the | > cores in the system. | | I think you're confused about what threads and subprocesses are. They | are completely different mechanisms for concurrent code. Threads never | show up on top or ps, in any language ... or the language isn't offering | threads. I don't know Java, so I can't really comment on it much, but it | may be misusing the 'thread' word, but I somehow doubt it. I suspect | you're just mistaken about what Java is offering. No, you're mistaken about the threading models on offer. Some systems offer a threading model where threads can have distinct process ids; the only real criterion is that they share the same address space. The advantages of separate process ids for threads include letting the OS arrange their scheduling, delivery of signals (on UNIX systems) to a particular thread, ability to use multiple cores. On the flipside, threads with distinct process ids tend to be more expensive to set up and may be more expensive in thread switching. Java has long shipped with multiple threading implementations; IIRC "green threads" is an "all in one process id" model that can be used on any platform. Some use a mix of heavyweight (threads with distinct pids) and lightweight threads. | But, in Python, only one thread actually ever executes actual Python | code at any given time. In CPython this is true. Other implementations like Jython can use other threading models; I'd expect Jython to take a lot of advantage of Java's native threads. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ Seeing my great fault Through darkening blue windows I begin again - Haiku Error Messages http://www.salonmagazine.com/21st/chal/1998/02/10chal2.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Python thread
On Thu, Sep 1, 2011 at 6:21 PM, Prasad, Ramit wrote: >>So what exactly does threading module do, if it doesn't create a subprocess. >>Does each thread have its own stack and PC. >>What advantage would a threading module provide over sequential execution. > > I believe it merely simulates multiple processes through scheduling (like the > CPU). > > >From http://docs.python.org/library/threading.html: CPython implementation > >detail: Due to the Global Interpreter Lock, in CPython only one thread can > >execute Python code at once (even though certain performance-oriented > >libraries might overcome this limitation). If you want your application to > >make better of use of the computational resources of multi-core machines, > >you are advised to use multiprocessing. However, threading is still an > >appropriate model if you want to run multiple I/O-bound tasks simultaneously. > > Ramit Threading is an OS-level construct to allow concurrency within a single process (and address space). Threads are never supposed to be separate processes (they aren't at the C-level, so I don't know what Java is doing here). CPython code has a global interpreter lock which prevents two threads from running Python code at the same time, but they're still useful for asynchronous operations. For example, one thread can be waiting for user input while another thread continues to process data. Other Python implementations such as Jython and IronPython don't have a global interpreter lock so threads can run concurrently (and on different cores in a multi-core machine). > Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology > 712 Main Street | Houston, TX 77002 > work phone: 713 - 216 - 5423 > > > > > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of > securities, accuracy and completeness of information, viruses, > confidentiality, legal privilege, and legal entity disclaimers, > available at http://www.jpmorgan.com/pages/disclosures/email. > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Python thread
On 9/1/2011 6:08 PM, George wrote: So what exactly does threading module do, if it doesn't create a subprocess. Does each thread have its own stack and PC. What advantage would a threading module provide over sequential execution. https://secure.wikimedia.org/wikipedia/en/wiki/Thread_%28computer_science%29 -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Python thread
Am 02.09.2011 00:46, schrieb Benjamin Kaplan: > Threading is an OS-level construct to allow concurrency within a > single process (and address space). Threads are never supposed to be > separate processes (they aren't at the C-level, so I don't know what > Java is doing here). CPython code has a global interpreter lock which > prevents two threads from running Python code at the same time, but > they're still useful for asynchronous operations. For example, one > thread can be waiting for user input while another thread continues to > process data. Other Python implementations such as Jython and > IronPython don't have a global interpreter lock so threads can run > concurrently (and on different cores in a multi-core machine). On Linux threading is implemented with multiple processes. A Linux pthread is a clone of the process created with the clone(2) syscall. [1] Each thread has a PID and an entry in the kernel's process table. Tools like htop can show user land threads as different processes. This may explain the confusion of the OP. He may have seen multiple Java threads as different processes. psutil can list all threads with PIDs. The getpid(2) syscall returns always the PID of the main process, gettid (only available through syscall(SYS_gettid)) returns the PID of the current thread. Christian [1] http://linux.die.net/man/2/clone -- http://mail.python.org/mailman/listinfo/python-list
Re: PythonThreading
Please do not repeatedly post the same thing. Doing so, with different titles, will only annoy people. It takes awhile for a post to show up with whatever news or mail reader you are using. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Detecting Ctrl-Alt-Del in Windows
On Thu, 01 Sep 2011 08:52:49 -0700, Den wrote: > Obviously, this is a windows-based question. I know that Ctrl-Alt-Del > is handled deep inside the OS, and I'm not trying to interrupt that. > But is there some way to detect that a C-A-D has been pressed? Not reliably. You might infer that Ctrl-Alt-Del has been used by the way that certain operations behave, but that's fairly error-prone. > Also, is there a corresponding key-sequence in Mac and Linux? And how > might one detect those too? I don't know about Mac. Linux has some support for Ctrl-Alt-Del on the console, and the optional "Magic SysRq" feature. But there's no easy way to detect these (if the sequence is recognised by the kernel, it's not reported by the usual mechanisms). -- http://mail.python.org/mailman/listinfo/python-list
Re: fun with nested loops
I thought a bit about Carl's and Thomas' proposals, and it gave me an idea how this problem could be approached: Break is relatively easy to implement with a context manager that returns an iterable that throws an exception specific to that context manager: with named_loop(i for i in range(10)) as loop1: for i in loop1: with named_loop(i for i in range(10)) as loop2a: for j in loop2a: loop1._break() # this is easy loop1._continue() # this is difficult # if we _continue here, we need to do a continue right after the with loop2a: if loop1.cont: continue # context manager does not create new scope with named_loop(i for i in range(10)) as loop2b: for j in loop2b: loop1._break() this throws an exception that propagates through all the context managers till it hits the one that made loop1 at that point the exception is caught. Now using the idea of break_levels, something like loop1._continue() should work. It is more difficult, because it should be caught in the last loop before the one that is targeted, loop1._continue throws an exception that is caught in loop2. Then loop1 just continues with the next value. I don't know how loop2 can learn that it is enclosed in loop1. Maybe loop1 could add itself to a global stack on enter and delete itself on exit, or maybe inspect could help? The big problem is that loop1._continue breaks out of loop2a, but then starts to execute loop2b, which we don't want. If loop1 is _continued inside of loop2a, a continue needs to directly follow the loop2a with block. An alternative would be to wrap each sequence of statements in another with statement, I think this is better: for i in loop1: with sequenced_stuff(): with named_loop(i for i in range(10)) as loop2a: for j in loop2a: loop1._continue() # this is caught in sequenced_stuff() with named_loop(i for i in range(10)) as loop2b: for j in loop2b: loop1._break() Loops can even be restarted with a small modification: In a loop like "for i in loop1:" the __iter__ method of loop1 is called. If __iter__ returns a smart iterator that keeps a reference to loop1, then it can be restarted, advanced etc. loop1.restart() would throw an exception that __exits__ all the inner loops and gets caught in the loop just before loop1. Then it resets the iterable that the iterator returned by __iter__ links to, i.e. loop1 restarts. Nice side benefit: loops can have a method peek(n) to look ahead. Thanks for all your input, Dan -- http://mail.python.org/mailman/listinfo/python-list
List comprehension timing difference.
In the following code I create the graph with vertices
sgb-words.txt (the file of 5 letter words from the
stanford graphbase), and an edge if two words differ
by one letter. The two methods I wrote seem to me to
likely perform the same computations, the list comprehension
is faster though (281 seconds VS 305 seconds on my dell mini).
Is the right interpretation of this timing difference
that the comprehension is performed in the lower level
C code?
As this time I have no other conjecture about the cause.
-
import time
import copy
data = map (lambda x: x.strip(), open('sgb-words.txt').readlines())
def d (w1, w2):
count = 0
for idx in range(0,5):
if w1[idx] != w2[idx]:
count += 1
return count
print "creating graph"
t0 = time.clock ()
graph = [[a,b] for a in data for b in data if d(a,b) ==1 and a < b]
t1 = time.clock ()
print "took " + str (t1 - t0) + " seconds."
t0 = time.clock ()
graph2 = []
for i in range (0, len(data)):
for j in range(0,len(data)):
if d(data[i],data[j]) == 1 and i < j:
graph2.append ([i,j])
t1 = time.clock ()
print "took " + str (t1 - t0) + " seconds."
--
http://mail.python.org/mailman/listinfo/python-list
Re: fun with nested loops
Daniel wrote: > That's the form the specification is in, and it makes sense and is > very readable. > In pseudocode it looks like this, I am using @ to give loops a name: > > @loop1 > for c in configurations: > @loop2 > while not_done: > @loop3 > while step1_did_not_work: > @loop4 > for substeps in step1 # loop 4a > if hopeless(): continue loop1 # run next configuration > if substepsFailed(): restart loop4 # try again > if substepsWorked(): break loop3 # go on to next > steps, like loop4 > > That format is fine, everyone involved can understand it, even the > people in charge. Well good for them, because I sure as hell don't understand it. To me, that's exactly the sort of thing that Guido was worried about when he rejected the idea of named labels. I'd need to sit down and trace a few loops by hand to grasp it. I wonder how new people coming into the project find it? Personally, I consider two nested loops right on the boundary of my "magic number seven, plus or minus two" short term memory[1]. I prefer to chunk code into functions so that I can ignore details of the inner loops while reasoning about the outer loops, and vice versa. If you feel different, then I'm not being sarcastic when I say "good for you". If you require a 1:1 correspondence between your code and your pseudo-code specification, then maybe Python isn't the right language for this task. Ruby is very Python-like, and has labelled loops. Perl and PHP less so, but can also be quite readable with some discipline. You could also check out Cobra -- their website is down just at the moment, so I can't check whether it has labelled loops. http://cobra-language.com/ [1] Not really magic, and probably more like 4±2. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: List comprehension timing difference.
On 02/09/2011 01:35, Bart Kastermans wrote:
In the following code I create the graph with vertices
sgb-words.txt (the file of 5 letter words from the
stanford graphbase), and an edge if two words differ
by one letter. The two methods I wrote seem to me to
likely perform the same computations, the list comprehension
is faster though (281 seconds VS 305 seconds on my dell mini).
Is the right interpretation of this timing difference
that the comprehension is performed in the lower level
C code?
As this time I have no other conjecture about the cause.
-
import time
import copy
data = map (lambda x: x.strip(), open('sgb-words.txt').readlines())
def d (w1, w2):
count = 0
for idx in range(0,5):
if w1[idx] != w2[idx]:
count += 1
return count
print "creating graph"
t0 = time.clock ()
graph = [[a,b] for a in data for b in data if d(a,b) ==1 and a< b]
t1 = time.clock ()
print "took " + str (t1 - t0) + " seconds."
t0 = time.clock ()
graph2 = []
for i in range (0, len(data)):
for j in range(0,len(data)):
if d(data[i],data[j]) == 1 and i< j:
graph2.append ([i,j])
t1 = time.clock ()
print "took " + str (t1 - t0) + " seconds."
Are they actually equivalent? Does graph == graph2?
The first version (list comprehension) creates a list of pairs of
values:
[a, b]
whereas the second version (for loops) creates a list of pairs of
indexes:
[i, j]
The second version has subscripting ("data[i]" and "data[j]"), which
will slow it down.
--
http://mail.python.org/mailman/listinfo/python-list
slightly OT -- LaTeX
I asked a question a couple weeks ago about scripting WordPerfect with Python, and a couple respondents suggested LaTeX was very good. Where would I start if I wanted to learn about it? ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: idiomatic analogue of Perl's: while (<>) { ... }
[Thanks to everyone who responded]
Steven D'Aprano wrote:
On Thu, 1 Sep 2011 02:56 pm Sahil Tandon wrote:
%%
# unbuffer STDOUT
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
I've never bothered with unbuffered stdout, but that looks fine to me.
I'm not sure if it is necessary though, because print seems to automatically
flush the buffer after each line in my testing. Unless you're printing
repeatedly to the same line, I'm not sure unbuffered stdout is helpful.
I found it necessary because without reopening sys.stdout with buffering
explicitly turned off, I would have to manually flush the buffer after
each print. This is because the program must reply (via writing to
STDOUT) after parsing each line read via STDIN. If I neither disable
buffering nor manually flush after each print, the program just hangs
instead of printing right away.
# process input, line-by-line, and print responses after parsing input
while 1:
rval = parse(raw_input())
if rval == None:
print('foo')
else:
print('bar')
%%
"while True" is considered slightly more idiomatic (readable), but
otherwise, that seems fine.
Ah, thanks -- I've changed '1' to 'True'.
This works, but while reading the documentation, I thought of using 'for
line in fileinput.input()' in lieu of 'while 1:' construct. This does
not work when debugging the program on the command line -- the script
appears to just hang no matter what is typed into STDIN. I believe this
is because of some internal buffering when using fileinput. Is there a
recommended way to disable such buffering? Am I taking a totally wrong
approach?
I'm not sure anything about fileinput is exactly *recommended*, it's kinda
discouraged on account of being a bit slow. See help(fileinput) at the
interactive prompt.
For what it's worth, the default buffersize for fileinput.input is 0, so if
that doesn't do what you want, I don't think fileinput is the right
solution.
Got it. Based on your and others' response, I will stick with my
existing approach.
--
Sahil Tandon
--
http://mail.python.org/mailman/listinfo/python-list
Re: slightly OT -- LaTeX
On Thu, 1 Sep 2011, Ethan Furman wrote: > I asked a question a couple weeks ago about scripting WordPerfect with Python, > and a couple respondents suggested LaTeX was very good. Where would I start > if I wanted to learn about it? > > ~Ethan~ 1. Leslie Lamport, "LaTeX: A Document Preparation System" - I have used it, learning LaTeX in front of a computer, as I wrote my first document in it. I guess this is a very good book on the subject but I have never tried anything else. 2. http://www.latex-project.org/ http://www.latex-project.org/guides/ http://www.ctan.org/ Regards, Tomasz Rola -- ** A C programmer asked whether computer had Buddha's nature. ** ** As the answer, master did "rm -rif" on the programmer's home** ** directory. And then the C programmer became enlightened... ** ** ** ** Tomasz Rola mailto:[email protected] ** -- http://mail.python.org/mailman/listinfo/python-list
Re: slightly OT -- LaTeX
Ethan Furman writes: > I asked a question a couple weeks ago about scripting WordPerfect with > Python, and a couple respondents suggested LaTeX was very good. Someone (you, or the respondents, or some combination of those) has omitted a few steps there, and what you've said here has become a non sequitur: I can't see the path you've taken from “scripting WordPerfect with Python” to “LaTeX”. How does this relate to Python? (If it relates only to WordPerfect or LaTeX, you're in the wrong forum, so I assume there must be some particular relevance to Python.) > Where would I start if I wanted to learn about it? About LaTeX? http://www.latex-project.org/> seems the obvious answer. If you want something more specific, please be more specific with the question. -- \ “Now Maggie, I’ll be watching you too, in case God is busy | `\ creating tornadoes or not existing.” —Homer, _The Simpsons_ | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Optparse buggy?
In article , Terry Reedy wrote: > Do note "The optparse module is deprecated and will not be developed > further; development will continue with the argparse module." One of the unfortunate things about optparse and argparse is the names. I can never remember which is the new one and which is the old one. It would have been a lot simpler if the new one had been named optparse2 (in the style of unittest2 and urllib2). -- http://mail.python.org/mailman/listinfo/python-list
Re: Optparse buggy?
Terry Reedy wrote: > Do note "The optparse module is deprecated and will not be developed > further; development will continue with the argparse module." Then,do you propose me to opt to argparse? -- Archlinux on $(uname -a) :P F -- http://mail.python.org/mailman/listinfo/python-list
Re: Optparse buggy?
Fulvio writes: > Terry Reedy wrote: > > > Do note "The optparse module is deprecated and will not be developed > > further; development will continue with the argparse module." > > Then,do you propose me to opt to argparse? Without argument, yes; though for now it is opt-in. -- \ “We are no more free to believe whatever we want about God than | `\ we are free to adopt unjustified beliefs about science or | _o__) history […].” —Sam Harris, _The End of Faith_, 2004 | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Calling Script from Command line not working
En Mon, 29 Aug 2011 07:40:06 -0300, Sathish S
escribió:
We created a DLL using cygwin and have written a class based python
module
for the same. We have created a sample script for the class based python
module, that creates an object of the class and calls various methods in
the
class. This Test script works fine while I run it from IDLE. However
when I
run it from command prompt it either hangs or just returns without
executing
the functions. When it returns I do not get a error trace.
When I tried to findout where exactly the issue is happening. the issue
occurs when I try to call the *cygwin_dll_init* method of the
cygwin1.dll .
This cygwin1.dll is actualy a dependency to the DLL we have built. So we
have to load this DLL and call this *cygwin_dll_init* method before
loading
my DLL.
cyg = cdll.LoadLibrary("cygwin1.dll")
cyg.cygwin_dll_init() #hangs or returns here
mydll=cdll.LoadLibrary("my.dll")
mydll.func1()
I'm trying to understand what exactly is the difference, when we call it
IDLE and when we call it from command prompt using the python command. I
will have to get the script working from command prompt as well.
A few comments:
* why do you initialize cygwin1.dll in Python? If it's a dependency of
my.dll, it might be better to load and initialize it there.
* for this function prototype: void cygwin_dll_init(void);
you should declare it using:
cyg = cdll.LoadLibrary("cygwin1.dll")
cyg.restype = None
cyg.cygwin_dll_init() #hangs or returns here
...
Anyway, I don't see why a console application would fail but not inside
IDLE.
--
Gabriel Genellina
--
http://mail.python.org/mailman/listinfo/python-list
Re: Python thread
On Sep 1, 5:54 pm, Terry Reedy wrote: > > Does it mean that python threads are not mapped to the core in the system. > > They all run on the same core. > No, CPython is a native thread implementation, so they'll be scheduled however the kernel sees fit. Only allowing one thread to run at a time doesn't mean they'll always run on the same core. Adam -- http://mail.python.org/mailman/listinfo/python-list
Re: idiomatic analogue of Perl's: while (<>) { ... }
On Thu, 01 Sep 2011 16:02:54 +1000, Steven D'Aprano wrote:
> On Thu, 1 Sep 2011 02:56 pm Sahil Tandon wrote:
>> # process input, line-by-line, and print responses after parsing input
>> while 1:
>> rval = parse(raw_input())
>> if rval == None:
>> print('foo')
>> else:
>> print('bar')
>> %%
> "while True" is considered slightly more idiomatic (readable), but
> otherwise, that seems fine.
Arguably more readable, but arguably less idomatic, is to describe the
actual condition that controls the loop in a string (non-empty strings
are equivalent to True in this context):
while "there is more input":
rval = parse(raw_input())
if real is None:
print('foo')
else:
print('bar')
(Although now that I've said that, this looks like an infinite loop
unless parse, raw_input, or print raises an exception.)
Dan
--
http://mail.python.org/mailman/listinfo/python-list
Re: Python thread
On Sep 1, 5:14 pm, George wrote: > Hi, > Why doesn't python threads show an associated PID? On spawning python > threads using the threading module I can only see the main thread's pid on > using top or ps unix command, no subprocesses are displayed. In otherwords > top or ps in not aware of any subprocesses created using threading module in > python. You probably need to run 'ps axm' or something similar to see to threads associated with a processes on your system. > > Whereas in Java , creating threads will result in separate pid , these > subprocesses can be listed using top or ps. Java threads get mapped to the > cores in the system. No. It depends on your runtime, but if Java uses native threads, it will have the same behavior as Python here. It also doesn't mean they get mapped to cores in the system. All it means is the operating system is responsible for scheduling the threads and managing their lifecycle. Adam -- http://mail.python.org/mailman/listinfo/python-list
Re: slightly OT -- LaTeX
I found http://tobi.oetiker.ch/lshort/lshort.pdf very useful. -- http://mail.python.org/mailman/listinfo/python-list
Re: Threads in Python
On 2011-09-01, Stephen Hansen wrote: > On 9/1/11 2:45 PM, George Kovoor wrote: >> Why doesn't python threads show an associated PID? On spawning >> python threads using the threading module I can only see the main >> thread's pid on using top or ps unix command, no subprocesses are >> displayed. In otherwords top or ps in not aware of any subprocesses >> created using threading module in python. That's because threads are displayed by top/ps in most Linux systems. >> Whereas in Java , creating threads will result in separate pid, these >> subprocesses can be listed using top or ps. Java threads get mapped to the >> cores in the system. If that's on the same system, then those aren't threads. > I think you're confused about what threads and subprocesses are. They > are completely different mechanisms for concurrent code. Threads never > show up on top or ps, in any language... That depends on your threading model. Some versions of Linux using LinuxThreads rather than NPTL will show each thread in top or ps. > or the language isn't offering threads. The difference between threads and processes isn't whether they show up in top or ps. For many years threads showed up in top and ps. They were still threads. But, you're right that on most modern, non-embedded, Linux systems threads don't show up in top or ps. > I don't know Java, so I can't really comment on it much, but it may > be misusing the 'thread' word, but I somehow doubt it. I suspect > you're just mistaken about what Java is offering. Sure sounds like it. -- Grant -- http://mail.python.org/mailman/listinfo/python-list
Re: idiomatic analogue of Perl's: while (<>) { ... }
On 01Sep2011 22:02, Sahil Tandon wrote: | [Thanks to everyone who responded] | | Steven D'Aprano wrote: | >On Thu, 1 Sep 2011 02:56 pm Sahil Tandon wrote: | >>%% | >># unbuffer STDOUT | >>sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) | > | >I've never bothered with unbuffered stdout, but that looks fine to me. | > | >I'm not sure if it is necessary though, because print seems to automatically | >flush the buffer after each line in my testing. Unless you're printing | >repeatedly to the same line, I'm not sure unbuffered stdout is helpful. | | I found it necessary because without reopening sys.stdout with | buffering explicitly turned off, I would have to manually flush the | buffer after each print. This is because the program must reply | (via writing to STDOUT) after parsing each line read via STDIN. If | I neither disable buffering nor manually flush after each print, the | program just hangs instead of printing right away. Yes. Steven was probably testing on a terminal. UNIX stdio buffering is line buffered on a terminal and block buffered otherwise (except for stderr, which is normally unbuffered regardless). So Steven saw stuff flushed on newlines and you would see stuff flushed when you explicitly flush or when the buffer fills (probably doesn't happen for your use because you need a response, and never write enough to fill the buffer). Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ Gentle suggestions being those which are written on rocks of less than 5lbs. - Tracy Nelson in comp.lang.c -- http://mail.python.org/mailman/listinfo/python-list
Re: [Python-ideas] allow line break at operators
I guess the issue here is that you can't tell if an expression is complete without checking the indent of the following line. This is likely not desirable. On Thu, Sep 1, 2011 at 11:43 PM, Yingjie Lan wrote: > Hi Matt, > === > From: Matt Joiner > > The "trailing \" workaround is nonobvious. Wrapping in () is noisy and > already heavily used by other syntactical structures. > === > How about only require indentation > to freely break lines? Here is an example: > x = firstpart * secondpart #line breaks here > + anotherpart #continue by indentation > + stillanother #continue on. > #until here, another line starts by dedentation > y = some_expression - another_one > All this would be completely compatible with former code, while > having almost free line breaking! Plus, indentation makes it pretty. > Really hope Python can have freedom in breaking lines. > Yingjie -- http://mail.python.org/mailman/listinfo/python-list
Re: Optparse buggy?
On Thursday, September 1, 2011 7:16:13 PM UTC-7, Roy Smith wrote: > In article , > Terry Reedy wrote: > > > Do note "The optparse module is deprecated and will not be developed > > further; development will continue with the argparse module." > > One of the unfortunate things about optparse and argparse is the names. > I can never remember which is the new one and which is the old one. It > would have been a lot simpler if the new one had been named optparse2 > (in the style of unittest2 and urllib2). It's easy: "opt"parse parses only "opt"ions (-d and the like), whereas "arg"parse parses all "arg"uments. argparse is the more recent version since it does more. optparse2 would have been a bad name for something that parses more than options. (In fact, although I have some minor philosophical disagreements with optparse's design decisions, the main reason I always recommended using argparse instead was that optparse didn't handle positional arguments. optparse has all these spiffy features with type checking and defaults, but it never occurred to the optparse developers that this stuff would be useful for positional arugments, too. They just dropped the ball there.) Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: [Python-ideas] allow line break at operators
So can be done with this syntax: > x = firstpart * secondpart + #line breaks here > anotherpart + #continue > stillanother #continue on. after a "+" operator the line is clearly not finished yet. Gabriel AHTUNE 2011/9/2 Matt Joiner > I guess the issue here is that you can't tell if an expression is > complete without checking the indent of the following line. This is > likely not desirable. > > On Thu, Sep 1, 2011 at 11:43 PM, Yingjie Lan wrote: > > Hi Matt, > > === > > From: Matt Joiner > > > > The "trailing \" workaround is nonobvious. Wrapping in () is noisy and > > already heavily used by other syntactical structures. > > === > > How about only require indentation > > to freely break lines? Here is an example: > > x = firstpart * secondpart #line breaks here > > + anotherpart #continue by indentation > > + stillanother #continue on. > > #until here, another line starts by dedentation > > y = some_expression - another_one > > All this would be completely compatible with former code, while > > having almost free line breaking! Plus, indentation makes it pretty. > > Really hope Python can have freedom in breaking lines. > > Yingjie > ___ > Python-ideas mailing list > [email protected] > http://mail.python.org/mailman/listinfo/python-ideas > -- http://mail.python.org/mailman/listinfo/python-list
Re: Calling Script from Command line not working
Hey Gabriel,
Thanks a lot for replying. I was able to run this python script from
console/command prompt using cygwin python. I'm not sure whats the
difference between these two versions of python. But it seems to be working.
Searching theough the web i found that having cygwin1.dll could be causing
this issue. So I'm trying to build my DLL using MinGW which will not create
an dependecy DLL's. But I'm stuck up with few more issue in porting few
functions to MinGW.
I'm using Python2.7 and Cygwin Python 2.6.5
*Reply to your comments:*
** why do you initialize cygwin1.dll in Python? If it's a dependency of
my.dll, it might be better to load and initialize it there.*
Yes, cygwin1.dll is actually a dependency to my.dll. hence I'm loading it
and initializing it
** for this function prototype: void cygwin_dll_init(void);*
*you should declare it using:*
I'm doing this as you said. But didn't mention it in my mail
hCyg = cdll.LoadLibrary(CygWinDLL_Name)
hCyg = CDLL(CygWinDLL_Name)
Prototype_Cyg = CFUNCTYPE(c_void_p)
Init = Prototype_Cyg (("cygwin_dll_init", hCyg))
Init.restype = c_void_p
Init()
Thanks,
Sathish
On Fri, Sep 2, 2011 at 7:56 AM, Gabriel Genellina wrote:
> En Mon, 29 Aug 2011 07:40:06 -0300, Sathish S
> escribió:
>
>
> We created a DLL using cygwin and have written a class based python module
>> for the same. We have created a sample script for the class based python
>> module, that creates an object of the class and calls various methods in
>> the
>> class. This Test script works fine while I run it from IDLE. However when
>> I
>> run it from command prompt it either hangs or just returns without
>> executing
>> the functions. When it returns I do not get a error trace.
>>
>> When I tried to findout where exactly the issue is happening. the issue
>> occurs when I try to call the *cygwin_dll_init* method of the cygwin1.dll
>> .
>> This cygwin1.dll is actualy a dependency to the DLL we have built. So we
>> have to load this DLL and call this *cygwin_dll_init* method before
>> loading
>> my DLL.
>>
>>
>> cyg = cdll.LoadLibrary("cygwin1.dll"**)
>> cyg.cygwin_dll_init() #hangs or returns here
>> mydll=cdll.LoadLibrary("my.**dll")
>> mydll.func1()
>> I'm trying to understand what exactly is the difference, when we call it
>> IDLE and when we call it from command prompt using the python command. I
>> will have to get the script working from command prompt as well.
>>
>
> A few comments:
>
> * why do you initialize cygwin1.dll in Python? If it's a dependency of
> my.dll, it might be better to load and initialize it there.
>
> * for this function prototype: void cygwin_dll_init(void);
> you should declare it using:
>
>
> cyg = cdll.LoadLibrary("cygwin1.dll"**)
> cyg.restype = None
>
> cyg.cygwin_dll_init() #hangs or returns here
> ...
>
> Anyway, I don't see why a console application would fail but not inside
> IDLE.
>
> --
> Gabriel Genellina
>
> --
> http://mail.python.org/**mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list
Re: Detecting Ctrl-Alt-Del in Windows
On Thu, 01 Sep 2011 08:52:49 -0700, Den wrote: Also, is there a corresponding key-sequence in Mac and Linux? The nearest equivalent in MacOSX is Command-Option-Escape, which brings up the force-quit dialog. I don't know how deep down in the system it's implemented. It's possible to use SetSystemUIMode to put an app into a "kiosk mode" where force-quitting is disabled, but I don't know whether the app can intercept Command-Option-Escape in that situation and do something else with it. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: Calling Script from Command line not working
One more thing I observed is, while running the script from IDLE it launches
a seperate process of pythonw.exe and I could see this console window poping
up. However while running it from command prompt this does not happens. I
was wondering if the command prompt way of calling the script is not able to
launch this new process, that why it could be hanging.
BTW I'm still trying to get the script running using Python 2.7 from the
command prompt.
Thanks,
Sathish
On Fri, Sep 2, 2011 at 11:47 AM, Sathish S wrote:
> Hey Gabriel,
> Thanks a lot for replying. I was able to run this python script from
> console/command prompt using cygwin python. I'm not sure whats the
> difference between these two versions of python. But it seems to be working.
> Searching theough the web i found that having cygwin1.dll could be causing
> this issue. So I'm trying to build my DLL using MinGW which will not create
> an dependecy DLL's. But I'm stuck up with few more issue in porting few
> functions to MinGW.
>
> I'm using Python2.7 and Cygwin Python 2.6.5
>
> *Reply to your comments:*
>
>
> ** why do you initialize cygwin1.dll in Python? If it's a dependency of
> my.dll, it might be better to load and initialize it there.*
> Yes, cygwin1.dll is actually a dependency to my.dll. hence I'm loading it
> and initializing it
>
> ** for this function prototype: void cygwin_dll_init(void);*
> *you should declare it using:*
> I'm doing this as you said. But didn't mention it in my mail
>
> hCyg = cdll.LoadLibrary(CygWinDLL_Name)
> hCyg = CDLL(CygWinDLL_Name)
> Prototype_Cyg = CFUNCTYPE(c_void_p)
> Init = Prototype_Cyg (("cygwin_dll_init", hCyg))
> Init.restype = c_void_p
> Init()
>
> Thanks,
> Sathish
>
>
>
> On Fri, Sep 2, 2011 at 7:56 AM, Gabriel Genellina
> wrote:
>
>> En Mon, 29 Aug 2011 07:40:06 -0300, Sathish S
>> escribió:
>>
>>
>> We created a DLL using cygwin and have written a class based python
>>> module
>>> for the same. We have created a sample script for the class based python
>>> module, that creates an object of the class and calls various methods in
>>> the
>>> class. This Test script works fine while I run it from IDLE. However when
>>> I
>>> run it from command prompt it either hangs or just returns without
>>> executing
>>> the functions. When it returns I do not get a error trace.
>>>
>>> When I tried to findout where exactly the issue is happening. the issue
>>> occurs when I try to call the *cygwin_dll_init* method of the cygwin1.dll
>>> .
>>> This cygwin1.dll is actualy a dependency to the DLL we have built. So we
>>> have to load this DLL and call this *cygwin_dll_init* method before
>>> loading
>>> my DLL.
>>>
>>>
>>> cyg = cdll.LoadLibrary("cygwin1.dll"**)
>>> cyg.cygwin_dll_init() #hangs or returns here
>>> mydll=cdll.LoadLibrary("my.**dll")
>>> mydll.func1()
>>> I'm trying to understand what exactly is the difference, when we call it
>>> IDLE and when we call it from command prompt using the python command. I
>>> will have to get the script working from command prompt as well.
>>>
>>
>> A few comments:
>>
>> * why do you initialize cygwin1.dll in Python? If it's a dependency of
>> my.dll, it might be better to load and initialize it there.
>>
>> * for this function prototype: void cygwin_dll_init(void);
>> you should declare it using:
>>
>>
>> cyg = cdll.LoadLibrary("cygwin1.dll"**)
>> cyg.restype = None
>>
>> cyg.cygwin_dll_init() #hangs or returns here
>> ...
>>
>> Anyway, I don't see why a console application would fail but not inside
>> IDLE.
>>
>> --
>> Gabriel Genellina
>>
>> --
>> http://mail.python.org/**mailman/listinfo/python-list
>>
>
>
--
http://mail.python.org/mailman/listinfo/python-list
Re: [Python-ideas] allow line break at operators
Hi Gabriel, == From: Gabriel AHTUNE Subject: Re: [Python-ideas] allow line break at operators So can be done with this syntax: > x = firstpart * secondpart + #line breaks here > anotherpart + #continue > stillanother #continue on. after a "+" operator the line is clearly not finished yet. Gabriel AHTUNE == That's good to me too, which I proposed early in this thread. Then somebody would like to have the operator in the beginning of the next line so that it would stand out.Then still another one said that indentation is good here. So I finally proposed line continuation with indentation. Since this is Python, we will live with indentation. Currently indentation in Python starts a new block, but if you view it from the perspective of line breaking, it also function as if the line is continued. The line if condition: do_a(); do_b() can be written as: if condition: #line breaks do_a(); # ';' is optional here do_b() # continue Sounds a pretty natural way to allow free line breaking. Yingjie-- http://mail.python.org/mailman/listinfo/python-list
Re: [Python-ideas] allow line break at operators
Yeah, that might be a challenge for the Python interpreter, for it has to check if the next line is indented or not. But it might be worthwhile to take this trouble, so that the coder has more freedom, and the code is hopefully better to read. From: Matt Joiner To: Yingjie Lan Cc: "[email protected]" ; python-ideas Sent: Friday, September 2, 2011 1:33 PM Subject: Re: [Python-ideas] allow line break at operators I guess the issue here is that you can't tell if an expression is complete without checking the indent of the following line. This is likely not desirable. On Thu, Sep 1, 2011 at 11:43 PM, Yingjie Lan wrote: > Hi Matt, > === > From: Matt Joiner > > The "trailing \" workaround is nonobvious. Wrapping in () is noisy and > already heavily used by other syntactical structures. > === > How about only require indentation > to freely break lines? Here is an example: > x = firstpart * secondpart #line breaks here > + anotherpart #continue by indentation > + stillanother #continue on. > #until here, another line starts by dedentation > y = some_expression - another_one > All this would be completely compatible with former code, while > having almost free line breaking! Plus, indentation makes it pretty. > Really hope Python can have freedom in breaking lines. > Yingjie-- http://mail.python.org/mailman/listinfo/python-list
