Re: How about some syntactic sugar for " __name__ == '__main__' "?
On Thu, Nov 13, 2014 at 6:23 PM, Cameron Simpson wrote: > Indeed. This aspect is a deal breaker for me; I'd never use it. > > I make a point of putting the module's main function right up the top, > immediately after the imports and any "constants" (let's not dither over > that term). I _want_ the main function to in the reader's face when they > visit the module code. All the cogs come later. > > And lots of my modules have "main" functions. Terribly useful. Hmm, I go the other way. As much as possible, I prefer functions to call what's above them, not what's below them - so the main function would always be at the end of the file. The very top of the file should have comments/docstrings etc, then imports, then pure utility functions that don't call on anything else, then "guts" functions, and finally routines that are called externally but never internally (like main). That way, if you're wondering at what some name means, you go to the top of the file and find the first occurrence; that'll usually be its definition. Most people already do this with their imports, putting them all at the top - I like to go further and make it unusual for this not to be the case. (Of course, the nature of live projects and constant editing is that there will be violations of the principle, and I don't code-churn just to fix it. But that's still the ideal.) ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Python: package root, root-node, __init__.py in the package root
I have a package structured like so on the file system: PKG LIBS are stored here: /usr/lib/python3.2/ Pkg-name: foo-1.0.0 1. What is the root directory, or root-node or 'root' of my package? My understanding is that it's: /usr/lib/python3.2/foo-1.0.0/ on the file-system and this is referred to the root of the pkg. 2. Can, foo-1.0.0 contain __init__.py or do i have to do: foo-1.0.0/foo/__init__.py ? Take a look at what this guy is saying on his blog: http://blog.habnab.it/blog/2013/07/21/python-packages-and-you/ --- (bottom of the page) "Your project root should contain a python package, not be a package itself. If you do this, your setup.py will be very confusing (or not work at all) and it will be very difficult to run your code." (top of the page) passacre/__init__.py passacre/__main__.py 3. Could someone elucidate, explain what it is he's talking about? - Don?t directly run modules inside packages "What I mean specifically is doing python passacre/__main__.py, or python passacre/test/test_application.py, or anything else that starts with python passacre/. This will prevent python from knowing where the root of your package is, and so absolute imports and explicit relative imports will fail, or not import the code you think it should be importing." 4. In this particular case, how does the interpreter determine pkg-root? -- https://mail.python.org/mailman/listinfo/python-list
xml problem in parsing the great grandchildren
http://pastebin.com/GCD6J0wd I am stuck here. What I am looking for is description of the system memory, but system has lot of places where class=memory is used and hence i can't use it. i need the one's which has id=bank:0 .. n and collect the decryption of it. I don't have option to use lxml. Computer Satellite A100 TOSHIBA PSB10U-SA10ES1 [REMOVED] 32 SMBIOS version 2.31 DMI version 2.31 SMP specification v1.4 Symmetric Multi-Processing Motherboard MPAD-MSAE Customer Reference Boards Intel Corporation 0 Not Applicable [REMOVED] BIOS Phoenix Technologies LTD 0 1.70 (05/11/2006) 114400 983040 ISA bus PCI bus PCMCIA/PCCard Plug-and-Play Advanced Power Management BIOS EEPROM can be upgraded BIOS shadowing ESCD Booting from CD-ROM/DVD ACPI USB legacy emulation AGP BIOS boot specification CPU Genuine Intel(R) CPU T1350 @ 1.86GHz Intel Corp. 4 cpu@0 6.14.8 [REMOVED] U1 186700 186700 32 boot processor mathematical co-processor FPU exceptions reporting virtual mode extensions debugging extensions page size extensions time stamp counter model-specific registers 4GB+ memory addressing (Physical Address Extension) machine check exceptions compare and exchange 8-byte on-chip advanced programmable interrupt controller (APIC) memory type range registers page global enable machine check architecture conditional move instruction debug trace and EMON store MSRs thermal control (ACPI) multimedia extensions (MMX) fast floating point save/restore streaming SIMD extensions (SSE) streaming SIMD extensions (SSE2) self-snoop thermal interrupt and status pending break event CPU Frequency scaling L1 cache 5 L1 Cache 16384 16384 Asynchronous Internal Write-back L2 cache 6 L2 Cache 2097152 Burst External Write-back System Memory 12 System board or motherboard 2147483648 2147483648 SODIMM DDR Synchronous 0 M1 1073741824 32 SODIMM DDR Synchronous 1 M2 1073741824 32 Host bridge Mobile 945GM/PM/GMS, 943/940GML and 945GT Express Memory Controller Hub Intel Corporation 100 pci@:00:00.0 03 32 3300 VGA compatible controller Mobile 945GM/GMS, 943/940GML Express Integrated Graphics Controller Intel Corporation 2 pci@:00:02.0 03 32 3300 Message Signalled Interrupts Power Management bus mastering PCI capabilities listing extension ROM Display controller Mobile 945GM/GMS/GME, 943/940GML Express Integrated Graphics Controller Intel Corporation 2.1 pci@:00:02.1 03 32 3300 Power Management bus mastering PCI capabilities listing Audio device N10/ICH 7 Family High Definition Audio Controller Intel Corporation 1b pci@:00:1b.0 02 64 3300 Power Management Message Signalled Interrupts PCI Express bus mastering PCI capabilities listing PCI bridge N10/ICH 7 Family PCI Express Port 1 Intel Corporation 1c pci@:00:1c.0 02 32 3300 PCI Express Message Signalled Interrupts Power Management bus mastering PCI capabilities listing PCI bridge N10/ICH 7 Family PCI Express Port 2 Intel Corporation 1c.1 pci@:00:1c.1 02 32 3300 PCI Express Message Signalled Interrupts Power Management bus mastering PCI capabilities listing
Re: How about some syntactic sugar for " __name__ == '__main__' "?
On 13Nov2014 19:04, Chris Angelico wrote: On Thu, Nov 13, 2014 at 6:23 PM, Cameron Simpson wrote: Indeed. This aspect is a deal breaker for me; I'd never use it. I make a point of putting the module's main function right up the top, immediately after the imports and any "constants" (let's not dither over that term). I _want_ the main function to in the reader's face when they visit the module code. All the cogs come later. And lots of my modules have "main" functions. Terribly useful. Hmm, I go the other way. As much as possible, I prefer functions to call what's above them, not what's below them - so the main function would always be at the end of the file. [...] My view is that if there's a main (i.e. the module implements a small app all on its own, however tiny), then the main program logic should come first. The details follow later. For a pureply functional module (utility functions, classes built on them, etc) I tend to go your way. But the main, if there is one, comes first. The very top of the file should have comments/docstrings etc, then imports, then pure utility functions that don't call on anything else, then "guts" functions, and finally routines that are called externally but never internally (like main). That way, if you're wondering at what some name means, you go to the top of the file and find the first occurrence; that'll usually be its definition. Sounds effective. I probably prefer my code (main aside, again) organised the same way. Needless to say, I have a heap of modules that could do with a cleanup along these lines. Cheers, Cameron Simpson If you make people think they're thinking, they'll love you; but if you really make them think, they'll hate you. - Don Marquis -- https://mail.python.org/mailman/listinfo/python-list
Re: How about some syntactic sugar for " __name__ == '__main__' "?
On Thu, Nov 13, 2014 at 7:47 PM, Cameron Simpson wrote: > My view is that if there's a main (i.e. the module implements a small app > all on its own, however tiny), then the main program logic should come > first. The details follow later. Ah, I see. Makes sense. It's kinda like an executable docstring. Still not my preferred style, but makes its own sense. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: xml problem in parsing the great grandchildren
OmPs wrote:
> import xml.etree.ElementTree as ET
>
> inv = open('lshw.xml', 'r')
> inv = inv.read()
> inv = ET.XML(inv)
>
> find_memory =inventory.findall(".//node[@id='bank:*']")
>
> # I am stuck here. What is required is description of the system memory,
> but system has lot of places where class=memory is used and hence i can't
> use it. i need the one's which has id=bank:0 .. n and collect the
> decryption of it.
> I am stuck here. What I am looking for is description of the system
> memory, but system has lot of places where class=memory is used and hence
> i can't use it. i need the one's which has id=bank:0 .. n and collect the
> decryption of it.
>
> I don't have option to use lxml.
Take the candidates and then find criteria the further reduce the matching
nodes until only those are left that you are interested in:
import xml.etree.ElementTree as ET
inv = ET.parse("lshw-a105.xml")
nodes = inv.findall(".//node[@class='memory']")
for node in nodes:
description = node.find("./description")
if description.text == "System Memory":
for subnode in node.findall("./node"):
print(subnode.attrib["id"], subnode.find("./description").text)
break
--
https://mail.python.org/mailman/listinfo/python-list
PyDev 3.9.0 Released
What is PyDev? --- PyDev is an open-source Python IDE on top of Eclipse for Python, Jython and IronPython development. It comes with goodies such as code completion, syntax highlighting, syntax analysis, code analysis, refactor, debug, interactive console, etc. Details on PyDev: http://pydev.org Details on its development: http://pydev.blogspot.com What is LiClipse? --- LiClipse is a PyDev standalone with goodies such as support for Multiple cursors, theming and a number of other languages such as Django Templates, Kivy Language, Mako Templates, Html, Javascript, etc. It's also a commercial counterpart which helps supporting the development of PyDev. Details on LiClipse: http://www.liclipse.com/ Release Highlights: --- * **Important**: PyDev requires Eclipse 3.8 or 4.3 onwards and Java 7! For older versions, keep using PyDev 2.x (use LiClipse: http://www.liclipse.com for a PyDev standalone with all requirements bundled). * **Vertical Indent Guide** is now available (may be customized in PyDev > Editor > Vertical Indent Guide. PyDev-359). * **Minimap** * The horizontal scrollbar is shown by default (again). It's still possible to hide it in the Preferences > PyDev > Editor > Overview Ruler Minimap. * Fixed critical issue where the minimap could lead to a repaint recursion on some Linux versions (reproduced on Ubuntu 12. LiClipse-120). * The PYTHONPATH is now properly passed to PyLint when using an external executable (PyDev-475). * Fixed issue where breakpoints in other editors (i.e.: CDT) where wrongly being handled by PyDev (patch by Danny Yoo. PyDev-482). * Fixed issue doing code-completion for builtins in Jython (PyDev-457). * **Interactive Console** * When doing a code-completion with Ctrl+Space, let tab change the focus instead of doing the tab-enabled completion. * Output given from the backend could end up being editable (PyDev-465). * input() was including the prompt in the input string (PyDev-465). * Debugger console was outputting greeting message when it shouldn't (PyDev-464). * **pep8**: --exclude can now be used in pep8 parameters (patch by Sebastian Elsner. PyDev-466). * **autopep8**: end line delimiter is now being kept (patch by Ben Blank. PyDev-461). * Unittest integration: Making sure we don't import the unittest module before executing pytest (PyDev-455). * Unittest integration: Fix to use the proper encoding when passing stdout/stderr to the java side. * Fixed issue when debugging file without extension (when there was no default editor associated to the file name). * Debugger: getpass properly working with additional arguments (PyDev-460). Cheers, -- Fabio Zadrozny -- Software Developer LiClipse http://www.liclipse.com PyDev - Python Development Environment for Eclipse http://pydev.org http://pydev.blogspot.com -- https://mail.python.org/mailman/listinfo/python-list
Synchronizing a sound with a widget change
Hello, here is a small test code: from tkinter import Tk, Frame from winsound import Beep root = Tk() f = Frame(root, width=300, height=300) f.pack() f.config(bg='Yellow') Beep(2000, 1000) -- I intended to change the frame color to yellow (f.config(bg='Yellow')) and at the same time to emit a sound (Beep(2000, 1000)) But I first have the sound and when the sound is over the window appears. Is there a way to fix that ? I have the idea to run an other thread to emit the sound, but I didn't try yet. Is it the solution ? Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: Synchronizing a sound with a widget change
"ast" a écrit dans le message de news:[email protected]... I have the idea to run an other thread to emit the sound, but I didn't try yet. Is it the solution ? nope, still doesn't work ! --- from tkinter import Tk, Frame from winsound import Beep def mybeep(): Beep(2000, 1000) root = Tk() f = Frame(root, width=300, height=300) f.pack() f.config(bg='Yellow') root.after(1, mybeep) -- https://mail.python.org/mailman/listinfo/python-list
Re: Synchronizing a sound with a widget change
"ast" a écrit dans le message de news:[email protected]... "ast" a écrit dans le message de news:[email protected]... I have the idea to run an other thread to emit the sound, but I didn't try yet. Is it the solution ? nope, still doesn't work ! root.after(1, mybeep) with: f = Frame(root, width=300, height=300) f.pack() f.config(bg='Yellow') root.after(80, mybeep) it works and with: f = Frame(root, width=300, height=300) f.pack() f.config(bg='Yellow') root.after(60, mybeep) it doesn't work I understand that Python takes times to create the root window and to color the frame. It the sound arrives before the end of the drawing, Python goes to the sound emitting,and when finished it goes back to drawing. This is annoying I would like sometuhing stable if possible thx -- https://mail.python.org/mailman/listinfo/python-list
Re: Synchronizing a sound with a widget change
"ast" Wrote in message: > > "ast" a écrit dans le message de > news:[email protected]... >> >> "ast" a écrit dans le message de >> news:[email protected]... >> >>> >>> I have the idea to run an other thread to emit the sound, but I didn't try >>> yet. >>> Is it the solution ? >>> >> >> nope, still doesn't work ! >> > >> root.after(1, mybeep) > > > with: > > f = Frame(root, width=300, height=300) > f.pack() > f.config(bg='Yellow') > root.after(80, mybeep) > > it works and with: > > f = Frame(root, width=300, height=300) > f.pack() > f.config(bg='Yellow') > root.after(60, mybeep) > > it doesn't work > > I understand that Python takes times to create the root > window and to color the frame. It the sound arrives > before the end of the drawing, Python goes to the sound > emitting,and when finished it goes back to drawing. > > This is annoying > I would like sometuhing stable if possible > I don't use Windows, but from what I read, winsound.Beep is a blocking call, and therefore must not be used in the main thread of a gui environment. Once the function is called, no events are processed. It seems like you need winsound.SND_ASYNC -- DaveA -- https://mail.python.org/mailman/listinfo/python-list
Re: Synchronizing a sound with a widget change
"Dave Angel" a écrit dans le message de news:[email protected]... I don't use Windows, but from what I read, winsound.Beep is a blocking call, and therefore must not be used in the main thread of a gui environment. Once the function is called, no events are processed. It seems like you need winsound.SND_ASYNC Yes, you are right. I have to use winsound.PlaySound(sound, flags) with flag = winsound.SND_ASYNC thx -- https://mail.python.org/mailman/listinfo/python-list
Re: How about some syntactic sugar for " __name__ == '__main__' "?
In article , Chris Angelico wrote: > On Thu, Nov 13, 2014 at 7:47 PM, Cameron Simpson wrote: > > My view is that if there's a main (i.e. the module implements a small app > > all on its own, however tiny), then the main program logic should come > > first. The details follow later. > > Ah, I see. Makes sense. It's kinda like an executable docstring. Still > not my preferred style, but makes its own sense. > > ChrisA I generally define a main() routine up near the top, then put if __name__ == '__main__': main() at the bottom. That gives you the best of both worlds; you get to see the main() code up front in the file, but you also get to not worry about what order things are defined. It also means you can import your module and call its main() directly. That's useful for testing, but occasionally for other purposes too. You can't do that with the (detestable) style of putting a whole bunch of code in the body of the "if" statement. -- https://mail.python.org/mailman/listinfo/python-list
Re: [Python-Dev] Dinamically set __call__ method
On Thu, Nov 13, 2014 at 2:20 AM, Gregory Ewing wrote: > Fabio Zadrozny wrote: > >> can someone from python-dev give some background of why that's the way it >> is? >> > > It's because, with new-style classes, a class is also an > instance (of class "type" or a subclass thereof). So > without that rule, it would be ambiguous whether a dunder > method applied to instances of a class or to the class > itself. > > > and if maybe it's something which python-dev would consider worth > >> changing in the future -- not sure how much could break because of that >> though >> > > Something fairly fundamental that would break is classs > instantiation! You instantiate a class by calling it, so if > a(x) were implemented as a.__call__(x), and class C had > a __call__ method, then C() would invoke that method > instead of instantiating C. > > Hi Gregory, Thanks for the explanation -- it still does seem a bit surprising from an end-user point of view, but it does make more sense now :) Best Regards, Fabio -- https://mail.python.org/mailman/listinfo/python-list
Re: How about some syntactic sugar for " __name__ == '__main__' "?
On Fri, Nov 14, 2014 at 12:33 AM, Roy Smith wrote: > ... you also get to not worry > about what order things are defined. That's only as regards the interpreter, though. My point has nothing to do with the order the interpreter sees things, it's all about how they're laid out for humans to read. For that, I prefer to have definitions before use. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: I love assert
On 13/11/14 10:05, Ian Kelly wrote:
On Wed, Nov 12, 2014 at 3:47 PM, Marko Rauhamaa wrote:
Ian Kelly :
Apart from idiomatic style, there is no difference between
# never reached
assert False
raise RuntimeError('Unreachable code reached')
If the purpose is communication, then the comment is most effective,
as it can easily convey anything you want. If the purpose is to detect
programming errors, then the RuntimeError is most effective, as it
will always raise an error in the event it is reached.
assert False is a strange hybrid of the two that is less effective at
both purposes.
You can do;
assert False, "Some comments about why this assert is here"
--
https://mail.python.org/mailman/listinfo/python-list
Re: Synchronizing a sound with a widget change
Hi, You may try to add the sleep(5) after the color change statement. You could adjust the sleep time to let the color change and beep synchroize. Thanks. Yimr Zero From: ast Date: 2014-11-13 18:50 To: python-list Subject: Synchronizing a sound with a widget change Hello, here is a small test code: from tkinter import Tk, Frame from winsound import Beep root = Tk() f = Frame(root, width=300, height=300) f.pack() f.config(bg='Yellow') Beep(2000, 1000) -- I intended to change the frame color to yellow (f.config(bg='Yellow')) and at the same time to emit a sound (Beep(2000, 1000)) But I first have the sound and when the sound is over the window appears. Is there a way to fix that ? I have the idea to run an other thread to emit the sound, but I didn't try yet. Is it the solution ? Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: Communicating with a PHP script (and pretending I'm a browser)
On 13/11/14 03:57, Larry Martell wrote:
We were all making this much harder than it is. I ended up doing this:
wp = urllib.request.urlopen('http://php_page/?' + request.POST.urlencode())
pw = wp.read()
I was about that suggest that actually, just be careful to escape things
properly. Although I would recommend to pass the parameters as request
body rather than as query parameters. Going through the web server via
HTTP is most definitely going to be even more expensive than with pipes,
but if performance is the least of your concern, then this is probably
the easiest way to include things between languages.
Yet another methods of mixing languages is to use iframes and to built
your frontend as HTML with that queries Web APIs with AJAX but this
relies on the client side to do the inclusion.
As your goal is to eventually port an existing site to Python, I would
highly recommend against using Django. Django, as a full-featured
framework, is quite opinionated on how to do things, especially in
regards to database design. While this is great for a new projects as it
enforces certain well-tested patterns, this can be a pain when you need
to use existing tables from the PHP application. Also, if your old
application database access is written in SQL (i.e. with PHP mysql or
mysqli driver), it might be less friction to port to SQLAlchemy Core
rather than jumping straight to a full-fledged ORM, eventually you can
slowly take the next step to port SQLA Core to SQLA ORM. Or you can mix
and match Core and ORM with SQLAlchemy (with some care); Django is much
less flexible about mixing plain SQL with ORM.
--
https://mail.python.org/mailman/listinfo/python-list
Re: ssl error with the python mac binary
On 12 November 2014 19:52, Ned Deily wrote: > In article > , > Paul Wiseman wrote: >> I'm currently using the installer with py2app to make a distributable >> app that targets 10.5+ (including ppc). To save having more than one >> build I use this for all downloads. Although I'm starting to consider >> making a second 32/64 distributable. Are there many major drawbacks >> for distributing this i386/ppc binary for all versions of OSX up 10.9 >> and 10.10? > > For a standalone app, not really. The main difference is that, by using > the older 10.5 ABI, a few functions in the os module are not available > (if they were implemented first in OS X 10.6 or later) and/or they may > work a little differently. AFAIK, the most impactful difference, by > far, is the OpenSSL version difference you have run into. Up to now, I > don't recall any compatibility problems with 10.5 ABI programs running > on later versions of OS X or, for the most part, mixing extension > modules compiled to later ABIs with a 10.5 Python, although there might > be issues with mixing versions of C++ modules (Python and its standard > library do not use C++ themselves). But, of course, there's no > guarantee that something won't break in a future release of OS X. So > far, so good. > Yea, I'm a bit worried that apple will break it on a future release- I think I will start looking into making a second build. I wonder what are the chances they'll make a 64bit only OSX one day? >> That's great news! Thanks for this! I've always found building things >> on mac a huge pain and wasn't much looking forward to the prospect of >> trying to build a 32/ppc python build on a 64 bit 10.10 machine (would >> that even be possible?). > > It's possible: I do it. But I cheat a bit: I have 10.5 running in a > virtual machine on a 10.10 host. In theory, it's possible to build > natively on 10.10. The trick is getting a version of Xcode 3 installed > on 10.10 since support for building ppc archs was removed in Xcode 4. I > also cheat a bit there: I happen to still have copies of Xcode 3.1.4 and > 3.2.6 installed on 10.10 because I made sure to preserve them through > upgrades from 10.6 days. IIRC, directly installing the necessary > components from 3.2.6 on newer systems would require some hacking. Then > you have to be really vigilant that the build never strays from the old > SDK and tools, which is not something we claim to support at the moment. > The VM approach is quite safe and reliable. > I never thought about a VM for this for some reason- I have a few as well for basic testing on older OSX versions. I remember having to re-enable ppc in later versions of Xcode (http://stackoverflow.com/q/5333490/659346) when I was building some extensions for the app. That was a bit of a pain. Thanks for your help though! look forward to the 2.7.9 release :) > -- > Ned Deily, > [email protected] > > -- > https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
Re: [Python-Dev] Dinamically set __call__ method
On 05/11/14 06:15, Roberto Martínez wrote:
The thing with this is tricky. I need the change in the instance,
> not in the class, because I have multiple instances and all of
> them must have different implementations of __call__.
Why not just use functions with closure if that's what you need?
def a(one):
two = 'three'
def mycall(self):
nonlocal two
print 'NEW'
return mycall
Python functions are objects.
The workaround of calling a different method inside __call__
> is not valid for my case because I want to change the *signature*
> of the function also -for introspection reasons.
This seems like they should be two totally separate classes. If the
signature is different, then it violates the substitution principle. If
it violates substitution, then there is no reason why they should be of
the same class.
This was my first approach, but it is not very informative to the user
and I prefer to have arguments with descriptive names. We have to change
__doc__ too, so this is not an ideal solution for me.
I tried to implement __getattribute__, but is not called either. :(
Or you can use an factory function:
def A(p):
def xcall(self):
return 'X'
def ycall(self):
return 'Y'
class _A(object):
__call__ = xcall if p == 'x' else ycall
return _A
>>> A('x')()(), A('y')()()
('X', 'Y')
or plain and simply just use inheritance if you want to pass an
isinstance check:
class A(object):
def __call__(self):
print 'OLD'
class A1(A):
def __call__(self):
print 'NEW'
What exactly, are you trying to do?
--
https://mail.python.org/mailman/listinfo/python-list
Re: Synchronizing a sound with a widget change
"Yimr Zero" Wrote in message:
> body { line-height: 1.5; }blockquote { margin-top: 0px; margin-bottom: 0px;
> margin-left: 0.5em; }body { font-size: 10.5pt; font-family: 'Segoe UI';
> color: rgb(0, 0, 0); line-height: 1.5; }
> Hi,
> You may try to add the sleep(5) after the color change statement. You could
> adjust the sleep time to let the color change and beep synchroize.
> Thanks.
>
But sleep () doesn't have a non blocking version. You'd have to
put it in another thread to get it out of the way.
--
DaveA
--
https://mail.python.org/mailman/listinfo/python-list
netaddr value back to IP
Hi there List, I am trying to get a value back to IP using the netaddr python module. How do I get the value 'ip' back to IP format? how is it done? snip print IPNetwork(v4_peer_ip).value ip = IPNetwork(v4_peer_ip).value + 1 print ip --- snip --- Cheers, Noah -- https://mail.python.org/mailman/listinfo/python-list
Help with Python Multiprocessing
I am having trouble understanding the Multiprocessing module. I need to run three different files 'Worker1' , 'Worker2', 'Worker3' all at once. Currently I am doing this : from multiprocessing import Process import Worker1.py import Worker2.py import Worker3.py p1 = Process(target=Worker1.py) p1.start() p2 = Process(target=Worker2.py) p2.start() p3 = Process(target=Worker3.py) p3.start() But this will only start the 'Worker1'. How do I execute all the three files at once? Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: Help with Python Multiprocessing
On Thursday, November 13, 2014 1:07:56 PM UTC-5, Anurag wrote: > I am having trouble understanding the Multiprocessing module. > I need to run three different files 'Worker1' , 'Worker2', 'Worker3' all at > once. Currently I am doing this : > > from multiprocessing import Process > > import Worker1.py > import Worker2.py > import Worker3.py > > > > p1 = Process(target=Worker1.py) > p1.start() > p2 = Process(target=Worker2.py) > p2.start() > p3 = Process(target=Worker3.py) > p3.start() > > But this will only start the 'Worker1'. How do I execute all the three files > at once? > > Thanks I am using Python 2.7 and each of my 'Worker' has a never ending loop that runs continuously. -- https://mail.python.org/mailman/listinfo/python-list
Re: How about some syntactic sugar for " __name__ == '__main__' "?
On 11/12/2014 01:51 PM, Ian Kelly wrote: On Wed, Nov 12, 2014 at 2:33 PM, Chris Kaynor wrote: A decorator is an interesting idea, and should be easy to implement (only lightly tested): def main(func): if func.__module__ == "__main__": func() return func # The return could be omitted to block the function from being manually called after import. This calls it at the wrong time, though. [...] One decorator that won't call too early is atexit.register(). -- ~Ethan~ -- https://mail.python.org/mailman/listinfo/python-list
Re: Help with Python Multiprocessing
On 2014-11-13 18:10, Anurag wrote:
On Thursday, November 13, 2014 1:07:56 PM UTC-5, Anurag wrote:
I am having trouble understanding the Multiprocessing module.
I need to run three different files 'Worker1' , 'Worker2', 'Worker3' all at
once. Currently I am doing this :
from multiprocessing import Process
import Worker1.py
import Worker2.py
import Worker3.py
p1 = Process(target=Worker1.py)
p1.start()
p2 = Process(target=Worker2.py)
p2.start()
p3 = Process(target=Worker3.py)
p3.start()
But this will only start the 'Worker1'. How do I execute all the three files at
once?
Thanks
I am using Python 2.7 and each of my 'Worker' has a never ending loop that runs
continuously.
The documentation has this example:
from multiprocessing import Process
def f(name):
print 'hello', name
if __name__ == '__main__':
p = Process(target=f, args=('bob',))
p.start()
p.join()
Suppose this is in a module called 'example.py'.
When 'example.py' is run as the main module, it executes:
p = Process(target=f, args=('bob',))
p.start()
The multiprocessing module will _import_ 'example.py' in a new process,
and because it's only imported (and not run as a main module), that
code won't be executed. The multiprocessing module will then call the
'f' function.
The way you've written your module, it'll spawn a new process even when
it's only imported, causing the spawned process to spawn another
process, which will, in turn, spawn another...
--
https://mail.python.org/mailman/listinfo/python-list
Re: Help with Python Multiprocessing
On Thursday, November 13, 2014 10:07:56 AM UTC-8, Anurag wrote: > I am having trouble understanding the Multiprocessing module. > I need to run three different files 'Worker1' , 'Worker2', 'Worker3' all at > once. Currently I am doing this : > > from multiprocessing import Process > > import Worker1.py > import Worker2.py > import Worker3.py > > > > p1 = Process(target=Worker1.py) > p1.start() > p2 = Process(target=Worker2.py) > p2.start() > p3 = Process(target=Worker3.py) > p3.start() > > But this will only start the 'Worker1'. How do I execute all the three files > at once? > > Thanks Do your WorkerX.py files have a main() function or anything like that? If not, they should. Then, you'd set the targets to WorkerX.main. -- https://mail.python.org/mailman/listinfo/python-list
Re: Help with Python Multiprocessing
On 11/13/2014 10:07 AM, Anurag wrote: I am having trouble understanding the Multiprocessing module. I need to run three different files 'Worker1' , 'Worker2', 'Worker3' all at once. Currently I am doing this : from multiprocessing import Process import Worker1.py import Worker2.py import Worker3.py p1 = Process(target=Worker1.py) p1.start() p2 = Process(target=Worker2.py) p2.start() p3 = Process(target=Worker3.py) p3.start() But this will only start the 'Worker1'. How do I execute all the three files at once? Thanks I doubt that is your actual code. Python imports do not include .py extension. Please show us your actual code. (Use cut and paste please.) And then take the time to tell us how you determine only the first is started. Then we can probably help. As an aside: To be sure, one could make the above imports work by having files named py.py and __init__.py in a directory named Worker1 (and the same for directories Worker2 and Worker3). I think it's more likely that you miss-typed the above code. Gary Herron -- https://mail.python.org/mailman/listinfo/python-list
Re: Communicating with a PHP script (and pretending I'm a browser)
In article ,
Lie Ryan wrote:
> On 13/11/14 03:57, Larry Martell wrote:
> > We were all making this much harder than it is. I ended up doing this:
> >
> > wp = urllib.request.urlopen('http://php_page/?' + request.POST.urlencode())
> > pw = wp.read()
You can do this if you want, but it's much easier to use requests
library (http://docs.python-requests.org/). Compared to using the raw
urllib stuff, requests makes it trivial to deal with argument encoding,
cookie management, and a zillion other little details which will drive
you crazy if you try to roll your own with urllib.
--
https://mail.python.org/mailman/listinfo/python-list
Re: How about some syntactic sugar for " __name__ == '__main__' "?
On Thu, Nov 13, 2014 at 11:32 AM, Ethan Furman wrote: > On 11/12/2014 01:51 PM, Ian Kelly wrote: >> >> On Wed, Nov 12, 2014 at 2:33 PM, Chris Kaynor wrote: >>> >>> A decorator is an interesting idea, and should be easy to implement (only >>> lightly tested): >>> >>> def main(func): >>> if func.__module__ == "__main__": >>> func() >>> return func # The return could be omitted to block the function from >>> being manually called after import. >> >> This calls it at the wrong time, though. [...] > > One decorator that won't call too early is atexit.register(). Nice. That feels like an abuse, though. The actual program won't be able to register its own atexit handlers, because the program will already be exiting, and other things decorated with atexit.register might actually be called before the main function. -- https://mail.python.org/mailman/listinfo/python-list
Re: How about some syntactic sugar for " __name__ == '__main__' "?
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 On 11/13/2014 12:33 PM, Ian Kelly wrote: > On Thu, Nov 13, 2014 at 11:32 AM, Ethan Furman wrote: >> On 11/12/2014 01:51 PM, Ian Kelly wrote: >>> >>> On Wed, Nov 12, 2014 at 2:33 PM, Chris Kaynor wrote: A decorator is an interesting idea, and should be easy to implement (only lightly tested): def main(func): if func.__module__ == "__main__": func() return func # The return could be omitted to block the function from being manually called after import. >>> >>> This calls it at the wrong time, though. [...] >> >> One decorator that won't call too early is atexit.register(). > > Nice. That feels like an abuse, though. The actual program won't be able to > register its own atexit handlers, > because the program will already be exiting, and other things decorated with > atexit.register might actually be > called before the main function. It's definitely a niche use-case -- such as a cli-helper lib: import said lib, and when it's decorators are used set the atexit handler to call the lib's __main__ function, which checks that the module name of the decorated function is '__main__', and if it is, run stuff! Hmmm... hopefully that wasn't difficult to explain. ;) - -- ~Ethan~ -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.11 (GNU/Linux) iQIcBAEBAgAGBQJUZRfjAAoJENZ7D1rrH75Nx4IP/3tuR4JhVK6Acv04+DiHm32H BHGmBRZGtXQrHGEBcv8BlvUiztmrHqjV+Lkm78zKF3n9R8Ta9qTeSjqIsjRWUMtR JVraCSH6usUwmcGITXIYKQHdXynl+ylu9p8Hr3NT2aNoICqowVGSvK3Ie1NmJuf3 lJcl8tXiXgUrGCwBwEgdrBKTdaATe4QT9XFQJx1QbXpF3qT1Za5hPYthY3fH/Pd9 Nl9NHyA6F5x4sSO7itD23UtUpnRBHWl7blwsKkBi7ClfacxJMrYjFAMUaxUaiTFF /bygveskmMAZw87ISLtjkmOcKtsi0i2BQSQEjpBDZTiveCD/wyDDhJ+5pmZKzll0 Q+pISt4jG9hkArd+JCCxPuTCCo2xm+cMIB4/oSeONd760u6vURLPUNZ5tmNsRkiZ o0/EwyRhWPZotiLoyi7kDNyfpj/BSKV0A6Ph+M40UXOkTZFUf0E84OFEpB359MTO rIvHDpd6Tzch2Dliuj6UKZ1OOygIZauv2ebmEBHHNDMdsVbhdtTElS1Rh2JtDVyZ tUd67KTmE9CwOPcFIbYKHXGIf4FWDAgeaz9x8RY4UUPaDRlyG1eqSxx8Vob2AG9c MEawmA48JCj52ZeICQf6nnIFdIowFkV7QssUgte3cVfbcMBYnPx/nuJWWMjULo77 WrIUpisDf/juvXn4VtuO =oczI -END PGP SIGNATURE- -- https://mail.python.org/mailman/listinfo/python-list
Re: How about some syntactic sugar for " __name__ == '__main__' "?
On Thu, Nov 13, 2014 at 2:33 PM, Ian Kelly wrote: > ... other things decorated with atexit.register > might actually be called before the main function I don't think that will happen. The atexit module is documented to execute its exit functions in reverse order. What's not documented is the behavior of calling atexit.register() while atexit._run_exitfuncs is running. That's an implementation detail, and though unlikely to change, it might be worthwhile getting that behavior documented. Skip -- https://mail.python.org/mailman/listinfo/python-list
help please: tkinter grid layout is very slow
Hi, I'm trying to toss together an image browser in tkinter, and it is so slow
it is unworkable. Here is my code. Can someone point out why it's so slw?
:-) Thanks
root = Tkinter.Tk()
root.geometry("1000x280+300+300")
label = Tkinter.Button(root, compound=Tkinter.TOP)
label.pack()
numimages = len(image_list)
numcols = 6
numrows = numimages/numcols
if numrows * numcols != numimages:
numrows += 1
frame = Tkinter.Frame(root)
for col in range(numcols):
frame.columnconfigure(col, pad=2)
for row in range(numrows):
frame.rowconfigure(row, pad=2)
print "There are", numimages, "images" # 256 in fact...
for imagenum, (row, col) in enumerate([(row,col) for row in range(numrows) for
col in range(numcols)]):
b = Tkinter.Label(frame, compound = Tkinter.TOP)
b['text'] = os.path.basename(image_list[imagenum])
b['image'] = ImageTk.PhotoImage(Image.open(image_list[imagenum]) )
b.grid(row=row, column = col)
frame.pack()
root.mainloop()
--
https://mail.python.org/mailman/listinfo/python-list
Re: How about some syntactic sugar for " __name__ == '__main__' "?
On Thu, Nov 13, 2014 at 2:44 PM, Skip Montanaro wrote: > What's not documented is > the behavior of calling atexit.register() while atexit._run_exitfuncs > is running. That's an implementation detail, and though unlikely to > change, it might be worthwhile getting that behavior documented. http://bugs.python.org/issue22867 Skip -- https://mail.python.org/mailman/listinfo/python-list
Re: What does zip mean?
Grant Edwards writes: > No, you don't. That's not how a zipper works. Each tooth from side A, > isn't bound with one from side B. It's bound with _two_ of them from > side B. And each of those is in turn bound with an additional tooth > from side A, and so on... > >> In your program you have two lists, whose elements `zip` returns >> bound together in pairs > > What the zipper on a coat does is convert two separate sequences into > a single sequence where the members alternate between the two input > sequences. IOW if we want to do something analogous to a zipper > fastener it should do this: > > zip([a,b,c,d,e,f],[1,2,3,4,5,6]) => [a,1,b,2,c,3,d,4,e,5,f,6] > > Item '1' is bound equally to item 'a' and 'b'. Item 'b' is bound > equally to item '1' and '2'. I love you folks of CLP -- https://mail.python.org/mailman/listinfo/python-list
Re: help please: tkinter grid layout is very slow
On 11/13/2014 3:45 PM, Rich Cook wrote:
Hi, I'm trying to toss together an image browser in tkinter, and it is so slow
it is unworkable. Here is my code. Can someone point out why it's so slw?
:-) Thanks
root = Tkinter.Tk()
root.geometry("1000x280+300+300")
label = Tkinter.Button(root, compound=Tkinter.TOP)
label.pack()
numimages = len(image_list)
numcols = 6
numrows = numimages/numcols
That should be numimages // numcols
if numrows * numcols != numimages:
numrows += 1
frame = Tkinter.Frame(root)
for col in range(numcols):
frame.columnconfigure(col, pad=2)
for row in range(numrows):
frame.rowconfigure(row, pad=2)
print "There are", numimages, "images" # 256 in fact...
for imagenum, (row, col) in enumerate([(row,col) for row in range(numrows) for
col in range(numcols)]):
b = Tkinter.Label(frame, compound = Tkinter.TOP)
b['text'] = os.path.basename(image_list[imagenum])
b['image'] = ImageTk.PhotoImage(Image.open(image_list[imagenum]) )
ImageTk? or Tkinter?
b.grid(row=row, column = col)
frame.pack()
root.mainloop()
--
Terry Jan Reedy
--
https://mail.python.org/mailman/listinfo/python-list
Re: I don't read docs and don't know how to use Google. What does the print function do?
"Clayton Kirkwood" writes: > Although I suspect for a price you could bring all of your > professional programming jobs to somebody here, but I think you > would pay out more than you would make. s/ here/ else/ and your assumption can be falsified -- https://mail.python.org/mailman/listinfo/python-list
How to recover bytes function?
file = open('data.bin', 'rb')
bytes = file.read()
bytes
b'\x00\x00\x00\x02spam\x00\x03?\x9d\xf3\xb6'
records = [bytes([char] * 8) for char in b'spam']
TypeError: 'bytes' object is not callable
How to recover bytes function?
--
https://mail.python.org/mailman/listinfo/python-list
Re: How about some syntactic sugar for " __name__ == '__main__' "?
On Thu, Nov 13, 2014 at 1:44 PM, Skip Montanaro wrote: > On Thu, Nov 13, 2014 at 2:33 PM, Ian Kelly wrote: >> ... other things decorated with atexit.register >> might actually be called before the main function > > I don't think that will happen. The atexit module is documented to > execute its exit functions in reverse order. Right, so if something else gets registered after the main function, it will be called before the main function. > What's not documented is > the behavior of calling atexit.register() while atexit._run_exitfuncs > is running. That's an implementation detail, and though unlikely to > change, it might be worthwhile getting that behavior documented. Since the exit functions are executed in reverse order, anything registered at this time would have to be called before something else that has already been called, so I would expect this to be an error condition. -- https://mail.python.org/mailman/listinfo/python-list
Re: How about some syntactic sugar for " __name__ == '__main__' "?
On Thu, Nov 13, 2014 at 1:53 PM, Skip Montanaro
wrote:
> On Thu, Nov 13, 2014 at 2:44 PM, Skip Montanaro
> wrote:
>> What's not documented is
>> the behavior of calling atexit.register() while atexit._run_exitfuncs
>> is running. That's an implementation detail, and though unlikely to
>> change, it might be worthwhile getting that behavior documented.
>
> http://bugs.python.org/issue22867
In fact it seems the behavior does differ between Python 2.7 and Python 3.4:
$ cat testatexit.py
import atexit
@atexit.register
def main():
atexit.register(goodbye)
@atexit.register
def goodbye():
print("Goodbye")
$ python2 testatexit.py
Goodbye
Goodbye
$ python3 testatexit.py
Goodbye
--
https://mail.python.org/mailman/listinfo/python-list
Re: How to recover bytes function?
On 2014-11-13 22:32, [email protected] wrote: file = open('data.bin', 'rb') bytes = file.read() bytes b'\x00\x00\x00\x02spam\x00\x03?\x9d\xf3\xb6' records = [bytes([char] * 8) for char in b'spam'] TypeError: 'bytes' object is not callable How to recover bytes function? The simple answer: bytes = __builtins__.bytes The smart answer: Don't bind to 'bytes' in the first place! -- https://mail.python.org/mailman/listinfo/python-list
Re: How to recover bytes function?
On Fri, Nov 14, 2014 at 9:32 AM, wrote:
> file = open('data.bin', 'rb')
> bytes = file.read()
> bytes
> b'\x00\x00\x00\x02spam\x00\x03?\x9d\xf3\xb6'
> records = [bytes([char] * 8) for char in b'spam']
> TypeError: 'bytes' object is not callable
>
> How to recover bytes function?
del bytes
ChrisA
--
https://mail.python.org/mailman/listinfo/python-list
A Freudian slip of *EPIC PROPORTIONS*!
Some of the folks on this list have attempted to shame me for not accepting "with open arms", this vile encoding we call Unicode, but i wonder, are they aware of the deepest held beliefs of our very own leader? The other day whilst perusing the idlelib i came across a small but *very* significant line of code. They say a picture is worth a thousand words, well folks, this one short line of code might cause *ANY* picture blush with envy! The line is as follows: uniphooey = str However, without some context, even the more "astute" readers might miss the connection, so allow me to offer the comment that precedes this line: # The parse functions have no idea what to do with # Unicode, so replace all Unicode characters with "x". # This is "safe" so long as the only characters germane # to parsing the structure of Python are 7-bit ASCII. # It's *necessary* because Unicode strings don't have a # .translate() method that supports deletechars. We can obviously intuit that "uni" is short for "unicode", and by attaching "phooey" to unicode the author is making a public statement that he believes "unicode is phooey". But what does "phooey" actually mean? The Merriam Webster online dictionary defines "phooey" as: PHOOEY: used to express disbelief, disappointment, or a strong dislike for something. So now it is blatantly obvious that the author of PyParse does not care for unicode, and from my recollection, it was the great GvR himself that wrote most, if not all, of the code for IDLE and Tkinter. Now that this revelation has seen the light of day, i wonder just how "far apart" myself and the great one might actually be on this unicode business? On the other hand, if the author is not GvR, then he is most likely someone of great importance within the community. In any event, i believe it is high time that the author explain his intentions when using the word "uniphooey", because using any word should not be a crime, but hiding in the shadows whilst a fellow member is being lynched, and not having the balls to stand up and speak of your deeply held beliefs *IS* the highest of all crimes! It is a betrayal of not only your peers, but also of yourself. -- https://mail.python.org/mailman/listinfo/python-list
Re: How to recover bytes function?
On Thursday, November 13, 2014 2:32:47 PM UTC-8, [email protected] wrote: > file = open('data.bin', 'rb') > bytes = file.read() > bytes > b'\x00\x00\x00\x02spam\x00\x03?\x9d\xf3\xb6' > records = [bytes([char] * 8) for char in b'spam'] > TypeError: 'bytes' object is not callable > > How to recover bytes function? So how many times do we have to ask you to tell us your EXPECTED output before you start actually doing that? 'bytes' is a built-in function, but built-in function definitions can be overwritten by redeclaring them. In this case, you're deleting the bytes function by assigning some read data to `bytes`. Don't do that. Either use a variable name other than 'bytes', or recover your bytes function. -DJ -- https://mail.python.org/mailman/listinfo/python-list
Re: Help with Python Multiprocessing
On Thursday, November 13, 2014 2:22:29 PM UTC-5, Gary Herron wrote: > On 11/13/2014 10:07 AM, Anurag wrote: > > I am having trouble understanding the Multiprocessing module. > > I need to run three different files 'Worker1' , 'Worker2', 'Worker3' all at > > once. Currently I am doing this : > > > > from multiprocessing import Process > > > > import Worker1.py > > import Worker2.py > > import Worker3.py > > > > > > > > p1 = Process(target=Worker1.py) > > p1.start() > > p2 = Process(target=Worker2.py) > > p2.start() > > p3 = Process(target=Worker3.py) > > p3.start() > > > > But this will only start the 'Worker1'. How do I execute all the three > > files at once? > > > > Thanks > > I doubt that is your actual code. Python imports do not include .py > extension. Please show us your actual code. (Use cut and paste > please.) And then take the time to tell us how you determine only the > first is started. Then we can probably help. > > As an aside: To be sure, one could make the above imports work by having > files named py.py and __init__.py in a directory named Worker1 (and the > same for directories Worker2 and Worker3). I think it's more likely > that you miss-typed the above code. > > Gary Herron That is the actual code I am using in a file named 'ex.py'. My Worker files are also named with a '.py' extension. When I run my 'ex.py' through a command prompt, the 'Worker1.py' is executed in the same command prompt and starts an infinite loop. It never gets to the 'Worker2.py' part. But I want my Workers to be executed in different command prompts. -- https://mail.python.org/mailman/listinfo/python-list
Re: Help with Python Multiprocessing
On Thursday, November 13, 2014 2:18:50 PM UTC-5, [email protected] wrote: > On Thursday, November 13, 2014 10:07:56 AM UTC-8, Anurag wrote: > > I am having trouble understanding the Multiprocessing module. > > I need to run three different files 'Worker1' , 'Worker2', 'Worker3' all at > > once. Currently I am doing this : > > > > from multiprocessing import Process > > > > import Worker1.py > > import Worker2.py > > import Worker3.py > > > > > > > > p1 = Process(target=Worker1.py) > > p1.start() > > p2 = Process(target=Worker2.py) > > p2.start() > > p3 = Process(target=Worker3.py) > > p3.start() > > > > But this will only start the 'Worker1'. How do I execute all the three > > files at once? > > > > Thanks > > Do your WorkerX.py files have a main() function or anything like that? If > not, they should. Then, you'd set the targets to WorkerX.main. My Worker files have three different functions -- https://mail.python.org/mailman/listinfo/python-list
io.UnsupportedOperation: fileno
import sys for stream in (sys.stdin, sys.stdout, sys.stderr): print(stream.fileno()) io.UnsupportedOperation: fileno -- https://mail.python.org/mailman/listinfo/python-list
Re: io.UnsupportedOperation: fileno
On Thursday, November 13, 2014 3:23:24 PM UTC-8, [email protected] wrote: > import sys > for stream in (sys.stdin, sys.stdout, sys.stderr): >print(stream.fileno()) > > > io.UnsupportedOperation: fileno Yup. That's what I'd expect to see. -- https://mail.python.org/mailman/listinfo/python-list
Re: io.UnsupportedOperation: fileno
What is the problem and how to overcome this problem? -- https://mail.python.org/mailman/listinfo/python-list
Re: A Freudian slip of *EPIC PROPORTIONS*!
On Fri, Nov 14, 2014 at 10:11 AM, Rick Johnson wrote: > # The parse functions have no idea what to do with > # Unicode, so replace all Unicode characters with "x". > # This is "safe" so long as the only characters germane > # to parsing the structure of Python are 7-bit ASCII. > # It's *necessary* because Unicode strings don't have a > # .translate() method that supports deletechars. Sounds to me like the functions that collapse whitespace to single spaces, or turn all letters into "A" and all digits into "9", or lowercase/casefold all alphabetics, or strip diacriticals, or anything else of that nature. It's often simpler to fold equivalencies together before parsing or comparing strings. It doesn't mean you don't respect Unicode; in fact, it proves that you *do*. So if you stop calling Unicode "vile", you might actually learn something. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: help please: tkinter grid layout is very slow
On Fri, Nov 14, 2014 at 7:45 AM, Rich Cook wrote: > print "There are", numimages, "images" # 256 in fact... > for imagenum, (row, col) in enumerate([(row,col) for row in range(numrows) > for col in range(numcols)]): > b = Tkinter.Label(frame, compound = Tkinter.TOP) > b['text'] = os.path.basename(image_list[imagenum]) > b['image'] = ImageTk.PhotoImage(Image.open(image_list[imagenum]) ) You're asking someone somewhere to load 256 images into memory and display them. What's the resolution of these images? Do they need to be scaled/cropped? That can be fairly expensive. How long does it actually take to (a) load all those images, and (b) pack the frame? Try, for instance, commenting out the b.grid() call, to force them all to be loaded but not packed. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: How to recover bytes function?
[email protected] writes: > file = open('data.bin', 'rb') > bytes = file.read() These are both terrible names, not least because they clobber the built-in objects ‘file’ and ‘bytes’. Don't name an object for *or not only for) its data type. Instead, choose names that convey the *purpose* for the object. -- \ “Alternative explanations are always welcome in science, if | `\ they are better and explain more. Alternative explanations that | _o__) explain nothing are not welcome.” —Victor J. Stenger, 2001-11-05 | Ben Finney -- https://mail.python.org/mailman/listinfo/python-list
Re: io.UnsupportedOperation: fileno
On Fri, Nov 14, 2014 at 10:34 AM, wrote: > What is the problem and how to overcome this problem? The problem is that you're posting, with no context, a query relating to a former post which gave scanty information and no indication of what you expected. To overcome this, read this: http://www.catb.org/esr/faqs/smart-questions.html ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: io.UnsupportedOperation: fileno
fileno() in not supported. Is it only in 3.1? What is the workaround? -- https://mail.python.org/mailman/listinfo/python-list
Bad file descriptor
import os os.write(1, b'Hello descriptor world\n') OSError: Bad file descriptor How to give a file descriptor number to this function? How to get a file descriptor number? -- https://mail.python.org/mailman/listinfo/python-list
Re: Bad file descriptor
On Thursday, November 13, 2014 3:40:50 PM UTC-8, [email protected] wrote: > import os > os.write(1, b'Hello descriptor world\n') > OSError: Bad file descriptor > > How to give a file descriptor number to this function? How to get a file > descriptor number? http://bit.ly/1zRWHyq -- https://mail.python.org/mailman/listinfo/python-list
Re: io.UnsupportedOperation: fileno
[email protected] writes: > What is the problem and how to overcome this problem? First, please provide context (just as the previous respondent did), so your message may be understood in the absence of those prior. https://en.wikipedia.org/wiki/Posting_style#Interleaved_style> As to your question: Please describe what you expected, and how the behaviour was different. Unless we know what you think is wrong, we don't know what “the problem” is. -- \ “Sittin' on the fence, that's a dangerous course / You can even | `\ catch a bullet from the peace-keeping force” —Dire Straits, | _o__) _Once Upon A Time In The West_ | Ben Finney -- https://mail.python.org/mailman/listinfo/python-list
fileno() not supported in Python 3.1
import sys for stream in (sys.stdin, sys.stdout, sys.stderr): print(stream.fileno()) io.UnsupportedOperation: fileno Is there a workaround? -- https://mail.python.org/mailman/listinfo/python-list
Re: io.UnsupportedOperation: fileno
[email protected] writes: > fileno() in not supported. It is supported, but it is behaving as the documentation describes https://docs.python.org/3/library/io.html#io.IOBase.fileno>. > Is it only in 3.1? What is the workaround? Expect an exception when you ask for the file descriptor on a stream that does not use a file descriptor. -- \ “Pinky, are you pondering what I'm pondering?” “Well, I think | `\ so, Brain, but ‘apply North Pole’ to what?” —_Pinky and The | _o__) Brain_ | Ben Finney -- https://mail.python.org/mailman/listinfo/python-list
Re: fileno() not supported in Python 3.1
[email protected] writes: > Is there a workaround? Please take the time to gather your thoughts, do not fire off a rapid series of terse scattered questions. What is it you're trying to do? What approach are you intending to take? -- \“I was in Las Vegas, at the roulette table, having a furious | `\ argument over what I considered to be an odd number.” —Steven | _o__) Wright | Ben Finney -- https://mail.python.org/mailman/listinfo/python-list
Re: Bad file descriptor
[email protected] writes: > import os > os.write(1, b'Hello descriptor world\n') > OSError: Bad file descriptor It works fine for me:: >>> import os >>> os.write(1, b'Hello descriptor world\n') Hello descriptor world 23 You don't say which Python, or which version, you're using. In the absence of different information, most of us will assume the latest stable release of CPython. Currently, that is CPython 3.4. -- \ “I am too firm in my consciousness of the marvelous to be ever | `\ fascinated by the mere supernatural …” —Joseph Conrad, _The | _o__) Shadow-Line_ | Ben Finney -- https://mail.python.org/mailman/listinfo/python-list
Re: fileno() not supported in Python 3.1
How to get file descriptor number for the following: sys.stdin sys.stdout sys.stderr It is displaying io.UnsupportedOperation: fileno error Kindly help. -- https://mail.python.org/mailman/listinfo/python-list
Re: A Freudian slip of *EPIC PROPORTIONS*!
On 11/13/2014 6:11 PM, Rick Johnson wrote: # The parse functions have no idea what to do with # Unicode, so replace all Unicode characters with "x". # This is "safe" so long as the only characters germane # to parsing the structure of Python are 7-bit ASCII. # It's *necessary* because Unicode strings don't have a # .translate() method that supports deletechars. uniphooey = str It is customary to attribute quotes to their source. This is from 2.x Lib/idlelib/PyParse.py. The file was committed (and probably written) by David Scherer 2000-08-15. Edits for unicode, including the above, were committed (and perhaps written) by Kurt B. Kaiser on 2001-07-13. I doubt GvR ever saw this code. I expect KBK has changed opinions with respect to unicode in 13 years, as has most everyone else. -- Terry Jan Reedy -- https://mail.python.org/mailman/listinfo/python-list
Re: Bad file descriptor
In article , Ben Finney wrote: > [email protected] writes: > > > import os > > os.write(1, b'Hello descriptor world\n') > > OSError: Bad file descriptor > > It works fine for me:: > > >>> import os > >>> os.write(1, b'Hello descriptor world\n') > Hello descriptor world > 23 > > You don't say which Python, or which version, you're using. In the > absence of different information, most of us will assume the latest > stable release of CPython. Currently, that is CPython 3.4. I don't think this has anything to do with which version of Python he's using. I think all that's happening is (for some unknown reason), fd 1 is closed before his program runs. You can demonstrate this, for example, in bash: $ cat hello.py import os os.write(1, b'Hello descriptor world\n') $ python hello.py Hello descriptor world $ 1<&- python hello.py Traceback (most recent call last): File "hello.py", line 2, in os.write(1, b'Hello descriptor world\n') OSError: [Errno 9] Bad file descriptor You owe the Oracle 5 minutes of his life back and a cookie for making him read enough of the bash manual to figure out the syntax to tell it to close a descriptor. -- https://mail.python.org/mailman/listinfo/python-list
How to get file descriptors of sys.stdin, sys.stdout and sys.stderr?
How to get file descriptors of sys.stdin, sys.stdout and sys.stderr? -- https://mail.python.org/mailman/listinfo/python-list
How to get file descriptors of sys.stdin, sys.stdout and sys.stderr?
How to get file descriptors of sys.stdin, sys.stdout and sys.stderr? -- https://mail.python.org/mailman/listinfo/python-list
Re: How to get file descriptors of sys.stdin, sys.stdout and sys.stderr?
On 11/13/14 7:54 PM, [email protected] wrote: How to get file descriptors of sys.stdin, sys.stdout and sys.stderr? You don't seem to be reading any of the responses you are getting. At the very least, you don't seem to be understanding them, or engaging with the authors. You are misbehaving on this list. Everyone else: I recommend that people stop responding. Satish seems unlikely to improve. -- Ned Batchelder, http://nedbatchelder.com -- https://mail.python.org/mailman/listinfo/python-list
Re: fileno() not supported in Python 3.1
[email protected] writes: > How to get file descriptor number for the following: > sys.stdin > sys.stdout > sys.stderr Why do you need this? What are you intending to do? -- \ “Crime is contagious… if the government becomes a lawbreaker, | `\ it breeds contempt for the law.” —Justice Louis Brandeis | _o__) | Ben Finney -- https://mail.python.org/mailman/listinfo/python-list
Re: io.UnsupportedOperation: fileno
On 13/11/2014 23:34, [email protected] wrote: What is the problem and how to overcome this problem? RTFM. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence -- https://mail.python.org/mailman/listinfo/python-list
Re: Bad file descriptor
On 13/11/2014 23:40, [email protected] wrote: import os os.write(1, b'Hello descriptor world\n') OSError: Bad file descriptor How to give a file descriptor number to this function? How to get a file descriptor number? I suggest getting your cheque book out and paying for the advice you so desperately need. Or follow the advice already given about asking smart questions. Or RTFM. Or simply go away. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence -- https://mail.python.org/mailman/listinfo/python-list
A new Help Vampire? (was Re: (too many threads)
On 11/13/2014 7:51 PM, [email protected] wrote: in 4 different threads How to get file descriptors of sys.stdin, sys.stdout and sys.stderr? fileno() in not supported. Is it only in 3.1? What is the workaround? > io.UnsupportedOperation: fileno > How to give a file descriptor number to this function? How to get a file descriptor number? Satish, you are acting like the variety of troll called a Help Vampire. One of the symptoms is hogging the newsgroup by starting multiple threads a day, often on the same topic. Another is ignoring the advice to read and study the manuals. Another is ignoring advice to read, study, and follow advice on how to ask good questions. Please desist. -- Terry Jan Reedy -- https://mail.python.org/mailman/listinfo/python-list
Re: fileno() not supported in Python 3.1
On 14Nov2014 13:52, Ben Finney wrote: [email protected] writes: How to get file descriptor number for the following: sys.stdin sys.stdout sys.stderr Why do you need this? What are you intending to do? In fairness, who cares? It is a basic and reasonable thing to do. I did it only last night: I wanted to know if stderr was a tty or pipe, versus a regular file, as I wanted to special case some error formatting (loosely speaking, default automatic people-friendliness versus log file verbosity). I know that why people want to do things is important, as they may be choosing the wrong approach. But the above question seems very simple and very basic: he seems unable to get the OS file descriptor number from the standard streams, and this is surprising. I think he even started the thead with almost a transcript of the failure, and backed off the the above abstraction when someone complained. Cheers, Cameron Simpson | Alain van der Heide | This is the way the world ends | | [email protected]| This is the way the world ends | | "The opinions expressed above are mine- | This is the way the world ends | | mineminemine, and you can't have them." | Not with a bang, but with a whi segmentation fault core dumped -- https://mail.python.org/mailman/listinfo/python-list
Re: Python: package root, root-node, __init__.py in the package root
Veek M writes: > I have a package structured like so on the file system: > PKG LIBS are stored here: /usr/lib/python3.2/ > Pkg-name: foo-1.0.0 > > 1. What is the root directory, or root-node or 'root' of my package? My > understanding is that it's: /usr/lib/python3.2/foo-1.0.0/ on the file-system > and this is referred to the root of the pkg. > > 2. Can, foo-1.0.0 contain __init__.py or do i have to do: > foo-1.0.0/foo/__init__.py ? > > > Take a look at what this guy is saying on his blog: > http://blog.habnab.it/blog/2013/07/21/python-packages-and-you/ > > --- > (bottom of the page) > "Your project root should contain a python package, not be a package itself. > If you do this, your setup.py will be very confusing (or not work at all) > and it will be very difficult to run your code." The blog author distinguishes between a project and a package and *recommends* that the package is in a subfolder of its project -- in order to get a simpler "setup.py". Let me clarify the terms "package" and "project" a bit. The "package" is what is used in a Python installation - what is imported into your application. In order to get the "package" installed, other resources are typically required (e.g. installation documentation, dependency specification, "setup.py", ...). The "project" contains the package sources and (most of) the required resources to get the package installed by standard means (e.g. "pip", "easy_install", ...). -- https://mail.python.org/mailman/listinfo/python-list
Python 3.x (beazley): __context__ vs __cause__ attributes in exception handling
In 'Chained Exceptions' - Beazley pg:626
try:
pass
except ValueError as e:
raise SyntaxError('foo bar') from e
-
Here, if ValueError is raised and SyntaxError is then raised.. 'e' contains
__cause__ which points to the ValueError Traceback. He goes on to say:
---
A more subtle example of exception chaining involves exceptions raised
within another exception handler. For example:
def error(msg):
print(m) # Note: typo is intentional (m undefined)
try:
statements
except ValueError as e:
error("Couldn't parse configuration")
---
Here, 'error' generates an inadvertent exception. What i don't understand is
this bit:
--
For implicit chaining, the _ _context_ _ attribute of an exception instance
e contains a reference to previous exception.
-
Why is he saying that 'e' contains a reference in __context__ to the
exception generated by 'error' ?? Is that correct? Surely, the exception
generated by 'error' will refer to 'e'? WTH??
For Implicit errors, there is no 'e'! Additionally, how would you go about
using __context__ if the exception is generated implicitly? Book pages:
imgur.com/bwpYq8T imgur.com/inZQv5J
--
https://mail.python.org/mailman/listinfo/python-list
Re: fileno() not supported in Python 3.1
On 13Nov2014 15:48, [email protected] wrote: import sys for stream in (sys.stdin, sys.stdout, sys.stderr): print(stream.fileno()) io.UnsupportedOperation: fileno Is there a workaround? The first workaround that suggests itself it to use a more modern Python. I've got 3.4.2 here, and it goes: Python 3.4.2 (default, Nov 5 2014, 21:19:51) [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.54)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> for stream in (sys.stdin, sys.stdout, sys.stderr): ... print(stream.fileno()) ... 0 1 2 >>> In short, in 3.4.2 it just works. Cheers, Cameron Simpson Chris Gascoyne, while struggling to program stuff on Microsoft Windows: "I thought people said how bad it was just because they didn't like Microsoft." -- https://mail.python.org/mailman/listinfo/python-list
Re: io.UnsupportedOperation: fileno
On 14Nov2014 10:52, Ben Finney wrote: [email protected] writes: fileno() in not supported. It is supported, but it is behaving as the documentation describes https://docs.python.org/3/library/io.html#io.IOBase.fileno>. Is it only in 3.1? What is the workaround? Expect an exception when you ask for the file descriptor on a stream that does not use a file descriptor. However, in 3.4.2 it does work (well, on MacOSX). Just as well really, as stdin, stdout and stderr do eventually connect to file descriptors... Cheers, Cameron Simpson You wouldn't... ...but you KNOW you could. - Original V65 Commercial -- https://mail.python.org/mailman/listinfo/python-list
Re: How to recover bytes function?
On 13Nov2014 14:32, [email protected] wrote: file = open('data.bin', 'rb') bytes = file.read() bytes b'\x00\x00\x00\x02spam\x00\x03?\x9d\xf3\xb6' records = [bytes([char] * 8) for char in b'spam'] TypeError: 'bytes' object is not callable How to recover bytes function? The best way is not to use "bytes" for something else when you know you will be using the builtin version as well. Using the same name for two things is generally a bad idea. The second, and worse, way is to see the documentation for the "builtins" module. Cheers, Cameron Simpson Madness takes its toll. Please have exact change. - Janice Hanes -- https://mail.python.org/mailman/listinfo/python-list
