Re: Negative array indicies and slice()
On Sunday, October 28, 2012 8:43:30 PM UTC-7, Ian wrote:
> On Sun, Oct 28, 2012 at 9:12 PM, wrote:
>
> > The slice operator does not give any way (I can find!) to take slices from
> > negative to positive indexes, although the range is not empty, nor the
> > expected indexes out of range that I am supplying.
>
> >
>
> > Many programs that I write would require introducing variables and logical
> > statements to correct the problem which is very lengthy and error prone
> > unless there is a simple work around.
>
> >
>
> > I *hate* replicating code every time I need to do this!
>
> >
>
> > I also don't understand why slice() is not equivalent to an iterator, but
> > can replace an integer in __getitem__() whereas xrange() can't.
>
> >
>
> >
>
> > Here's an example for Linux shell, otherwise remove /bin/env...
>
> > {{{#!/bin/env python
>
> > a=[1,2,3,4,5,6,7,8,9,10]
>
> > print a[-4:3] # I am interested in getting [7,8,9,10,1,2] but I get [].
>
> > }}}
>
>
>
>
>
> For a sequence of length 10, "a[-4:3]" is equivalent to "a[6:3]",
>
> which is an empty slice since index 6 is after index 3.
>
>
>
> If you want it to wrap around, then take two slices and concatenate
>
> them with "a[-4:] + a[:3]".
Hi Ian,
Well, no it really isn't equivalent; although Python implements it as
equivalent.
Consider a programmer who writes:
xrange(-4,3)
They clearly *want* [-4,-3,-2,-1,0,1,2]
That is the "idea" of a range; So, for what reason would anyone want -4 to +3
to be 6:3??? Can you show me some code where this is desirable??
I do agree that the data held in -4 is equivalent to the data in 6, but the
index is not the same.
So: Why does python choose to convert them to positive indexes, and have slice
operate differently than xrange -- for the slice() object can't possibly know
the size of the array when it is passed in to __getitem__; They are totally
separate classes.
I realize I can concat. two slice ranges, BUT, the ranges do not always span
from negative to positive.
eg: a line in my program reads:
a[x-5:x]
if x is 7, then this is a positive index to a positive index.
So, there is no logic to using two slices concatd !
I use this arbitrary range code *often* so I need a general purpose solution.
I looked up slice() but the help is of no use, I don't even know how I might
overload it to embed some logic to concatenate ranges of data; nor even if it
is possible.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Negative array indicies and slice()
On Sunday, October 28, 2012 9:26:01 PM UTC-7, Ian wrote: > On Sun, Oct 28, 2012 at 10:00 PM, Andrew wrote: > > > Hi Ian, > > > Well, no it really isn't equivalent. > > > Consider a programmer who writes: > > > xrange(-4,3) *wants* [-4,-3,-2,-1,0,1,2] > > > > > > That is the "idea" of a range; for what reason would anyone *EVER* want -4 > > to +3 to be 6:3??? > > > > That is what ranges do, but your question was about slices, not ranges. Actually, I said in the OP: "I also don't understand why slice() is not equivalent to an iterator, but can replace an integer in __getitem__() whereas xrange() can't." = Thank you for the code snippet; I don't think it likely that existing programs depend on nor use a negative index and a positive index expecting to take a small chunk in the center... hence, I would return the whole array; Or if someone said [-len(listX) : len(listX)+1 ] I would return the whole array twice. That's the maximum that is possible. If someone could show me a normal/reasonable script which *would* expect the other behavior, I'd like to know; compatibility is important. = My intended inferences about the iterator vs. slice question was perhaps not obvious to you; Notice: an iterator is not *allowed* in __getitem__(). The slice class when passed to __getitem__() was created to merely pass two numbers and a stride to __getitem__; As far as I know slice() itself does *nothing* in the actual processing of the elements. So, it's *redundant* functionality, and far worse, it's restrictive. The philosophy of Python is to have exactly one way to do something when possible; so, why create a stand alone class that does nothing an existing class could already do, and do it better ? A simple list of three values would be just as efficient as slice()! xrange is more flexible, and can be just as efficient. So, Have I misunderstood the operation of slice()? I think I might have... but I don't know. In 'C', where Python is written, circularly linked lists -- and arrays are both very efficient ways of accessing data. Arrays can, in fact, have negative indexes -- perhaps contrary to what you thought. One merely defines a variable to act as the base pointer to the array and initialize it to the *end* of the array. Nor is the size of the data elements an issue, since in Python all classes are accessed by pointers which are of uniform size. I routinely do this in C. Consider, also, that xrange() does not actually create a list -- but merely an iterator generating integers which is exactly what __getitem__ works on. So, xrange() does not need to incur a memory or noticeable time penalty. >From micro-python, it's clear that their implementation of xrange() is at the >'C' level; which is extremely fast. -- http://mail.python.org/mailman/listinfo/python-list
os.popen and the subprocess module
Hello world, I'm working on a script that will run an executable obtaine the output from the executable and do some analysis on the output. Essentially the script runs the executable analyses the data. I'm looking into os.popen and the subprocess module, implementing os.popen is easy but i hear it is depreciating however I'm finding the implemantation of subprocess daunting can anyone help Dx -- 守破離(shuhari)first learn, then detach, and finally transcend -- http://mail.python.org/mailman/listinfo/python-list
getpass and IDEs
I find that calling getpass produces a warning noting that it can't suppress output, if I'm using idle, wingide, or a few others. If I'm running from the console it works fine, but then I can't make use of ide-integrated debugging. I know I could just set up a test account for development purposes if I'm concerned about shoulder surfers, and that's probably a good idea anyway. But I'm curious what's different about IDE environments that makes it impossible to suppress output on them, and if there's anything that might be done about this. -- Andrew -- http://mail.python.org/mailman/listinfo/python-list
Re: getpass and IDEs
On Fri, 25 Feb 2011 20:27:42 +0100, Wolfgang Rohdewald wrote: > On Freitag 25 Februar 2011, Andrew wrote: >> But I'm curious what's different >> about IDE environments that makes it impossible to suppress >> output on them, and if there's anything that might be done >> about this. > > I'd say your IDE redirects stdout/stderr so it can show > output within the IDE > > http://docs.python.org/library/getpass.html > reading python docs lets me believe you are using > python pre 2.6 3.2. Though maybe you're right anyway. Does IDLE redirect in that fashion? Why would that interfere with getpass? I'm less concerned about how to get around it as with figuring out why it does it. More curiosity than practicality. -- Andrew -- http://mail.python.org/mailman/listinfo/python-list
ANNOUNCE: Python interface for making telephone calls using Voicent Gateway
The Voicent Python Simple Interface class contains the following functions. callText callAudio callStatus callRemove callTillConfirm These functions are used to invoke telephone calls from your Python program. For example, callText is used to call a specified number and automatically play your text message using text-to-speech engine. In order for this class to work, you'll need to have Voicent Gateway installed somewhere in your network. This class simply sends HTTP request for telephone calls to the gateway. Voicent has a free edition for the gateway. You can download it from http://www.voicent.com More information can be found at: http://www.voicent.com/devnet/docs/pyapi.htm Thank you and have fun -- http://mail.python.org/mailman/listinfo/python-list
Proper use of the codecs module.
I have a mixed binary/text file[0], and the text portions use a radically nonstandard character set. I want to read them easily given information about the character encoding and an offset for the beginning of a string. The descriptions of the codecs module and codecs.register() in particular seem to suggest that this is already supported in the standard library. However, I can't find any examples of its proper use. Most people who use the module seem to want to read utf files in python 2.x.[1] I would like to know how to correctly set up a new codec for reading files that have nonstandard encodings. I have two other related questions: How does seek() work on a file opened in text mode? Does it seek to a character offset or to a byte offset? I need the latter behavior. If I can't get it I will have to find a different approach. The files I'm working with use a nonstandard end-of-string character in the same fashion as C null-terminated strings. Is there a builtin function that will read a file "from seek position until seeing EOS character X"? The methods I see for this online seem to amount to reading one character at a time and checking manually, which seems nonoptimal to me. [0] The file is an SNES ROM dump, but I don't think that matters. [1] I'm using Python 3, if it's relevant. -- Andrew -- http://mail.python.org/mailman/listinfo/python-list
Re: Proper use of the codecs module.
On 16 Aug 2013 19:12:02 GMT, Steven D'Aprano wrote: > If you try opening the file in text mode, you'll very likely break the > binary parts (e.g. converting the two bytes 0x0D0A to a single byte > 0x0A). So best to stick to binary only, extract the "text" portions of > the file, then explicitly decode them. Okay, I'll do that. Given what you said about seek() and text mode below, I have no choice anyway. >> I would like to know how to correctly set up a new codec for >> reading files that have nonstandard encodings. > > I suggest you look at the source code for the dozens of codecs in the > standard library. E.g. /usr/local/lib/python3.3/encodings/palmos.py I'll do that too. My thanks for the pointer. >> How does seek() work on a file opened in text mode? Does it seek to a >> character offset or to a byte offset? I need the latter behavior. If I >> can't get it I will have to find a different approach. > > For text files, seek() is only legal for offsets that tell() can return, > but this is not enforced, so you can get nasty rubbish like this: > > > > So I prefer not to seek in text files if I can help it. If I'm understanding the above right, it seeks to a byte offset but the behavior is undocumented, not guaranteed, shouldn't be used, etc. That would actually work for me in theory (because I have exact byte offsets to work with) but I think I'll avoid it anyway, on the grounds that relying on undocumented behavior is bad. >> The files I'm working with use a nonstandard end-of-string character in >> the same fashion as C null-terminated strings. Is there a builtin >> function that will read a file "from seek position until seeing EOS >> character X"? The methods I see for this online seem to amount to >> reading one character at a time and checking manually, which seems >> nonoptimal to me. > > How do you think such a built-in function would work, if not inspect each > character until the EOS character is seen? :-) I don't know, but I'm assuming it wouldn't involve a function call to file.read(1) for each character, and that's what Google keeps handing me. Such an approach fills me with horror. :-) I suppose there's nothing stopping me from reading some educated guess at the length of the string and then stepping through the result. Or I'll look at the readline() source and see how it does its thing. > There is no such built-in function though. By default, Python files are > buffered, so it won't literally read one character from disk at a time. > The actual disk IO will read a bunch of bytes into a memory buffer, and > then read from the buffer. I'd guessed as much, but assumed there was still ridiculous function call overhead involved in the repeated read(1) method above. Of course, trying to avoid said overhead is premature optimization; my interest in doing so is more aesthetic than anything else. Thanks for the help. -- Andrew -- http://mail.python.org/mailman/listinfo/python-list
Server Questions (2 of them)
Hello List, How to do you create a server that accepts a set of user code? For example, I would like to send this function: def addition(x,y): return x+y and have the socket server perform the operation and send is back to the end user. Question 2: On that same server, I want a user to be able to pass a file to the server along with code. What is the best way to pass file to the server? Thank you for any suggestions or resources you can provide. Andrew -- http://mail.python.org/mailman/listinfo/python-list
need help with recieving sockets
Hi I was wondering if any one could help me with a chat client I am writing my main issue is not in the sending of messages or in the connection setting. I am having issues receiving the messages. I am using Tkinter as the GUI and Python 2.3.5 my code has been edited so many times but no matter what I do everytime I click my recieve button the client crashes and Tkinter freezes up and I don't recieve the message back from the server. Does anyone have any ideas what I am doing wrong here is the latest function I am using: def recv_basic(): textbox.insert(END, sock.recv(1024)) textbox.insert(END, "\n\n") on a side note I can get the first connection message back from the server if I click the recieve button. Another side note I have tried two different servers one I wrote and another one I found in a tutorial Cheers and thanks for any help -- http://mail.python.org/mailman/listinfo/python-list
Scapy Port to Windows
Hello Everyone I'm just writing to inform the newsgroup or anyone who is interested. I have some what of a working copy of scapy, ported to Windows, based on the notes provided on the scapy mailing list for reference http://www.secdev.org/projects/scapy/ (scapy windows) for python version 24 http://www.techshinobi.de/software/scapyandpack.zip (scapy windows) for python version 23 http://www.techshinobi.de/software/pyscapy23.zip however my testing and skill with this application is limited. Ive been trying to get this src code to work with it: >>> www.techshinobi.de/software/IPFreelysrc.zip and it has been successful Please note I am not really a good programmer I have a small - medium knowledge of programming (compared to some of you guys) If anyone is interested in assisting with a full working version of scapy on windows, I believe it would be very beneficial to the growth of the scapy project Thank You in Advance Cheers Andrew :) -- http://mail.python.org/mailman/listinfo/python-list
Shortcut to initialize variables
Newb here... For one of my programs I want to initialize a variable for each letter of the alphabet. For example, a,b,c = 0,0,0. I don't think this works, but I'm wondering if I can do something similar to this: from string import ascii_lowercase class Blah: def __init__(self): for letter in ascii_lowercase: setattr(self,letter,0) Is there a way I can do something like this without using classes? Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Shortcut to initialize variables
Oops, I probably should have tried searching the list first. My background is strictly academic. I was switching languages so often I never got really familiar with any of them. Maybe C for a while, but I've forgotten alot. I'm hoping python will be the last language I ever need. :) I don't know why I didn't turn to dictionaries first. It does seem to be the obvious solution. I'm writing a program that will take substitution and transposition cipher texts and spit out plain text with no human input. So I suppose I'll have dictionaries of digraphs and trigraphs too; for frequency analysis. Do you think this is to heavy of a project to learn the language? Thanks for the quick feedback -- http://mail.python.org/mailman/listinfo/python-list
Problems Drawing Over Network
xpand=True)
self.send=Button(self.frame, text='Send Message',
command=self.send)
self.send.pack(side=LEFT)
self.draw=Button(self.frame, text='Dungeon Canvas',
command=self.openCanvas)
self.draw.pack(side=LEFT)
self.d20=Button(self.frame, text='D20', command=self.d20roll)
self.d20.pack(side=LEFT)
self.sendtext=Entry(self.frame)
self.sendtext.pack(side=LEFT, fill=X, expand=True)
def d20roll(self):
self.rand = random.randrange(1, 20)
rs = str(self.rand)
self.d20text = "d20 Roll " + rs
s.send(self.d20text)
self.textbox.insert(END, self.d20text)
def openCanvas(self):
main()
def send(self):
self.sendit = self.sendtext.get()
if self.sendit == "":
pass
else:
s.send(self.sendit)
self.textbox.insert(END, self.sendit + "\n")
self.sendtext.delete(0, END)
def run(self):
while 1:
data=s.recv(1024)
app.textbox.insert(END, str(data) + "\n")
time.sleep(0.1)
#
root = Tk()
root.wm_resizable(0, 0)
root.wm_iconbitmap("shinobi.ico")
frmimg = Image.open("banner.jpg")
fri = ImageTk.PhotoImage(frmimg)
classtitle="Tech Shinobi Chat 1.0"
root.option_readfile("optionDB")
root.title(classtitle)
root.geometry('%dx%d+%d+%d' % (500,380,0,0))
app = App(root)
root.mainloop()
s.close()
###END CODE###
That is the client now here is the server
###CODE###
#!/usr/bin/env python
#SERVER
import socket, traceback, os, sys
from threading import *
import spots
host = '' # Bind to all interfaces
port =
def handlechild():
while 1:
data = ZSP.recv()
if not len(data):
break
ZSP.send((data))
# Set up the socket.
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port))
s.listen(1)
while 1:
try:
ZSP = spots.ZSP(s.accept()[0])
except KeyboardInterrupt:
raise
except:
traceback.print_exc()
continue
t = Thread(target=handlechild)
t.setDaemon(1)
t.start()
heres is a link to the spots module I am using
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/511435
also the original drawing application I am using
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/511436
Cheers
I appreciate any help
ty
Andrew Evans
--
http://mail.python.org/mailman/listinfo/python-list
Pil Raw Image Viewer-- How to get image mode
Hello Ive been messing around with a simple raw image viewer using Pil
and Tkinter
However I am running into problems displaying the images they appear to
be not correct I believe it is cause of the modes for the different
files but I am unsure
If someone could examine my code and assist in helping me solve my
problem(s)
It would be greatly appreciated
from Tkinter import *
import Image, ImageTk
import os
import tkFileDialog
size = 1024, 768
def getfiles():
try:
entry.delete(0, END)
global fileopen
fileopen = tkFileDialog.askdirectory()
entry.insert(END, fileopen)
finally:
listb.delete(0, END)
filenames = {'': []}
getfileext = fileentry.get()
path = entry.get()
for root, dirs, files in os.walk(path):
for name in files:
lname = name.lower()# if on windows
global names
for ext, names in filenames.iteritems():
if lname.endswith(getfileext):
names.append(os.path.join(root, name))
listb.insert(END, name)
break
def select(event):
selection = listb.curselection()
global selectit
selectit = names[int(selection[0])]
global im
image_file = open(selectit, 'rb')
data = image_file.read()
im = Image.fromstring("RGB", (size), data, "raw")
im.thumbnail((700, 700))
image = ImageTk.PhotoImage(im)
label["image"]=image
label.image = image
root = Tk()
root.title("Engrooved Image Viewer")
root.wm_resizable(0, 0)
root.wm_iconbitmap("shinobi.ico")
frame = Frame(root)
im = Image.open("startimage.jpg")
image = ImageTk.PhotoImage(im)
##canvas = Canvas(frame, width=400, height=400)
##canvas.create_image(0, 0, image=image)
##canvas.grid(row=0, column=0, sticky=N+S+W+E)
label = Label(frame, image=image)
label.image = image
label.grid(row=0, column=0, sticky=N+S+W+E)
scrollbar2 = Scrollbar(frame)
scrollbar2.grid(row=0, column=2, rowspan=1, columnspan=1, stick=N+S)
listb = Listbox(frame, selectmode=SINGLE)
listb.grid(row=0, column=1, columnspan=1, sticky=N+S+W+E)
listb.bind('', select)
scrollbar2.config(command=listb.yview)
listb.config(yscrollcommand=scrollbar2.set)
frame.grid(sticky=N+S+W+E)
frame3 = Frame(root)
entry = Entry(frame3)
entry.grid(row=1, column=1, stick=W+E, columnspan=1)
label2 = Label(frame3, text="EXT").grid(row=1, column=2)
fileentry = Entry(frame3)
fileentry.grid(row=1, column=3, columnspan=1, sticky=W+E)
button = Button(frame3, text="Open and List Directory", command=getfiles)
button.grid(row=1, column=4)
frame3.grid(sticky=W+E)
root.mainloop()
Ty
Cheers
--
http://mail.python.org/mailman/listinfo/python-list
socket.inet_ntop, and pton question
Hi Are these functions (inet_ntop(), inet_pton()) from the socket library supported on Windows. If not is there an equivalent for them using Windows Ive seen mention of people creating their own in order to use them Appreciate the help ty -- http://mail.python.org/mailman/listinfo/python-list
Re: socket.inet_ntop, and pton question
Hi I just thought I would mention that I found what I needed from dnspython if anyone ever needs ;) http://www.dnspython.org/ -- http://mail.python.org/mailman/listinfo/python-list
Raw Imager
Im looking at building a tool for previewing raw images as Thumbnails no editing really just viewing in a simple Tkinter GUI however from what I can tell Pil does not support raw images Does anyone have a link to a module that would allow this I guess I would need support for as many different raw types as possible... if possible. Cheers Andrew -- http://mail.python.org/mailman/listinfo/python-list
system(...) and unicode
Hi,
I'm seeing the following error:
...
system(cmd)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe3' in
position 57: ordinal not in range(128)
and I think I vaguely understand what's going on - "cmd" is constructed
to include a file name that is UTF-8 encoded (I think - it includes
accents when I "ls" the file - this is on a recent Suse Linux with
Python 2.4.2). So I guess I need to specify the encoding used, right?
But (1) I don't know how to do this; (2) this string came from the
filesystem in the first place, so how come it isn't managed in an
internally consistent way?; and (3) I have no explicit uncode strings
in my program.
Looking at the docs (unicode howto) it seems like maybe I need to do
system(cmd.encode(...))
but how do I know which locale and what if cmd isn't a unicode string
(I didn't make it so!)? I could force an encoding as in the unicode
howto ("filename.decode(encoding)"), but that seems to already be
happening (or is it not - am I wrong in assuming that?).
So can someone help me or point me to some more detailed instructions,
please? At the CL "locale" says en_GB.UTF-8, but I'd like this code to
work whatever the locale is, if that makes sense.
Sorry for being stupid,
Andrew
--
http://mail.python.org/mailman/listinfo/python-list
Re: system(...) and unicode
Hmmm. After reading http://kofoto.rosdahl.net/trac/wiki/UnicodeInPython I tried: system(cmd.encode(getfilesystemencoding())) which works (nothing else changed). But that seems odd - is this a bug (the asymmetry - I read files with os.listdir with no explicit unicode handling, but need to do something explicitly on output - seems wrong), or am I going to be bitten by other errors later? Thanks, Andrew -- http://mail.python.org/mailman/listinfo/python-list
Re: system(...) and unicode
The impression I got from the link I gave was that exec et al already had the appropriate unicode support; system seems to be the exception. Anyway, thanks for the info - that directory name is coming from a DOM call, and I'm pretty sure it's returning Unicode, so that makes sense. Andrew -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess returncode windows
On Dec 16 2008, 5:11 pm, "Gabriel Genellina"
wrote:
> En Tue, 16 Dec 2008 17:21:35 -0200, Andrew
> escribió:
>
>
>
> > On Dec 16, 12:50 pm, Christian Heimes wrote:
> >> Andrew schrieb:
>
> >> > I'm running into a strange situation with getting incorrect
> >> > returncodes / exit status from python subprocess.call. I'm using a
> >> > python script (runtime 2.6.1 on windows) to automate the deploy of
> >> > java applications to glassfish application server. Below is an example
>
> > I've removed shell=True, unfortunately, if I structure the call like:
>
> > call(["c:/glassfish/bin/asadmin.bat", "list-system-properties", "--
> > host
> > mydomain", "--port 4848", "--user admin", "server-01"])
>
> > It doesn't seem to recognize any arguments after list-system-
> > properties.
>
> Should be:
>
> call(["c:/glassfish/bin/asadmin.bat", "list-system-properties", "--host",
> "mydomain", "--port", "4848", "--user", "admin", "server-01"])
>
> *Every* argument should be an item in the list (your way, "--port 4848"
> becomes a single argument, not two: option plus value)
> (This is independent of your other issue)
>
> > If I structure it like:
>
> > call("c:/glassfish/bin/asadmin.bat "+"list-system-properties --host
> > mydomain --port 4848 --user admin server-01")
>
> > Then it executes correctly but still gives invalid returncode of 0
> > when it fails instead of 1.
>
> A similar example works fine for me:
>
> C:\temp>type ret.c
> #include
>
> int main(int argc, char* argv[])
> {
> return atoi(argv[1]);
>
> }
>
> C:\temp>ret 5
>
> C:\temp>echo %errorlevel%
> 5
>
> C:\temp>type testret.bat
> ret %1
>
> C:\temp>testret 3
>
> C:\temp>ret 3
>
> C:\temp>echo %errorlevel%
> 3
>
> C:\temp>type testret.py
> from subprocess import call
> ret = call(["testret.bat", "42"])
> print "testret.bat exit code =", ret
>
> C:\temp>python testret.py
>
> C:\temp>ret 42
> testret.bat exit code = 42
>
> C:\temp>python -V
> Python 2.6
>
> C:\temp>ver
>
> Microsoft Windows XP [Versión 5.1.2600]
>
> --
> Gabriel Genellina
I've tried this several ways now. It seems to be something specific
with python and asadmin.bat.
I've tried the following manually in the cmd.exe prompt:
--
C:\temp>c:\glassfish\bin\asadmin.bat list-system-properties
Instance-01
properties here
Command list-system-properties executed successfully.
C:\temp>echo %errorlevel%
0
C:\temp>c:\glassfish\bin\asadmin.bat list-system-properties
Instance-05//note that Instance-05 does not exist
Cannot determine type for target : Instance-05
CLI137 Command list-system-properties failed.
C:\temp>echo %errorlevel%
1
C:\temp>ping 019293.com
Ping request could not find host 019293.com. Please check the name and
try again
.
C:\temp>echo %errorlevel%
1
C:\temp>ping google.com
Pinging google.com [74.125.45.100] with 32 bytes of data:
Reply from 74.125.45.100: bytes=32 time=48ms TTL=234
Reply from 74.125.45.100: bytes=32 time=66ms TTL=234
Reply from 74.125.45.100: bytes=32 time=63ms TTL=234
Reply from 74.125.45.100: bytes=32 time=44ms TTL=234
Ping statistics for 74.125.45.100:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 44ms, Maximum = 66ms, Average = 55ms
C:\temp>echo %errorlevel%
0
Then I tried the following in python (2.6.1)
---script---
import subprocess
import sys
try:
retcode = subprocess.call(["ping","019293.com"])
if retcode < 0:
print >>sys.stderr, "Child was terminated by signal", -retcode
else:
print >>sys.stderr, "Child returned", retcode
except OSError, e:
print >>sys.stderr, "Execution failed:", e
try:
retcode = subprocess.call(["ping","google.com"])
if retcode < 0:
print >>sys.stderr, "Child was terminated by signal", -retcode
else:
print >>sys.stderr, "Child returned", retcode
except OSError, e:
print >>sys.stderr, "Execution failed:", e
try:
retcode = subprocess.call(["c:/glassfish/bin/asadmin.bat","list-
system-properties","Instance-01"], shell=False)
if retcode < 0:
print >>sys.stderr, "Child was terminated by signal"
Re: subprocess returncode windows
On Feb 5, 9:17 pm, "Gabriel Genellina" wrote: > En Thu, 05 Feb 2009 17:34:29 -0200, Andrew > escribió: > > > > > On Dec 16 2008, 5:11 pm, "Gabriel Genellina" > > wrote: > >> En Tue, 16 Dec 2008 17:21:35 -0200, Andrew > >> escribió: > > >> > On Dec 16, 12:50 pm, Christian Heimes wrote: > >> >> Andrew schrieb: > > >> >> > I'm running into a strange situation with getting incorrect > >> >> > returncodes / exit status from python subprocess.call. I'm using a > >> >> > python script (runtime 2.6.1 on windows) to automate the deploy of > >> >> > java applications to glassfish application server. Below is an >> > >> > example > > I've tried this several ways now. It seems to be something specific > > with python and asadmin.bat. > > > I've tried the following manually in the cmd.exe prompt: > > [examples showing %ERRORLEVEL% correctly set when running from the command > line, but subprocess.call doesn't get it] > > > Notice how python never gets the correct returncode from asadmin.bat > > but I can get the correct returncode from the shell every time. Can > > anyone tell me why Python wouldn't be able to get the correct > > returncode for asadmin? > > The last exit code set by a command *should* propagate as the exit code of > the whole .bat, then as the exit code of the cmd.exe instance that runs > it, and finally Python *should* receive that value. Some old Windows > versions didn't behave like that, but AFAIK XP does the right thing here. > Unless asadmin.bat is playing tricks with %ERRORLEVEL% or something. > Can you post the contents of asadmin.bat? > > Without looking into it, I can think of a few alternatives: > > - rewrite asadmin.bat in Python, if feasible. Some scripts just check/set > a few environment variables and execute some process at the end, and > that's all; in this case it should be easy to emulate the same thing in > Python. > > - try using another layer of your own, e.g., my_asadmin.bat: > > call asadmin.bat %* > exit /b %ERRORLEVEL% > > - variation: write the exit code somewhere: > > call asadmin.bat %* > echo %ERRORLEVEL% > asadmin.err > > and read asadmin.err from Python. (I've used something like this in a > chain Win32 process --> 16 bits GUI application --> .bat script --> old > DOS executable) > > -- > Gabriel Genellina Thanks Gabriel, Someone on the glassfish forums also pointed out the "exit /B %ERRORLEVEL%" for the bottom of the batch file and that corrected the issue for me. As well as not using that and removing "endlocal" which I admit I have no clue what that does. Removing endlocal seems to cause the batch script to pass out the correct returncode. Thanks everyone for your input and assistance =] Andrew -- http://mail.python.org/mailman/listinfo/python-list
IF YOU WANT TO LIVE LONGER, YOU SHOULD CHECK THIS!!
http://www.associatedcontent.com/article/995306/parameningeal_infection_brain_abscess.html?cat=70 -- http://mail.python.org/mailman/listinfo/python-list
subprocess returncode windows
Hello,
I'm running into a strange situation with getting incorrect
returncodes / exit status from python subprocess.call. I'm using a
python script (runtime 2.6.1 on windows) to automate the deploy of
java applications to glassfish application server. Below is an example
of using a subprocess call to test the success / failure of the
glassfish CLI tool "asadmin"
Example.py:
--
import sys
from subprocess import *
try:
retcode = call("c:/glassfish/bin/asadmin.bat " + "list-system-
properties --host mydomain --port 4848 --user admin server-01",
shell=True)
if retcode < 0:
print >>sys.stderr, "Child was terminated by signal", -retcode
else:
print >>sys.stderr, "Child returned", retcode
except OSError, e:
print >>sys.stderr, "Execution failed:", e
--
However, when I execute it, it gets the same returncode whether it
fails or succeeds (0).
-
C:\>python z:\bin\example.py
Please enter the admin password> ***Enters Good Password***
IIOP_SSL_MUTUALAUTH_PORT=33920
JMX_SYSTEM_CONNECTOR_PORT=38686
IIOP_LISTENER_PORT=33700
IIOP_SSL_LISTENER_PORT=33820
HTTP_LISTENER_PORT=38080
AJP_INSTANCE_NAME=WebReporting-01
HTTP_SSL_LISTENER_PORT=38181
JMS_PROVIDER_PORT=37676
AJP_PORT=18009
Command list-system-properties executed successfully.
Child returned 0
C:\>python z:\bin\example.py
Please enter the admin password>***Enters BAD PASSWORD***
Invalid user or password
CLI137 Command list-system-properties failed.
Child returned 0
C:\>
When I execute this manually from the cmd.exe and I check the
%errorlevel% it returns the correct levels:
---
C:\>c:\glassfish\bin\asadmin.bat list-system-properties --host
mydomain --port 4848 --user admin server-01
Please enter the admin password>***GOOD PASSWORD***
IIOP_SSL_MUTUALAUTH_PORT=33920
JMX_SYSTEM_CONNECTOR_PORT=38686
IIOP_LISTENER_PORT=33700
IIOP_SSL_LISTENER_PORT=33820
HTTP_LISTENER_PORT=38080
AJP_INSTANCE_NAME=WebReporting-01
HTTP_SSL_LISTENER_PORT=38181
JMS_PROVIDER_PORT=37676
AJP_PORT=18009
Command list-system-properties executed successfully.
C:\>echo %errorlevel%
0
C:\>c:\glassfish\bin\asadmin.bat list-system-properties --host
mydomain --port 4848 --user admin server-01
Please enter the admin password>***BAD PASSWORD***
Invalid user or password
CLI137 Command list-system-properties failed.
C:\>echo %errorlevel%
1
C:\>
-
I'm guessing that returncode isn't the same thing as exit status? Is
there a way to get exit status using a subprocess function instead of
returncode? Is this the right way to go about this?
Thanks for any direction / advice you can provide.
Andrew
--
http://mail.python.org/mailman/listinfo/python-list
Re: subprocess returncode windows
On Dec 16, 12:50 pm, Christian Heimes wrote:
> Andrew schrieb:
>
>
>
> > Hello,
>
> > I'm running into a strange situation with getting incorrect
> > returncodes / exit status from python subprocess.call. I'm using a
> > python script (runtime 2.6.1 on windows) to automate the deploy of
> > java applications to glassfish application server. Below is an example
> > of using a subprocess call to test the success / failure of the
> > glassfish CLI tool "asadmin"
>
> > Example.py:
> > --
> > import sys
> > from subprocess import *
>
> > try:
> > retcode = call("c:/glassfish/bin/asadmin.bat " + "list-system-
> > properties --host mydomain --port 4848 --user admin server-01",
> > shell=True)
> > if retcode < 0:
> > print >>sys.stderr, "Child was terminated by signal", -retcode
> > else:
> > print >>sys.stderr, "Child returned", retcode
> > except OSError, e:
> > print >>sys.stderr, "Execution failed:", e
>
> Don't use shell=True! Instead use a list of arguments without shell=True:
>
> call(["c:/glassfish/bin/asadmin.bat", "list-system-properties", "--host
> mydomain", "--port 4848", "--user admin", "server-01"])
>
> That should solve your quoting issues on Windows and fix your code.
> shell=True is considered evil and should be avoided whenever possible.
>
> Christian
Thanks Christian,
I've removed shell=True, unfortunately, if I structure the call like:
call(["c:/glassfish/bin/asadmin.bat", "list-system-properties", "--
host
mydomain", "--port 4848", "--user admin", "server-01"])
It doesn't seem to recognize any arguments after list-system-
properties. If I structure it like:
call("c:/glassfish/bin/asadmin.bat "+"list-system-properties --host
mydomain --port 4848 --user admin server-01")
Then it executes correctly but still gives invalid returncode of 0
when it fails instead of 1.
Andrew
--
http://mail.python.org/mailman/listinfo/python-list
Re: [Newbie] Strange output from list
Ben Finney wrote:
> Gilles Ganault <[EMAIL PROTECTED]> writes:
>
>
>> Hello
>>
>> I'm getting some unwanted result when SELECTing data from an SQLite
>> database:
>>
>> ==
>> sql = 'SELECT id FROM master'
>> rows=list(cursor.execute(sql))
>> for id in rows:
>> sql = 'SELECT COUNT(code) FROM companies WHERE code="%s"' % id[0]
>> result = list(cursor.execute(sql))
>> print "Code=%s, number=%s" % (id[0],result[0])
>> ==
>> Code=0111Z, number=(47,)
>> ==
>>
>> I expected to see "number=47". Why does Python return "(47,)"?
>>
>
> The result of an SQL SELECT is a sequence of tuples, where each item
> in the tuple is a value for a column as specified in the SELECT
> clause.
>
> SQLAlchemy represents this with a sequence of ResultProxy objects.
> When you convert a ResultProxy object to a string, it displays like a
> tuple. See the documentation for other ways of accessing various
> attributes of a ResultProxy object.
>
(47,) is the python representation of a one item tuple
If you want:
Code=0111Z, number=47
Just change your code to:
sql = 'SELECT id FROM master'
rows=list(cursor.execute(sql))
for id in rows:
sql = 'SELECT COUNT(code) FROM companies WHERE code="%s"' % id[0]
result = list(cursor.execute(sql))
print "Code=%s, number=%s" % (id[0],result[0][0])
Notice the extra [0] index on the "result"
In English:
Item zero of the tuple that is item zero of result
E.g.
>>> result = [(47,)]
>>> result = result[0]
>>> result
(47,)
>>> result[0]
47
--
Andrew
--
http://mail.python.org/mailman/listinfo/python-list
PEP 324 error
It appears PEP 324 is missing the part about check_call(): http://www.python.org/dev/peps/pep-0324/ ... This module also defines two shortcut functions: - call(*args, **kwargs): Run command with arguments. Wait for command to complete, then return the returncode attribute. The arguments are the same as for the Popen constructor. Example: retcode = call(["ls", "-l"]) Exceptions -- ... Note the lack of "two shortcut functions". In the docstring of subprocess in python 2.5: This module also defines two shortcut functions: call(*popenargs, **kwargs): Run command with arguments. Wait for command to complete, then return the returncode attribute. The arguments are the same as for the Popen constructor. Example: retcode = call(["ls", "-l"]) check_call(*popenargs, **kwargs): Run command with arguments. Wait for command to complete. If the exit code was zero then return, otherwise raise CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute. The arguments are the same as for the Popen constructor. Example: check_call(["ls", "-l"]) I don't know if check_call is going to be deprecated, but there still appears to be a missing function. I'm not sure if this is the correct way to report errors, but I think it's prudent to keep the documentation comprehensive. -- Andrew -- http://mail.python.org/mailman/listinfo/python-list
imported method from module evaluates to None in some cases
Hi:
I'm having a problem in some zope (2.10) code (HTTPResponse.py) where
a method that gets imported somehow evaluates to None in certain cases
which causes a TypeError exception to be raised (eg: TypeError:
'NoneType' object is not callable). The code excerpt is below where
the exception is raised on the line with the comment 'TypeError IS
RAISED HERE'. I've read that the thread stack size may be insufficient
but the I compiled a test pthreads program on the same system to get
the default. I used pthread_attr_getstacksize() and it returned
3657952 (3.5 mb?). I would imagine that's enough. Any ideas how this
could occur?
from PubCore.ZEvent import Wakeup
def close(self):
DebugLogger.log('A', id(self._request),
'%s %s' % (self._request.reply_code, self._bytes))
if not self._channel.closed:
self._channel.push(LoggingProducer(self._request,
self._bytes), 0)
self._channel.push(CallbackProducer(self._channel.done),
0)
self._channel.push(CallbackProducer(
lambda t=('E', id(self._request)): apply
(DebugLogger.log, t)), 0)
if self._shutdown:
self._channel.push(ShutdownProducer(), 0)
Wakeup()
else:
if self._close: self._channel.push(None, 0)
Wakeup()# TypeError IS RAISED HERE
else:
# channel closed too soon
self._request.log(self._bytes)
DebugLogger.log('E', id(self._request))
if self._shutdown:
Wakeup(lambda: asyncore.close_all())
else:
Wakeup()
self._channel=None #need to break cycles?
self._request=None
--
http://mail.python.org/mailman/listinfo/python-list
Re: imported method from module evaluates to None in some cases
On Nov 20, 6:53 am, Hrvoje Niksic <[EMAIL PROTECTED]> wrote: > Andrew <[EMAIL PROTECTED]> writes: > > I'm having a problem in some zope (2.10) code (HTTPResponse.py) where > > a method that gets imported somehow evaluates to None in certain cases > > which causes a TypeError exception to be raised (eg: TypeError: > > 'NoneType' object is not callable). The code excerpt is below where > > the exception is raised on the line with the comment 'TypeError IS > > RAISED HERE'. > > Could the "certain cases" involve automatic invocation of the close > method at interpreter shutdown? While the interpreter shuts down, > module-level variables are set to None. This is documented in some > detail inhttp://www.python.org/doc/essays/cleanup/, steps C1-C3. That's possible. I didn't know that. Now I guess the question for me is why and where did the interpreter shutdown? I don't see log entries relating to it. Is it possible for me to intercept an interpreter shutdown so I can find out the location and possibly the reason why the interpreter abruptly shuts down? -- http://mail.python.org/mailman/listinfo/python-list
Tun/Tap Driver using OpenVPN and DeviceIoControl
Hello I am trying to port some code and I am running into some issues I
may or may not be able to solve on my own and would appreciate your help
Basically I am trying to open the Tun Driver through openvpn in Ether
(Tap mode).
code is as follows
f = win32file.CreateFile("C:\\WINDOWS\\System32\\drivers\\tunmp.sys",
GENERIC_READ, 0, None, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0)
if WINDOWS:
ifs = win32file.DeviceIoControl(f, TUNSETIFF,
struct.pack("16sH", "wj%d", TUNMODE), 0, None)
else:
ifs = ioctl(f, TUNSETIFF, struct.pack("16sH", "wj%d", TUNMODE))
ifname = ifs[:16].strip("\x00")
print "Interface %s created. Configure it and use it" % ifname
but does not seem to work so well I get "The Paramater is incorrect"
Traceback (most recent call last):
File "wifi.py", line 167, in
ifs = win32file.DeviceIoControl(f, TUNSETIFF, struct.pack("16sH",
"wj%d", TU
NMODE), 0, None)
pywintypes.error: (87, 'DeviceIoControl', 'The parameter is incorrect.')
Would appreciate any help
Ty
--
http://mail.python.org/mailman/listinfo/python-list
Re: Easier way to get the "here" path?
bukzor wrote:
I have to go into these convulsions to get the directory that the
script is in whenever I need to use relative paths. I was wondering if
you guys have a better way:
...
If you just need the current path (where it is executed) why not use
os.getcwd()
which returns a string of the absolute path to the module being executed.
$ echo "print __file__" > path.py
$ ipython
In [1]: import path
path.pyc
In [2]: import os
In [3]: os.path.join(os.getcwd(), path.__file__.rstrip("c"))
Out[3]: '/home/andrew/path.py'
--
Andrew
--
http://mail.python.org/mailman/listinfo/python-list
Re: Easier way to get the "here" path?
bukzor wrote:
from os.path import abspath, realpath
realpath(path.__file__.rstrip("c"))
'/home/bgolemon/python/symlinks/path.py'
realpath(abspath(path.__file__.rstrip("c")))
'/home/bgolemon/python/symlinks/symlinks/path.py'
--
http://mail.python.org/mailman/listinfo/python-list
I find it interesting that I get something different:
In [1]: import path
path.pyc
In [2]: path.__file__
Out[2]: 'path.pyc'
In [3]: path.__file__.rstrip("c")
Out[3]: 'path.py'
In [4]: from os.path import abspath, realpath
In [5]: realpath(path.__file__.rstrip("c"))
Out[5]: '/home/andrew/sym/sym/path.py'
In [6]: realpath(abspath(path.__file__.rstrip("c")))
Out[6]: '/home/andrew/sym/sym/path.py'
I get the same thing for realpath() and realpath(abspath())
It seems to me you can just use:
In [1]: import path
path.pyc
In [2]: from os.path import abspath
In [3]: realpath(path.__file__.rstrip("c"))
Out[3]: '/home/andrew/sym/sym/path.py'
By the way, I am in /home/andrew/sym and path is symlinked from
/home/andrew/sym/sym/path.py to /home/andrew/sym/path.py
--
Andrew
--
http://mail.python.org/mailman/listinfo/python-list
Re: Easier way to get the "here" path?
Andrew wrote:
bukzor wrote:
I have to go into these convulsions to get the directory that the
script is in whenever I need to use relative paths. I was wondering if
you guys have a better way:
...
If you just need the current path (where it is executed) why not use
os.getcwd()
which returns a string of the absolute path to the module being executed.
$ echo "print __file__" > path.py
$ ipython
In [1]: import path
path.pyc
In [2]: import os
In [3]: os.path.join(os.getcwd(), path.__file__.rstrip("c"))
Out[3]: '/home/andrew/path.py'
--
Andrew
I was thinking of this in the module being imported, but now that I try,
it doesn't work. It is still seeing itself from the symlink's position.
This works, in the module being imported:
$ less path.py
from os.path import realpath
here = realpath(__file__.rstrip("c"))
$ python
>>> import path
>>> path.here
'/home/andrew/sym/sym/path.py'
--
Andrew
--
http://mail.python.org/mailman/listinfo/python-list
Return a string result with out breaking loop
Hi I was wondering if there is anyway with XML RPC to send a string of text from the server to the client with out calling return thus breaking my loop for example def somefunc(): for action, files in results: full_filename = os.path.join(path_to_watch, files) theact = ACTIONS.get(action, "Unknown") out2 = str(full_filename) + " " + str(theact) return out2 the return statement will return a result breaking my loop. My goal is to have it continue looping and updating the client any ideas? Cheers Andrew Thanks in advance Pyhon 2.5.2 Windows XP -- http://mail.python.org/mailman/listinfo/python-list
Re: Return a string result with out breaking loop
Hi Ive been trying with yield all day and other different things :D but I always get the same result using yield Fault: :cannot marshal 'generator' > objects"> I'm not sure exactly what I am doing wrong as this is the first time Ive used yield Any suggestions on how to fix this error Cheers Andrew Christian Heimes wrote: Andrew wrote: Hi I was wondering if there is anyway with XML RPC to send a string of text from the server to the client with out calling return thus breaking my loop for example def somefunc(): for action, files in results: full_filename = os.path.join(path_to_watch, files) theact = ACTIONS.get(action, "Unknown") out2 = str(full_filename) + " " + str(theact) return out2 the return statement will return a result breaking my loop. My goal is to have it continue looping and updating the client any ideas? Yes, use yield instead of return. It turns the function into a generator. Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: Return a string result with out breaking loop
Yes I found many examples similiar to that but Yield still produces that error Sorry if I sound Novice but I have no formal education in programming so understanding something takes me a bit longer than most of you guys :-D Ive included a bit more of the function How ever unimportant it may be def watchos(self, path_to_watch="C:\\"): FILE_LIST_DIRECTORY = 0x0001 try: path_to_watch or "." except: path_to_watch = "." path_to_watch = os.path.abspath(path_to_watch) out1 = "Watching %s at %s" % (path_to_watch, time.asctime()) + "\n\n" while 1: #INSERT MORE CODE HERE results = change_handle for action, files in results: full_filename = os.path.join(path_to_watch, files) theact = ACTIONS.get(action, "Unknown") yield str(full_filename) + " " + str(theact) But I am having a hard time wrapping my head around yield... perhaps if it produced more than the same error no matter what I did. I could try and get a bit further Anyway once again I appreciate the help cheers :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Return a string result with out breaking loop
I run the server then execute the client. From the client I execute the
function key.watchos()
My goal is an administration tool
and this is just a function in my goal :-)
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
C:\Documents and Settings\Maboroshi>python C:\software\mabssystem\client.py
Use the keyword, "key" to interact with the server
>>> key.watchos()
Traceback (most recent call last):
File "", line 1, in
File "C:\Python25\lib\xmlrpclib.py", line 1147, in __call__
return self.__send(self.__name, args)
File "C:\Python25\lib\xmlrpclib.py", line 1437, in __request
verbose=self.__verbose
File "C:\Python25\lib\xmlrpclib.py", line 1201, in request
return self._parse_response(h.getfile(), sock)
File "C:\Python25\lib\xmlrpclib.py", line 1340, in _parse_response
return u.close()
File "C:\Python25\lib\xmlrpclib.py", line 787, in close
raise Fault(**self._stack[0])
Fault: :cannot marshal 'generator'
> objects">
>>>
the function watchos is basically based off of Tim Goldens Directory
watching app
the function is as follows in entirety
def watchos(self, path_to_watch="C:\\"):
#get path or maintain current path of app
FILE_LIST_DIRECTORY = 0x0001
try: path_to_watch or "."
except: path_to_watch = "."
path_to_watch = os.path.abspath(path_to_watch)
out1 = "Watching %s at %s" % (path_to_watch, time.asctime()) +
"\n\n"
# FindFirstChangeNotification sets up a handle for watching
# file changes.
while 1:
hDir = win32file.CreateFile (
path_to_watch,
FILE_LIST_DIRECTORY,
win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
None,
win32con.OPEN_EXISTING,
win32con.FILE_FLAG_BACKUP_SEMANTICS,
None
)
change_handle = win32file.ReadDirectoryChangesW (
hDir,
1024,
True,#Heap Size include_subdirectories,
win32con.FILE_NOTIFY_CHANGE_FILE_NAME |
win32con.FILE_NOTIFY_CHANGE_DIR_NAME |
win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES |
win32con.FILE_NOTIFY_CHANGE_SIZE |
win32con.FILE_NOTIFY_CHANGE_LAST_WRITE |
win32con.FILE_NOTIFY_CHANGE_SECURITY,
None,
None
)
# Loop forever, listing any file changes. The WaitFor... will
# time out every half a second allowing for keyboard
interrupts
# to terminate the loop.
ACTIONS = {
1 : "Created",
2 : "Deleted",
3 : "Updated",
4 : "Renamed from something",
5 : "Renamed to something"
}
results = change_handle
for action, files in results:
full_filename = os.path.join(path_to_watch, files)
theact = ACTIONS.get(action, "Unknown")
yield str(full_filename) + " " + str(theact)
and the rpc client is as follows
import xmlrpclib, code
# Specify IP of Server here defualt port is 9000
url = "http://127.0.0.1:";
sock = xmlrpclib.ServerProxy(url, allow_none=True, verbose=0)
# use the interactive console to interact example "key.keyit()" will
start the logger
interp = code.InteractiveConsole({'key': sock})
interp.interact("Use the keyword, \"key\" to interact with the server")
Sorry if I posted to much code :-)
Thank you in advance
--
http://mail.python.org/mailman/listinfo/python-list
Re: Return a string result with out breaking loop
Hi I have done this without error
:D
Yield returns the result I am looking for... however it does not
continue looping. It does the same thing as return would
any suggestions
my code is as follows
serveraddr = ('', )
srvr = ThreadingServer(serveraddr, SimpleXMLRPCRequestHandler,
allow_none=True)
srvr.register_instance(theApp())
srvr.register_introspection_functions()
def watchos(path_to_watch="C:\\"):
#get path or maintain current path of app
FILE_LIST_DIRECTORY = 0x0001
try: path_to_watch or "."
except: path_to_watch = "."
path_to_watch = os.path.abspath(path_to_watch)
out1 = "Watching %s at %s" % (path_to_watch, time.asctime()) + "\n\n"
# FindFirstChangeNotification sets up a handle for watching
# file changes.
while 1:
hDir = win32file.CreateFile (
path_to_watch,
FILE_LIST_DIRECTORY,
win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
None,
win32con.OPEN_EXISTING,
win32con.FILE_FLAG_BACKUP_SEMANTICS,
None
)
change_handle = win32file.ReadDirectoryChangesW (
hDir,
1024,
True,#Heap Size include_subdirectories,
win32con.FILE_NOTIFY_CHANGE_FILE_NAME |
win32con.FILE_NOTIFY_CHANGE_DIR_NAME |
win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES |
win32con.FILE_NOTIFY_CHANGE_SIZE |
win32con.FILE_NOTIFY_CHANGE_LAST_WRITE |
win32con.FILE_NOTIFY_CHANGE_SECURITY,
None,
None
)
# Loop forever, listing any file changes. The WaitFor... will
# time out every half a second allowing for keyboard interrupts
# to terminate the loop.
ACTIONS = {
1 : "Created",
2 : "Deleted",
3 : "Updated",
4 : "Renamed from something",
5 : "Renamed to something"
}
results = change_handle
for action, files in results:
full_filename = os.path.join(path_to_watch, files)
theact = ACTIONS.get(action, "Unknown")
out2 = str(full_filename) + " " + str(theact)
yield str(out2)
servg = watchos()
srvr.register_function(servg.next, 'watchos')
srvr.register_multicall_functions()
srvr.serve_forever()
--
http://mail.python.org/mailman/listinfo/python-list
Re: Return a string result with out breaking loop
mmk guess I will have to look for alternate solutions for this project. Thank you all for your help cheers Andrew! Fredrik Lundh wrote: Andrew wrote: Yield returns the result I am looking for... however it does not continue looping. It does the same thing as return would the XML-RPC protocol doesn't really support your use case; for each call, the client issues a complete request package, and the server produces a complete response in return. -- http://mail.python.org/mailman/listinfo/python-list
Re: computer support
On 2008-08-29, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > hello every body in the group Hello Dr Nick :-) -- http://www.andrews-corner.org -- http://mail.python.org/mailman/listinfo/python-list
explain slice assignment to newb
please explain this behavior to a newb: >>> a = [1,2,3,4] >>> b = ["a","b","c","d"] >>> a [1, 2, 3, 4] >>> b ['a', 'b', 'c', 'd'] >>> a[0:2] [1, 2] >>> a [1, 2, 3, 4] >>> b[2:4] ['c', 'd'] >>> a[0:2] = b[0:2] >>> b[2:4] = a[2:4] >>> a ['a', 'b', 3, 4] >>> b ['a', 'b', 3, 4] >>> -- http://mail.python.org/mailman/listinfo/python-list
Re: Find similar images using python
I did this once for a motion dection algorithm. I used luminescence calculations to determine this. I basically broke the image into a grid of nine (3x3) areas and calculated the luminescene for each section and if it changed signficantly enough then there has been motions. The more sections, the more precise the detection will be. This was written in Visual Basic 4 and was able to do about 10 frames per seconds so you can get decent performance. I got the luminescence calculation from a classic math/computer science equation book. I should know the title but I'm blanking on it. Andy -- http://mail.python.org/mailman/listinfo/python-list
PyQt4 designer custom properties - combo box style
I am creating custom widgets for the PyQt4 Designer. I can create custom properties, but I'm looking for how to create a custom property that has a combo box drop down. I've seen them in the example widgets and tried following them, but they are using pre-defined items to populate their property, so it's not a very clear example of how to get the combo box property to work. Is there any other examples or help for this kind of setup? Thanks, Andrew -- http://mail.python.org/mailman/listinfo/python-list
Re: PyQt4 designer custom properties - combo box style
On Feb 4, 2:59 pm, David Boddie wrote: > On Tuesday 02 February 2010 22:25, Andrew wrote: > > > I am creating custom widgets for the PyQt4 Designer. I can create > > custom properties, but I'm looking for how to create a custom property > > that has a combo box drop down. I've seen them in the example widgets > > and tried following them, but they are using pre-defined items to > > populate their property, so it's not a very clear example of how to > > get the combo box property to work. > > Can you explain a bit more about what you have seen and what you are > trying to do. Are you trying to create a property that is treated > specially by Designer or do you want to get the data for the combo > box from somewhere else? I'm attempting to create a drop down property for a custom widget I'm creating. So when in designer and you scroll down to the custom properties, under the regular widget properties, one of them would be a drop down menu. The data to populate it will be coming from our API and currently is a list of string-items. Yes, it would be treated specially by Designer, since it's the only place it would be seen. In the PyQt4\examples\designer folder, it carries a number of custom widgets that will load into designer. The datetimeedit widget creates a custom drop down menu property. The plugin pulls its information from the QtCore libraries and from the QCalander Widget. Though I am unable to find a better example or even explanation of how it's actually creating that drop down menu. > > > Is there any other examples or help for this kind of setup? > > Have you seen this article? > > http://qt.nokia.com/doc/qq/qq26-pyqtdesigner.html No, I haven't, thanks. That might step in the right direction. I can't run it right now, so I'm not sure if it is putting a spinbox as it's property or just the value from the spin box. > > David Andrew -- http://mail.python.org/mailman/listinfo/python-list
2010 Congress on Computer Applications and Computational Science, Singapore [EI Compendex,ISTP,IEEE Xplore]
[ Please forward to those who may be interested. Thanks. ] == 2010 International Congress on Computer Applications and Computational Science CACS 2010 http://irast.org/conferences/CACS/2010 4-6 December 2010, Singapore == CACS 2010 aims to bring together researchers and scientists from academia, industry, and government laboratories to present new results and identify future research directions in computer applications and computational science. Topics of interest include, but are not limited to: Agent and Autonomous Systems Computational Biology and Bioinformatics Computer-Aided Design and Manufacturing Computer Architecture and VLSI Computer Control and Robotics Computer Graphics, Animation and Virtual Reality Computers in Education & Learning technology Computer Modeling and Simulations Computer Networks and Communications Computer Security and Privacy Computer Vision and Pattern Recognition Data Mining and Data Engineering Distributed and Services Computing Energy and Power Systems Intelligent Systems Internet and Web Systems Nano Technologies Real-Time and Embedded Systems Scientific Computing and Applications Signal, Image and Multimedia Processing Software Engineering Test Technologies CACS 2010 conference proceedings will be published by CPS which will include the conference proceedings in IEEE Xplore and submit the proceedings to Ei Compendex and ISTP for indexing. Singapore's cultural diversity reflects its colonial history and Chinese, Malay, Indian and Arab ethnicities. English is the dominant official language, which is convenient for foreign visitors. Places of interest, such as the Orchard Road district, Singapore Zoo, Night Safari, and Sentosa, attract millions of visitors a year. Singapore is a paradise for shopping, dinning, entertainment, and nightlife, with two new integrated resorts. Conference Contact: [email protected] Paper Submission Deadline: 15 May 2010 Review Decision Notifications: 15 August 2010 Final Papers and Author Registration Deadline: 9 September 2010 -- http://mail.python.org/mailman/listinfo/python-list
Extended deadline (15 July 2010): CACS Singapore [EI Compendex,ISTP,IEEE Xplore]
[ Please forward to those who may be interested. Thanks. ] == 2010 International Congress on Computer Applications and Computational Science CACS 2010 http://irast.org/conferences/CACS/2010 4-6 December 2010, Singapore == CACS 2010 aims to bring together researchers and scientists from academia, industry, and government laboratories to present new results and identify future research directions in computer applications and computational science. Topics of interest include, but are not limited to: Agent and Autonomous Systems Computational Biology and Bioinformatics Computer-Aided Design and Manufacturing Computer Architecture and VLSI Computer Control and Robotics Computer Graphics, Animation and Virtual Reality Computers in Education & Learning technology Computer Modeling and Simulations Computer Networks and Communications Computer Security and Privacy Computer Vision and Pattern Recognition Data Mining and Data Engineering Distributed and Services Computing Energy and Power Systems Intelligent Systems Internet and Web Systems Nano Technologies Real-Time and Embedded Systems Scientific Computing and Applications Signal, Image and Multimedia Processing Software Engineering Test Technologies CACS 2010 conference proceedings will be published by CPS which will include the conference proceedings in IEEE Xplore and submit the proceedings to Ei Compendex and ISTP for indexing. Singapore's cultural diversity reflects its colonial history and Chinese, Malay, Indian and Arab ethnicities. English is the dominant official language, which is convenient for foreign visitors. Places of interest, such as the Orchard Road district, Singapore Zoo, Night Safari, and Sentosa, attract millions of visitors a year. Singapore is a paradise for shopping, dinning, entertainment, and nightlife, with two new integrated resorts. Conference Contact: [email protected] Paper Submission Deadline with Extended: 15 July 2010 Review Decision Notifications: 15 August 2010 Final Papers and Author Registration Deadline: 9 September 2010 -- http://mail.python.org/mailman/listinfo/python-list
Deleting widgets from PyQt4 QFormWidget
I'm trying to remove the widgets from the QFormLayout widget from
PyQt4. According to the documentation I should be able to use the
command .takeAt(int) which will delete the widget from the layout and
then return to me the QLayoutWidget.
It currently is giving me back the widget, but is not removing it from
the layout.
At the moment, I'm simply trying to clear out all the widgets on the
layout with this:
def clearForm(self):
print ("Clearing")
print self.dataForm.rowCount()
for i in range(self.dataForm.rowCount()-1, -1, -1):
print " .",
tmp = self.dataForm.takeAt(i)
print tmp.widget()
tmp = ""
print self.dataForm.rowCount()
It goes through each widget on the layout, and prints out the
classes .__repr__ on the tmp.widget() line since tmp is a
QLayoutWidget. So it's doing the returning part, but they still exist
instead of being deleted like the documentation explains.
Am I missing a step or is this just broken? I haven't been able to
find anything else on this issue yet. If it's broke, is there any
potential workaround?
I'm using python 2.6.4 and PyQt4 4.7.6
Thanks,
Andrew
--
http://mail.python.org/mailman/listinfo/python-list
Re: Deleting widgets from PyQt4 QFormWidget
On Sep 15, 9:53 am, Andrew wrote:
> I'm trying to remove the widgets from the QFormLayout widget from
> PyQt4. According to the documentation I should be able to use the
> command .takeAt(int) which will delete the widget from the layout and
> then return to me the QLayoutWidget.
> It currently is giving me back the widget, but is not removing it from
> the layout.
> At the moment, I'm simply trying to clear out all the widgets on the
> layout with this:
>
> def clearForm(self):
> print ("Clearing")
> print self.dataForm.rowCount()
> for i in range(self.dataForm.rowCount()-1, -1, -1):
> print " .",
> tmp = self.dataForm.takeAt(i)
> print tmp.widget()
> tmp = ""
> print self.dataForm.rowCount()
>
> It goes through each widget on the layout, and prints out the
> classes .__repr__ on the tmp.widget() line since tmp is a
> QLayoutWidget. So it's doing the returning part, but they still exist
> instead of being deleted like the documentation explains.
>
> Am I missing a step or is this just broken? I haven't been able to
> find anything else on this issue yet. If it's broke, is there any
> potential workaround?
>
> I'm using python 2.6.4 and PyQt4 4.7.6
>
> Thanks,
> Andrew
QLayoutWidget, I meant a QWidgetItem.
--
http://mail.python.org/mailman/listinfo/python-list
pyqt4 Table Widget deleting c/c++ object
I have two issues dealing with the table widget, though they may be interconnected. I'm not sure. Both delete the cell widgets off of my table but leave the rows, and then when I have the table update, it complains the c++ object has been deleted. # self.tableData.setCellWidget(rowCount, 0, trackItem) # RuntimeError: underlying C/C++ object has been deleted I have a list of a custom widget class that keeps track of several directories. Each class gets put into a row on the table. I have a set of radio buttons that will show me different views of the data: All, New, Done, Errors, Warnings. When I switch views, I clear my table, set the row count to 0, and then add back in only the widgets I want to see. Error 1: I load in the data initially, and then repopulate the table, and then re-size the window, instantly all listed rows are cleared, but the rows stay. This only happened on the diagonal re-size (bottom left corner); not the up and down, or side to side re-size. Attempting to repopulate the table, resulted in: underlying C/C++ object has been deleted. Though it will put in the correct number of rows required. Everything worked fine as long as I did not re-size the window. Error 2: I load in the data initially, and then repopulate the table, the table clears and then nothing happens. No error messages or even visible rows. After several more repopulates it with either crash or tell me: underlying C/C++ object has been deleted. I had error 1 two days ago, then without changing the code, I now get error 2. I do not have to re-size the window for it to break now. I am using python 2.7 with PyQt4 4.7.7 Thanks for any insight, Andrew -- http://mail.python.org/mailman/listinfo/python-list
Re: pyqt4 Table Widget deleting c/c++ object
On Oct 18, 2:26 pm, Andrew wrote: > I have two issues dealing with the table widget, though they may be > interconnected. I'm not sure. Both delete the cell widgets off of my > table but leave the rows, and then when I have the table update, it > complains the c++ object has been deleted. > > # self.tableData.setCellWidget(rowCount, 0, trackItem) > # RuntimeError: underlying C/C++ object has been deleted > > I have a list of a custom widget class that keeps track of several > directories. Each class gets put into a row on the table. I have a set > of radio buttons that will show me different views of the data: All, > New, Done, Errors, Warnings. > When I switch views, I clear my table, set the row count to 0, and > then add back in only the widgets I want to see. > > Error 1: > I load in the data initially, and then repopulate the table, and then > re-size the window, instantly all listed rows are cleared, but the > rows stay. This only happened on the diagonal re-size (bottom left > corner); not the up and down, or side to side re-size. Attempting to > repopulate the table, resulted in: underlying C/C++ object has been > deleted. Though it will put in the correct number of rows required. > > Everything worked fine as long as I did not re-size the window. > > Error 2: > I load in the data initially, and then repopulate the table, the table > clears and then nothing happens. No error messages or even visible > rows. After several more repopulates it with either crash or tell me: > underlying C/C++ object has been deleted. > > I had error 1 two days ago, then without changing the code, I now get > error 2. I do not have to re-size the window for it to break now. > > I am using python 2.7 with PyQt4 4.7.7 > > Thanks for any insight, > Andrew Here is a working example of what I'm describing above. http://dl.dropbox.com/u/11715751/trackSetLoader.rar Thanks. -- http://mail.python.org/mailman/listinfo/python-list
nntplib and ssl
I'm working on a personal project that, among other things, needs to talk to a news server. Python's nntplib seems ideal for my purposes, but as far as I can see it doesn't support nntps connections. If I understand nntp correctly (I may not) that means, among other things, it sends passwords in cleartext. That won't do. I note that python has a separate ssl module but I must admit I'm at a loss as to how to fit the two together. I'm working from the Python 3.1.2 documentation, page noted here: http://docs.python.org/py3k/library/nntplib.html Anyone have suggestions? -- Andrew -- http://mail.python.org/mailman/listinfo/python-list
Re: nntplib and ssl
On Fri, 22 Oct 2010 23:23:31 +0200, Antoine Pitrou wrote: > On Fri, 22 Oct 2010 17:02:07 -0400 > Andrew wrote: >> >> Python's nntplib seems ideal for my purposes, but as far as I can see it >> doesn't support nntps connections. If I understand nntp correctly (I may >> not) that means, among other things, it sends passwords in cleartext. >> >> That won't do. I note that python has a separate ssl module but I must >> admit I'm at a loss as to how to fit the two together. I'm working from the >> Python 3.1.2 documentation, page noted here: > > There's an issue open for this: > http://bugs.python.org/issue1926 I found that but noted it was dated for a few years ago. Of course like an idiot I didn't scroll down the page and see that it was still active as of last month. > A patch is there, but it's totally outdated. If you're interested, you > could provide a new patch against py3k SVN (that is, the next 3.2, > although the deadline for new features is in a couple of weeks). I'd say I'm interested...but despite not being too terrible a programmer, I've never written and submitted a patch for anything in my life and have no idea how to go about it. ;-) I suppose google could solve that problem. > It's probably not very difficult to write such a patch. You mostly need > to wrap the connection in an SSL socket, then give that socket to the > NNTP connection class. Details will be found out by studying the > nntplib code. I might take a crack at it if I can figure out how. Thanks for the help. -- Andrew -- http://mail.python.org/mailman/listinfo/python-list
Re: pyqt4 Table Widget deleting c/c++ object
On Oct 19, 2:29 pm, David Boddie wrote: > On Monday 18 October 2010 23:26, Andrew wrote: > > > I have two issues dealing with the table widget, though they may be > > interconnected. I'm not sure. Both delete the cell widgets off of my > > table but leave the rows, and then when I have the table update, it > > complains the c++ object has been deleted. > > > # self.tableData.setCellWidget(rowCount, 0, trackItem) > > # RuntimeError: underlying C/C++ object has been deleted > > This is because you pass your widgets to this method and later ask > the table to clear the contents of the table. When it does so, it > deletes the underlying widgets, leaving only Python wrappers. > > The documentation mentions that the table takes ownership of the > widget: > > http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qtablewidg... > > I had read that, but I did not fully understand what that actually was supposed to mean. like a 'Ok it has ownership, good for it?' I hadn't run into such a problem before either in any form. Now I know. > > > I have a list of a custom widget class that keeps track of several > > directories. Each class gets put into a row on the table. I have a set > > of radio buttons that will show me different views of the data: All, > > New, Done, Errors, Warnings. > > When I switch views, I clear my table, set the row count to 0, and > > then add back in only the widgets I want to see. > > > Error 1: > > I load in the data initially, and then repopulate the table, and then > > re-size the window, instantly all listed rows are cleared, but the > > rows stay. This only happened on the diagonal re-size (bottom left > > corner); not the up and down, or side to side re-size. Attempting to > > repopulate the table, resulted in: underlying C/C++ object has been > > deleted. Though it will put in the correct number of rows required. > > > Everything worked fine as long as I did not re-size the window. > > This may only be a symptom of the behaviour and not a guarantee that > the code was working correctly up until the point when the resize > occurred. > > > Error 2: > > I load in the data initially, and then repopulate the table, the table > > clears and then nothing happens. No error messages or even visible > > rows. After several more repopulates it with either crash or tell me: > > underlying C/C++ object has been deleted. > > > I had error 1 two days ago, then without changing the code, I now get > > error 2. I do not have to re-size the window for it to break now. > > I recommend that you create a list of non-widget data structures in > your parsePath() method and create widgets on the fly in your addToTable() > method. If you need to retain information when you repopulate the table > then update the data structures that correspond to the widgets just before > you clear the table. > > David Thanks, it does work now that I've split it into a data and widget class and create the widgets on the fly. Thanks for the help and sorry for the delayed response. Andrew -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter: how to create (modal) dialogs a la tk_dialog?
On Thu, 28 Oct 2010 13:57:24 + (UTC), Olaf Dietrich wrote: > Could it be that these parts of Tkinter > are not particularly extensively documented? (Or am I searching > with the wrong expressions?) > Olaf I've wondered about this too. The tkinter and tkinter.ttk sections of the documentation seem to have a large number of classes and functions listed as part of the module but without any more than a line or two about what they do or how to use them. The last (and only, so far) time I used tkinter, I often found it more useful to examine Tk documentation to discover, say, what options or arguments were possible and/or useful, and then try to translate that into the python/tkinter equivelant. -- Andrew -- http://mail.python.org/mailman/listinfo/python-list
Making safe file names
Currently, I keep Last.fm artist data caches to avoid unnecessary API calls and have been naming the files using the artist name. However, artist names can have characters that are not allowed in file names for most file systems (e.g., C/A/T has forward slashes). Are there any recommended strategies for naming such files while avoiding conflicts (I wouldn't want to run into problems for an artist named C-A-T or CAT, for example)? I'd like to make the files easily identifiable, and there really are no limits on what characters can be in an artist name. -- CPython 3.3.1 | Windows NT 6.2.9200 / FreeBSD 9.1 -- http://mail.python.org/mailman/listinfo/python-list
Re: Making safe file names
On 2013.05.07 17:18, Fábio Santos wrote: > I suggest Base64. b64encode > (http://docs.python.org/2/library/base64.html#base64.b64encode) and > b64decode take an argument which allows you to eliminate the pesky "/" > character. It's reversible and simple. > > More suggestions: how about a hash? Or just use IDs from the database? None of these would work because I would have no idea which file stores data for which artist without writing code to figure it out. If I were to end up writing a bug that messed up a few of my cache files and noticed it with a specific artist (e.g., doing a "now playing" and seeing the wrong tags), I would either have to manually match up the hash or base64 encoding in order to delete just that file so that it gets regenerated or nuke and regenerate my entire cache. -- CPython 3.3.1 | Windows NT 6.2.9200 / FreeBSD 9.1 -- http://mail.python.org/mailman/listinfo/python-list
Re: Making safe file names
On 2013.05.07 17:01, Terry Jan Reedy wrote: > Sounds like you want something like the html escape or urlencode > functions, which serve the same purpose of encoding special chars. > Rather than invent a new tranformation, you could use the same scheme > used for html entities. (Sorry, I forget the details.) It is possible > that one of the functions would work for you as is, or with little > modification. This has the problem of mangling non-ASCII characters (and artist names with non-ASCII characters are not rare). I most definitely want to keep as many characters untouched as possible so that the files are easy to identify by looking at the file name. Ideally, only characters that file systems don't like would be transformed. -- CPython 3.3.1 | Windows NT 6.2.9200 / FreeBSD 9.1 -- http://mail.python.org/mailman/listinfo/python-list
Re: Making safe file names
On 2013.05.07 17:37, Jens Thoms Toerring wrote:
> You
> could e.g. replace all characters not allowed by the file
> system by their hexidecimal (ASCII) values, preceeded by a
> '%" (so '/' would be changed to '%2F', and also encode a '%'
> itself in a name by '%25'). Then you have a well-defined
> two-way mapping ("isomorphic" if I remember my math-lear-
> nining days correctly) between the original name and the
> way you store it. E.g.
>
> "C/A/T" would become "C%2FA%2FT"
>
> and
>
> "C%2FA/T" would become "C%252FA%2FT"
>
> You can translate back and forth between them with not too
> much effort.
>
> Of course, that assumes that '%' is a character allowed by
> your file system - otherwise pick some other one, any one
> will do in principle. It's a bit harder for a human to in-
> terpret but rathe likely not that much of a problem.
Yes, something like this is what I am trying to achieve. Judging by the
responses I've gotten so far, I think I'll have to roll my own
transformation scheme since URL encoding and the like transform Unicode
characters. I can memorize that 植松伸夫 is a Japanese composer who
is well-known for his works in the Final Fantasy series of video games. Trying
to match up the URL-encoded version to an artist would be
almost impossible when I have several other artist names that have no ASCII
characters.
--
CPython 3.3.1 | Windows NT 6.2.9200 / FreeBSD 9.1
--
http://mail.python.org/mailman/listinfo/python-list
Re: Making safe file names
On 2013.05.07 19:14, Dave Angel wrote: > You also need to decide how to handle Unicode characters, since they're > different for different OS. In Windows on NTFS, filenames are in > Unicode, while on Unix, filenames are bytes. So on one of those, you > will be encoding/decoding if your code is to be mostly portable. Characters outside whatever sys.getfilesystemencoding() returns won't be allowed. If the user's locale settings don't support Unicode, my program will be far from the only one to have issues with it. Any problem reports that arise from a user moving between legacy encodings will generally be ignored. I haven't yet decided how I will handle artist names with characters outside UTF-8, but inside UTF-16/32 (UTF-16 is just fine on Windows/NTFS, but on Unix(-ish) systems, many use UTF-8 in their locale settings). > Don't forget that ls and rm may not use the same encoding you're using. > So you may not consider it adequate to make the names legal, but you > may also want they easily typeable in the shell. I don't understand. I have no intention of changing Unicode characters. This is not a Unicode issue since (modern) file systems will happily accept it. The issue is that certain characters (which are ASCII) are not allowed on some file systems: \ / : * ? " < > | @ and the NUL character The first 9 are not allowed on NTFS, the @ is not allowed on ext3cow, and NUL and / are not allowed on pretty much any file system. Locale settings and encodings aside, these 11 characters will need to be escaped. -- CPython 3.3.1 | Windows NT 6.2.9200 / FreeBSD 9.1 -- http://mail.python.org/mailman/listinfo/python-list
Re: Making safe file names
On 2013.05.07 20:28, Neil Hodgson wrote: > http://support.microsoft.com/kb/74496 > http://en.wikipedia.org/wiki/Nul_%28band%29 I can indeed confirm that at least 'nul' cannot be used as a filename. However, I add an extension to the file names to identify them as caches. -- CPython 3.3.1 | Windows NT 6.2.9200 / FreeBSD 9.1 -- http://mail.python.org/mailman/listinfo/python-list
Re: Making safe file names
On 2013.05.07 20:45, Dave Angel wrote: > While we're looking for trouble, there's also case insensitivity. > Unclear if the user cares, but tom and TOM are the same file in most > configurations of NT. Artist names on Last.fm cannot differ only in case. This does remind me to make sure to update the case of the artist name as necessary, though. For example, if Sam becomes SAM again (I have seen Last.fm change the case for artist names), I need to make sure that I don't end up with two file names differing only in case. -- CPython 3.3.1 | Windows NT 6.2.9200 / FreeBSD 9.1 -- http://mail.python.org/mailman/listinfo/python-list
Re: Making safe file names
On 2013.05.07 20:13, Dave Angel wrote: > So you're comfortable typing arbitrary characters? what about all the > characters that have identical displays in your font? Identification is more important than typing. I can copy and paste into a terminal if necessary. I don't foresee typing out one of the filenames being anything more than a rare occurrence, but I will occasionally just read the list. > What about viewing > 0x07 in the terminal window? Or 0x04? I don't think Last.fm will even send those characters. In any case, control characters in artist names are rare enough that it's not worth the trouble to write the code to avoid the problems associated with them. > As soon as you have a small, finite list of invalid characters, writing > an escape system is pretty easy. Probably. I was just hoping there was an existing system that would work, but as I said in a different reply, it would seem I need to roll my own. -- CPython 3.3.1 | Windows NT 6.2.9200 / FreeBSD 9.1 -- http://mail.python.org/mailman/listinfo/python-list
Re: Making safe file names
On 2013.05.07 22:40, Steven D'Aprano wrote: > There aren't any characters outside of UTF-8 :-) UTF-8 covers the entire > Unicode range, unlike other encodings like Latin-1 or ASCII. You are correct. I'm not sure what I was thinking. >> I don't understand. I have no intention of changing Unicode characters. > > Of course you do. You even talk below about Unicode characters like * > and ? not being allowed on NTFS systems. I worded that incorrectly. What I meant, of course, is that I intend to preserve as many characters as possible and have no need to stay within ASCII. > If you have an artist with control characters in their name, like newline > or carriage return or NUL, I think it is fair to just drop the control > characters and then give the artist a thorough thrashing with a halibut. While the thrashing with a halibut may be warranted (though I personally would use a rubber chicken), conflicts are problematic. > Does your mapping really need to be guaranteed reversible? If you have an > artist called "JoeBlow", and another artist called "Joe\0Blow", and a > third called "Joe\nBlow", does it *really* matter if your application > conflates them? Yes and yes. Some artists like to be real cute with their names and make witch house artist names look tame in comparison, and some may choose to use names similar to some very popular artists. I've also seen people scrobble fake artists with names that look like real artist names (using things like a non-breaking space instead of a regular space) with different artist pictures in order to confuse and troll people. If I could remember the user profiles with this, I'd link them. Last.fm is a silly place. As I said before though, I don't think control characters are even allowed in artist names (likely for technical reasons). -- CPython 3.3.1 | Windows NT 6.2.9200 / FreeBSD 9.1 -- http://mail.python.org/mailman/listinfo/python-list
Re: Making safe file names
On 2013.05.08 19:16, Roy Smith wrote: > Yup. At Songza, we deal with this crap every day. It usually bites us > the worst when trying to do keyword searches. When somebody types in > "Blue Oyster Cult", they really mean "Blue Oyster Cult", and our search > results need to reflect that. Likewise for Ke$ha, Beyonce, and I don't > even want to think about the artist formerly known as an unpronounceable > glyph. > > Pro-tip, guys. If you want to form a band, and expect people to be able > to find your stuff in a search engine some day, don't play cute with > your name. It's a thing (especially in witch house) to make names with odd glyphs in order to be harder to find and be more "underground". Very silly. Try doing searches for these artists with names like these: http://www.last.fm/music/%E2%96%BC%E2%96%A1%E2%96%A0%E2%96%A1%E2%96%A0%E2%96%A1%E2%96%A0 http://www.last.fm/music/ki%E2%80%A0%E2%80%A0y+c%E2%96%B2t -- CPython 3.3.1 | Windows NT 6.2.9200 / FreeBSD 9.1 -- http://mail.python.org/mailman/listinfo/python-list
Re: Making safe file names
On 2013.05.08 18:37, Dennis Lee Bieber wrote: > And now you've seen why music players don't show the user the > physical file name, but maintain a database mapping the internal data > (name, artist, track#, album, etc.) to whatever mangled name was needed > to satisfy the file system. Tags are used mainly for organization but a nice benefit of tags is that they are not subject to file system or URL or whatever other limits. If an audio file has no metadata, most players will show the file name. -- CPython 3.3.1 | Windows NT 6.2.9200 / FreeBSD 9.1 -- http://mail.python.org/mailman/listinfo/python-list
Re: Differences of "!=" operator behavior in python3 and python2 [ bug? ]
On 2013.05.13 17:53, Mark Lawrence wrote: > I much prefer the alternative <> for != but some silly people insisted > that this be removed from Python3. It's not removed from Python 3, though: Python 3.3.1 (v3.3.1:d9893d13c628, Apr 6 2013, 20:30:21) [MSC v.1600 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from __future__ import barry_as_FLUFL >>> 3 <> 2 True -- CPython 3.3.1 | Windows NT 6.2.9200 / FreeBSD 9.1 -- http://mail.python.org/mailman/listinfo/python-list
IndexError: pop index out of range
hello,
going fru some basic examples and can't figureout why the following errors
out. Help is very much appreciated:
def front_x(words):
# +++your code here+++
print "words passed : ", words
list_xx = []
list_temp = words[:]
print "list_temp -", list_temp
print "words -", words
for idx, val in enumerate(words):
print val, idx
# str_idx = val.find('x',0,2)
if val[0] == 'x':
vl = list_temp.pop(idx)
list_xx.append(vl)
print "appending list_xx", list_xx
list_xx.sort
list_temp.sort
print "words sorted : " + str(words)
print "list_temp sorted : ", list_temp
list_xx.append(words)
print "list_xx" + str(list_xx)
return True
front_x
words passed : ['bbb', 'ccc', 'axx', 'xzz', 'xaa']
list_temp - ['bbb', 'ccc', 'axx', 'xzz', 'xaa']
words - ['bbb', 'ccc', 'axx', 'xzz', 'xaa']
bbb 0
ccc 1
axx 2
xzz 3
appending list_xx ['xzz']
xaa 4
Traceback (most recent call last):
File
"/home/az/work/Python/Google_Course/google-python-exercises/basic/list1.py",
line 119, in
main()
File
"/home/az/work/Python/Google_Course/google-python-exercises/basic/list1.py",
line 100, in main
test(front_x(['bbb', 'ccc', 'axx', 'xzz', 'xaa']),
File
"/home/az/work/Python/Google_Course/google-python-exercises/basic/list1.py",
line 55, in front_x
vl = list_temp.pop(idx)
IndexError: pop index out of range
--
http://mail.python.org/mailman/listinfo/python-list
Question re: objects and square grids
Hello everyone. I am having a good time programming with Python 3.3 and Pygame. Pygame seems like the perfect platform for the kind of simple games that I want to make. What I have currently programmed is basically a drawn rectangle filled with 200 squares, each side of the squares being 43 pixels. The rectangle is 20 squares by 10 squares. This grid is what I want to have the entire game on. There will be pieces that move certain numbers of squares, perform actions that effect pieces on certain squares, etc. The possibilities are endless. So what I am now trying to do is organize these squares into objects that I can easily reference when programming things related to the squares. So far, I have done this: A1 = pygame.Rect(10, 12, 43, 43) A2 A3 A4 B1 B2 etc. where said integers are the precise location of the top left-most square for A1, and onward down the line. I would guess that I could continue on in such a fashion, with appropriate box names for each square. But I'm running into the problem of confirming that the code above actually does something useful. For example, I would love to be able to turn A1 a different color, but how does this work? How do I actually utilize these object variable names? Are there methods that I am not aware of, because most things I try tend to do nothing or crash the game. For example, A1.fill(BLUE) does not work. Any general advice about how to organize my squares into something that is easy to program for would be VERY appreciated. Basically all the games I want to make involve square grids like this, so I want to know as much about them as possible. Thank you very much for reading this, Andrew -- http://mail.python.org/mailman/listinfo/python-list
Re: Question re: objects and square grids
Now I want to show you what I have written: row = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) column = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20) SQUARESIZE = 43 grid = [] for row in range(10): row_squares = [] for column in range(20): rect = Rect(12 + column * SQUARESIZE, 10 + row * SQUARESIZE, SQUARESIZE, SQUARESIZE) row_squares.append(rect) grid.append(row_squares) It appears to be working (that is, the program still runs without crashing). So now, how can I utilize this new grid list? Thank you for the help so far, I feel like the entire grid is now being worked out. -Andrew On Wed, May 15, 2013 at 3:57 PM, Dave Angel wrote: > On 05/15/2013 02:14 PM, Andrew Bradley wrote: > > Please reply on the list, not privately, unless it's something like a > simple thank-you. Typically, you'd do a reply-all, then delete the people > other than the list itself. Or if you're using Thunderbird, you could just > reply-list. > > > Thank you very much for your response: it seems excellent, but I'm > afraid I > > do not understand it fully. Your code here: > > > > > maxrows = 10 > > maxcols = 20 > > grid = [] > > for row in range(maxrows): > > rowdata = [] > > for column in range(maxcols): > > arg1 = ... > > arg2 = ... > > arg3 = ... > > arg4 = ... > > rowdata.append(pygame.Rect(arg > > 1, arg2, arg3, arg4) > > grid.append(rowdata) > > > > Seems very good, but keep in mind I just started programming last week, > and > > this is hard for me to wrap my head around. Do I really just write grid = > > []? or is this like a def grid(): function? > > This code was intended to replace the 200 lines you started, A1= pygame... > A2= A3= etc. I'd have put them inside a function, but this is just one > of the things I'd have initialized in such a function. grid is a list of > lists, not a function. > > > > What do you mean by rowdata = []? > > [] is the way you define an empty list. Another way might be: > rowdata = list() > > > > And how exactly would I make the formula for a rect call? > > Well, for row==0 and col==0, you say you wanted 10, 12, 43, and 43 for the > four parameters. But you never said how you were going to (manually) > calculate those numbers for other cells. Only once you've decided that can > you fill in "formulas" for arg1 and arg2. I suspect that arg3 and arg4 are > simply 43 and 43 respectively, since you want all the cells to be the same > size. > > taking my clue from Ian, I might try: > > x_offset = 10 > y_offset = 12 > width = height = 43 > arg1 = column * width + x_offset > arg2 = row * height + y_offset > arg3 = width > arg4 = height > > That assumes that there is no gap between cells in this grid. If you want > a gap, then the width value used in the arg1 formula would be more than 43 > (width). Likewise the height value used in the arg2 formula would be more > than 43 (height). > > > If there's a good website for these kind of details, I would appreciate > that too. > > You cannot begin to write a non-trivial program in Python without > understanding lists pretty thoroughly. Perhaps you should start with Alan > Gauld's tutorial, which doesn't assume previous programming experience. >http://www.alan-g.me.uk/ > > I haven't studied it, as Python was about my 35th programming language. > But he's very active on Python-tutor, and explains things very well. So > his website is probably very good as well. > > Now, as you can see from Ian's message, writing a game using pygame will > require quite a bit of other understanding. He demonstrates with classes > to represent cells, which is indeed what I'd do. But I suspect you're not > nearly ready to consider writing classes. (You use classes all the time. > For example, 5 is an instance of class int.) > > > -- > DaveA > > > > -- > DaveA > -- > http://mail.python.org/**mailman/listinfo/python-list<http://mail.python.org/mailman/listinfo/python-list> > -- http://mail.python.org/mailman/listinfo/python-list
Re: Question re: objects and square grids
ok, now I have tested this more thoroughly, and it seems i can only do the grid[x][y] function up to grid[9][9], when i really should be able to be doing up to grid[10][20]. What exactly is the function of this row_squares list? On Wed, May 15, 2013 at 4:35 PM, Andrew Bradley wrote: > Now I want to show you what I have written: > > row = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) > column = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, > 18, 19, 20) > SQUARESIZE = 43 > > grid = [] > for row in range(10): > row_squares = [] > for column in range(20): > rect = Rect(12 + column * SQUARESIZE, 10 + row * SQUARESIZE, > SQUARESIZE, SQUARESIZE) > row_squares.append(rect) > grid.append(row_squares) > > It appears to be working (that is, the program still runs without > crashing). So now, how can I utilize this new grid list? Thank you for the > help so far, I feel like the entire grid is now being worked out. > -Andrew > > > > On Wed, May 15, 2013 at 3:57 PM, Dave Angel wrote: > >> On 05/15/2013 02:14 PM, Andrew Bradley wrote: >> >> Please reply on the list, not privately, unless it's something like a >> simple thank-you. Typically, you'd do a reply-all, then delete the people >> other than the list itself. Or if you're using Thunderbird, you could just >> reply-list. >> >> > Thank you very much for your response: it seems excellent, but I'm >> afraid I >> > do not understand it fully. Your code here: >> >> > >> > maxrows = 10 >> > maxcols = 20 >> > grid = [] >> > for row in range(maxrows): >> > rowdata = [] >> > for column in range(maxcols): >> > arg1 = ... >> > arg2 = ... >> > arg3 = ... >> > arg4 = ... >> > rowdata.append(pygame.Rect(arg >> > 1, arg2, arg3, arg4) >> > grid.append(rowdata) >> > >> > Seems very good, but keep in mind I just started programming last week, >> and >> > this is hard for me to wrap my head around. Do I really just write grid >> = >> > []? or is this like a def grid(): function? >> >> This code was intended to replace the 200 lines you started, A1= >> pygame... A2= A3= etc. I'd have put them inside a function, but this is >> just one of the things I'd have initialized in such a function. grid is a >> list of lists, not a function. >> >> >> > What do you mean by rowdata = []? >> >> [] is the way you define an empty list. Another way might be: >> rowdata = list() >> >> >> > And how exactly would I make the formula for a rect call? >> >> Well, for row==0 and col==0, you say you wanted 10, 12, 43, and 43 for >> the four parameters. But you never said how you were going to (manually) >> calculate those numbers for other cells. Only once you've decided that can >> you fill in "formulas" for arg1 and arg2. I suspect that arg3 and arg4 are >> simply 43 and 43 respectively, since you want all the cells to be the same >> size. >> >> taking my clue from Ian, I might try: >> >> x_offset = 10 >> y_offset = 12 >> width = height = 43 >> arg1 = column * width + x_offset >> arg2 = row * height + y_offset >> arg3 = width >> arg4 = height >> >> That assumes that there is no gap between cells in this grid. If you >> want a gap, then the width value used in the arg1 formula would be more >> than 43 (width). Likewise the height value used in the arg2 formula would >> be more than 43 (height). >> >> > If there's a good website for these kind of details, I would appreciate >> that too. >> >> You cannot begin to write a non-trivial program in Python without >> understanding lists pretty thoroughly. Perhaps you should start with Alan >> Gauld's tutorial, which doesn't assume previous programming experience. >>http://www.alan-g.me.uk/ >> >> I haven't studied it, as Python was about my 35th programming language. >> But he's very active on Python-tutor, and explains things very well. So >> his website is probably very good as well. >> >> Now, as you can see from Ian's message, writing a game using pygame will >> require quite a bit of other understanding. He demonstrates with classes >> to represent cells, which is indeed what I'd do. But I suspect you're not >> nearly ready to consider writing classes. (You use classes all the time. >> For example, 5 is an instance of class int.) >> >> >> -- >> DaveA >> >> >> >> -- >> DaveA >> -- >> http://mail.python.org/**mailman/listinfo/python-list<http://mail.python.org/mailman/listinfo/python-list> >> > > -- http://mail.python.org/mailman/listinfo/python-list
Re: Question re: objects and square grids
> > > SQUARESIZE = 43 >>> >>> grid = [] >>> for row in range(10): >>> row_squares = [] >>> for column in range(20): >>> rect = Rect(12 + column * SQUARESIZE, 10 + row * SQUARESIZE, >>> SQUARESIZE, SQUARESIZE) >>> row_squares.append(rect) >>> grid.append(row_squares) >>> >>> It appears to be working (that is, the program still runs without >>> crashing). >>> >> > Sorry, but that's no criteria. Question is whether it's doing what you > want. Are the rows 20 across and are there 10 of them? Do the values of > each individual rect look right? print is your friend. Yes, I have gotten rid of that part with the 1, 2, 3, 4, etc., and now the code appears to be working up to [9][19]. Thank you very much. The coordinates all do look correct, and there are 200 rectangles when I do list(grid). > > > So now, how can I utilize this new grid list? Thank you for the >>> help so far, I feel like the entire grid is now being worked out. >>> -Andrew >>> >>> > That's a Pygame question, and I told you at the beginning, I can't really > help with that. I'd like to learn, but not this week. > > Others - can you show some minimal code to use these grid parameters to > color selected squares of the pygame window? > > Yes, I would very much like some help or general advice now about utilizing this grid thing. How can I refer to these square's new numerical values to do things with them? Will I be using things like "grid[0][1]" in specific functions and methods to refer to squares now? That is what I would like to do, somehow. > > -- > DaveA > -- > http://mail.python.org/**mailman/listinfo/python-list<http://mail.python.org/mailman/listinfo/python-list> > I apologize if these questions are too rudimentary--I am trying to wrap my head around how this language works in a more general sense so I can start applying it to things. -Andrew -- http://mail.python.org/mailman/listinfo/python-list
Re: python sockets question
On 2013.05.15 20:47, Eric Miller wrote: > Can python sockets be used to capture IP traffic when the traffic is > originating from a non-python source? Python just exposes the underlying OS socket interface. There is nothing special about sockets in Python. The whole point is to connect heterogeneous systems. I can use Python on Windows to create a client that will connect to a service written in C running on Solaris or to something written in Java running on Linux. -- CPython 3.3.1 | Windows NT 6.2.9200 / FreeBSD 9.1 -- http://mail.python.org/mailman/listinfo/python-list
Re: Python for philosophers
Tim Daneliuk wrote: > All You People are making this way too hard. To understand how > questions like the OPs ought be resolved, please read: > > http://pvspade.com/Sartre/cookbook.html On this list, I would expect a Sartre reference to be something like this: https://www.youtube.com/watch?v=crIJvcWkVcs -- CPython 3.3.1 | Windows NT 6.2.9200 / FreeBSD 9.1 -- http://mail.python.org/mailman/listinfo/python-list
Re: executing python scripts that are symlinked
On 2013.05.16 02:48, Charles Smith wrote: > Hi. > > How can I say, from the cmd line, that python should take my CWD as my > CWD, and not the directory where the script actually is? > > > I have a python script that works fine when it sits in directory WC, > but if I move it out of WC to H and put a symlink from H/script to WC, > it doesn't find the packages that are in WC. Also, if I use the > absolute path to H, it won't find them, but I guess I can understand > that. Symlinks can find their targets, but targets have absolutely no way of knowing where symlinks to them are. It's one-way. It would work if the actual file were in WC and you created a symlink inside H. -- CPython 3.3.1 | Windows NT 6.2.9200 / FreeBSD 9.1 -- http://mail.python.org/mailman/listinfo/python-list
Re: How to raise a socket "104 connection reset by peer error"
On 2013.05.21 10:26, loial wrote: > For testing purposes I want my code to raise a socket "connection reset by > peer" error, so that I can test how I handle it, but I am not sure how to > raise the error. Arbitrary exceptions can be raised with the raise keyword. In Python 3.3, that exact error got its own builtin exception: http://docs.python.org/3.3/tutorial/errors.html#raising-exceptions http://docs.python.org/3.3/library/exceptions.html#ConnectionResetError In earlier versions of Python, you will have to raise OSError and set its errno attribute. -- CPython 3.3.2 | Windows NT 6.2.9200 / FreeBSD 9.1 -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 378: Format Specifier for Thousands Separator
On 2013.05.21 14:26, Mark Lawrence wrote: > On 21/05/2013 20:13, Skip Montanaro wrote: >>> Thank you, but let me rephrase it. I'm already using str.format() but I'd >>> like to use '%' (BINARY_MODULO) operator instead. >> >> That's unlikely to change. If not deprecated already string >> interpolation using the modulo operator has lost favor to the string >> object's format method. >> > > Please stop perpetuating this myth, see > http://mail.python.org/pipermail/python-dev/2012-February/116789.html > and http://bugs.python.org/issue14123 > What myth? People should indeed be using .format(), but no one said % formatting was going away soon. Also, the suggested change to the docs wasn't made and the issue is closed. The current docs do not say that % formatting isn't going to be deprecated, but it does mention its caveats and suggests .format(). If you are trying to say that % formatting will never ever go away, then you are wrong. It is highly unlikely to go away in a 3.x release, but /may/ get phased out in Python 4.0. -- CPython 3.3.2 | Windows NT 6.2.9200 / FreeBSD 9.1 -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 378: Format Specifier for Thousands Separator
On 2013.05.21 21:59, Steven D'Aprano wrote: > On Tue, 21 May 2013 14:53:54 -0500, Andrew Berg wrote: > >> On 2013.05.21 14:26, Mark Lawrence wrote: > >>> Please stop perpetuating this myth, see >>> http://mail.python.org/pipermail/python-dev/2012-February/116789.html >>> and http://bugs.python.org/issue14123 >>> >> What myth? > > The myth that % string formatting is deprecated. It is not deprecated. Skip didn't say that it was deprecated. >> but no one said % formatting was going away soon. > > True, but only for the definition "no one = all the people who insist > that % is deprecated, or soon to be deprecated". Perhaps I missed something, but who is insisting this? > What happens in Python 4000 is irrelevant. If somebody is trying to > "future proof" their code for a version that *may never exist*, and if it > does exist is likely to be six or eight years away from even starting the > design phase, they are wasting their time. It is hard enough to track a > moving target, it is impossible to track a target that isn't even a gleam > in GvR's eye yet. I think you misunderstand. I'm not suggesting that format() be used simply because % formatting could be deprecated at some unknown time years from now; I was clarifying the status of % formatting. -- CPython 3.3.2 | Windows NT 6.2.9200 / FreeBSD 9.1 -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessing Json data (I think I am nearly there) complete beginner
On 2013.05.23 11:09, Andrew Edwards-Adams wrote: > I was recommended to use the following code to access the Json data directly, > however I cannot get it to return anything. Where exactly is the problem? Do you not get JSON back? Do you get the wrong values? Do you get a KeyError or IndexError trying to get values from text1? Are there gremlins going around flipping bits in memory? It's good that you posted code, but "really cant get anything out of this" isn't very useful. -- CPython 3.3.2 | Windows NT 6.2.9200 / FreeBSD 9.1 -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessing Json data (I think I am nearly there) complete beginner
On 2013.05.23 11:58, Andrew Edwards-Adams wrote: > If there was a trackback/debug I might know where to look, but its not > yielding errors, its simply yielding nothing. What i dont know, is if it is > the code that isnt working, or what I am inputting in the " print > text1['rows'][0]['id']" that isnt working. If fed a valid JSON object, json.loads() will return a regular dictionary. You can print (or pretty print with the pprint module) text1 to see everything. If you're not familiar with dictionaries and lists, thoroughly read the tutorial before writing or modifying any more code. http://docs.python.org/2/library/json.html#json.loads -- CPython 3.3.2 | Windows NT 6.2.9200 / FreeBSD 9.1 -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessing Json data (I think I am nearly there) complete beginner
On 2013.05.23 11:58, Andrew Edwards-Adams wrote: > Hi thanks for the reply Andrew, my first bit of code was heading in the right > direction I was managing to pull out the usernames from the JSON, using REGEX. It's also worth mentioning that regexes are almost always the wrong tool, especially for standardized formats like JSON. They can be very useful when nothing saner will get the job done, but are a nasty mess with no real benefit otherwise. -- CPython 3.3.2 | Windows NT 6.2.9200 / FreeBSD 9.1 -- http://mail.python.org/mailman/listinfo/python-list
Re: Prepending string "@" to usernames
On 2013.05.24 17:53, Thomas Murphy wrote: > I know I'm iterating wrong. May I ask how? .split() already returns a list, so instead of iterating over the list and getting a single username, you iterate over the list and get a single list. -- CPython 3.3.2 | Windows NT 6.2.9200 / FreeBSD 9.1 -- http://mail.python.org/mailman/listinfo/python-list
Re: I want to know how to implement concurrent threads in Python
On 2013.05.26 14:10, Daniel Gagliardi wrote: > I want to know how to implement concurrent threads in Python With the threading module in the standard library. http://docs.python.org/3.3/library/threading.html There are plenty of tutorials on this out there; we'll be happy to help if you're stuck on something specific. -- CPython 3.3.2 | Windows NT 6.2.9200 / FreeBSD 9.1 -- http://mail.python.org/mailman/listinfo/python-list
Re: I want to know how to implement concurrent threads in Python
On 2013.05.26 16:21, Daniel Gagliardi wrote: > shutup bitch! i do know python cannot concurrent threads. want a workaround You're a charming fellow. I'm sure everyone will flock to help you. -- http://mail.python.org/mailman/listinfo/python-list
Re: PyWart: The problem with "print"
I don't think you go far enough. Obviously we need way more flexibility. A simple on/off is okay for some things, but a finer granularity would be really helpful because some things are more important than others. And why stop at stdout/stderr? We need to add a consistent way to output these messages to files too in case we need to reference them again. The messages should have a consistent format as well. Why add the same information to each message when it would be much simpler to simply define a default format and insert the real meat of the message into it? It really seems like we should already have something like this. Hmm. -- CPython 3.3.2 | Windows NT 6.2.9200 / FreeBSD 9.1 -- http://mail.python.org/mailman/listinfo/python-list
Re: Re-using copyrighted code
On 2013.06.08 16:31, Malte Forkel wrote: > Hello, > > I have written a small utility to locate errors in regular expressions > that I want to upload to PyPI. Before I do that, I would like to learn > a litte more about the legal aspects of open-source software. What would > be a good introductory reading? The exact license terms. We might be able to help if you tell us which part(s) of the license you don't understand. There are some nice articles on many of the more common licenses on Wikipedia as well if you want a broader understanding. "Open-source" only implies that the source code is available. What one is allowed to actually do with the code will vary by project/author. > Now, how am I supposed to deal with that? Ask Secret Labs for some kind > of permission? Leave it as it is and add my own copyright line? If you can't find the license, I'd suggest sending an email to that address asking for a copy. -- CPython 3.3.2 | Windows NT 6.2.9200 / FreeBSD 9.1 -- http://mail.python.org/mailman/listinfo/python-list
Re: Re-using copyrighted code
On 2013.06.08 17:09, Benjamin Kaplan wrote: > On Sat, Jun 8, 2013 at 2:31 PM, Malte Forkel wrote: >> # This version of the SRE library can be redistributed under CNRI's >> # Python 1.6 license. For any other use, please contact Secret Labs >> # AB ([email protected]). >> # >> # Portions of this engine have been developed in cooperation with >> # CNRI. Hewlett-Packard provided funding for 1.6 integration and >> # other compatibility work. >> # >> >> Now, how am I supposed to deal with that? Ask Secret Labs for some kind >> of permission? Leave it as it is and add my own copyright line? >> >> Malte >> > > You can find the license terms for all versions of Python at > http://docs.python.org/3/license.html > I'm not a lawyer, but it looks like you just need to include the > copyright statement. I misread that bit, having forgotten that Python was not always under the PSF. To the OP: this is a pretty permissive license, but, as noted in the FAQ that Chris linked, there could be a problem if you wish to license your work under the GPL since the CNRI license specifies a jurisdiction. -- CPython 3.3.2 | Windows NT 6.2.9200 / FreeBSD 9.1 -- http://mail.python.org/mailman/listinfo/python-list
Re: My son wants me to teach him Python
On 2013.06.12 23:47, Rick Johnson wrote: > 1. Rock is dead... Nah, he just does movies now. Seriously, though, GUI stuff might be okay to learn early on since he's interested in making games. There's no reason to focus heavily on it this early, however. -- CPython 3.3.2 | Windows NT 6.2.9200 / FreeBSD 9.1 -- http://mail.python.org/mailman/listinfo/python-list
Re: A few questiosn about encoding
On 2013.06.20 08:40, Rick Johnson wrote: > One the most humorous aspects of Unicode is that it has > encodings for Braille characters. Hmm, this presents a > conundrum of sorts. RIDDLE ME THIS?! > > Since Braille is a type of "reading" for the blind by > utilizing the sense of touch (therefore DEMANDING 3 > dimensions) and glyphs derived from Unicode are > restrictively two dimensional, because let's face it people, > Unicode exists in your computer, and computer screens are > two dimensional... but you already knew that -- i think?, > then what is the purpose of a Unicode Braille character set? Two dimensional characters can be made into 3 dimensional shapes. Building numbers are a good example of this. We already have one Unicode troll; do we really need you too? -- CPython 3.3.2 | Windows NT 6.2.9200 / FreeBSD 9.1 -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie EOL while scanning string literal
On 2013.06.25 17:19, [email protected] wrote: > na=('type first integer n\')##THE RED SHADOW APPEARS HERE## Here you escape the closing single quote. \n is a line feed, not n\. Also, the parentheses are unnecessary, and it looks like you are a assigning a tuple instead of a string. Syntax errors are often the result of typos; IDEs can easily detect such problems and will highlight them for you to make them obvious. > int(naa) Strings are immutable; this returns an integer, but you don't assign it to anything. > is_triangle(na,ne,ni) And here, you pass the strings you assigned for the input prompt instead of the integers you wanted to get. BTW, if you have an error, it helps if you copy/paste the full traceback. Many times, the exact issue is laid out in the traceback, and the solution is obvious to those with experience. -- CPython 3.3.2 | Windows NT 6.2.9200 / FreeBSD 9.1 -- http://mail.python.org/mailman/listinfo/python-list
Why is the argparse module so inflexible?
I've begun writing a program with an interactive prompt, and it needs to parse input from the user. I thought the argparse module would be great for this, but unfortunately it insists on calling sys.exit() at any sign of trouble instead of letting its ArgumentError exception propagate so that I can handle it. Overriding ArgumentParser.error doesn't really help since methods like parse_known_args just send a message to be relayed to the user as an argument after swallowing ArgumentError (which does have useful information in its attributes). If I wanted to figure out what actually caused the exception to be raised, I'd have to parse the message, which is ugly at best. I understand that most people do want argparse to just display a message and terminate if the arguments supplied aren't useful, but there's a lot of potential in the module that is crippled outside the main use case. I have to wonder why a module that is meant to be imported would ever call sys.exit(), even if that is what the caller would normally do if presented with an exception. -- CPython 3.3.2 | Windows NT 6.2.9200 / FreeBSD 9.1 -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is the argparse module so inflexible?
On 2013.06.27 08:08, Roy Smith wrote: > Can you give us a concrete example of what you're trying to do? The actual code I've written so far isn't easily condensed into a short simple snippet. I'm trying to use argparse to handle all the little details of parsing and verifying arguments in the precmd hook for a cmd.Cmd child class. argparse's help system is more sophisticated than cmd's help and does all the work of verifying arguments. The problem I keep running into is that I can't handle any bad input very well. I would have to override every method that catches ArgumentError in order to get a useful exception that I would then handle. If I input something that begins with '-' that isn't recognized, parse_args doesn't even raise the exception; it just quits. In this case, the message gets mangled if error is overridden, and I don't know why. > You might look into "type=". It's normally used for things like > "type=int" or "type=float", but it could give it any user-defined > function as a type and this essentially becomes a hook to insert your > own code into the middle of the processing. Sometimes that can be > warped into doing all sorts of useful things. I don't think that would solve my problem, but it would probably be quite useful. -- CPython 3.3.2 | Windows NT 6.2.9200 / FreeBSD 9.1 -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is the argparse module so inflexible?
I appreciate the responses from everyone. I knew I couldn't be the only who thought this behavior was unnecessarily limiting. I found a ticket on the bug tracker. A patch was even submitted, but obviously it didn't make it into 3.3. Hopefully, it will make it into 3.4 with some prodding. http://bugs.python.org/issue9938 -- CPython 3.3.2 | Windows NT 6.2.9200 / FreeBSD 9.1 -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is the argparse module so inflexible?
After getting over the hurdles I initially explained and moving forward, I've found that standard command-line parsing and its conventions are far too ingrained in the design of argparse to make it useful as a general command parser. I think I would end up overriding a substantial amount of the module to make it do what I want, and I would really rather not try to shoehorn one paradigm into another. Unfortunately, getopt provides none of the benefits I sought with argparse, and optparse is deprecated, so I will probably be rolling my own custom parser. -- CPython 3.3.2 | Windows NT 6.2.9200 / FreeBSD 9.1 -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is the argparse module so inflexible?
On 2013.06.29 09:12, Roy Smith wrote: > What is the tracker issue number or url? http://bugs.python.org/issue9938 -- CPython 3.3.2 | Windows NT 6.2.9200 / FreeBSD 9.1 -- http://mail.python.org/mailman/listinfo/python-list
math functions with non numeric args
Hello,
print max(-10, 10)
10
print max('-10', 10)
-10
My guess max converts string to number bye decoding each of the characters
to it's ASCII equivalent?
Where can i read more on exactly how the situations like these are dealt
with?
Thank you
AZ
--
http://mail.python.org/mailman/listinfo/python-list
Re: math functions with non numeric args
On 2013.06.30 13:46, Andrew Z wrote:
> Hello,
>
> print max(-10, 10)
> 10
> print max('-10', 10)
> -10
>
> My guess max converts string to number bye decoding each of the characters to
> it's ASCII equivalent?
>
> Where can i read more on exactly how the situations like these are dealt with?
This behavior is fixed in Python 3:
>>> max('10', 10)
Traceback (most recent call last):
File "", line 1, in
TypeError: unorderable types: int() > str()
Python is strongly typed, so it shouldn't magically convert something from one
type to another.
Explicit is better than implicit.
--
CPython 3.3.2 | Windows NT 6.2.9200 / FreeBSD 9.1
--
http://mail.python.org/mailman/listinfo/python-list
Re: python adds an extra half space when reading from a string or list
On 2013.07.01 08:28, Νίκος wrote: > So, Steven you want me to sit tight and read all the insults coming from > this guy? > > If that happened to you, wouldn't you feel the need and urge to reply > back and stand for yourself? You can ignore it (this is the best solution) or you can take it off-list. Most on this list do not consider insults and flaming on the list acceptable. It doesn't matter who started it. > I use Thunderbird and i'm currently looking for a way to kill-file him, > because he is not likely to stop. Tools -> Message Filters... -- CPython 3.3.2 | Windows NT 6.2.9200 / FreeBSD 9.1 -- http://mail.python.org/mailman/listinfo/python-list
Re: How to tell Script to use pythonw.exe ?
On 2013.07.02 20:20, goldtech wrote: > Using Windows > > I want to run a .py file script using pythonw.exe so the DOS box will not > open. Is there a way from inside the script to say "run me with pythonw.exe > and not python.exe"? Use the .pyw extension instead of .py. Also, just FYI, DOS is long dead, and is much, much different under the hood from the console subsystem in modern versions of Windows. -- CPython 3.3.2 | Windows NT 6.2.9200 / FreeBSD 9.1 -- http://mail.python.org/mailman/listinfo/python-list
Re: DOS or not? [was Re: How to tell Script to use pythonw.exe ?]
On 2013.07.03 02:34, Tim Golden wrote: > While this is clearly true, it's by no means unusual for people to refer > to the "DOS Box" or talk about "DOS commands" etc. even when they're > quite well aware of the history of Windows and its Console subsystem. > It's just quicker than saying "Console Window" or something. > > I mention this because it seems to get called out every time someone > uses the term "DOS" on this and other Python lists and it can smack > slightly of pedantry. It's not as ambiguous (or as common) as it used to be, but it has always bothered me when someone refers to the Win32 console as DOS. I try not to be rude about it, but I really would like to prevent those who are not very familiar with Windows or its history from associating the limits and internal behavior of MS-DOS with the console subsystem of Windows NT. Especially with the anti-Windows sentiment that seems to be getting more popular (not that it's entirely without merit, but that's another topic for another day on another list), I'd rather see operating systems judged on things that are actually true and not miscellaneous FUD spread by ignorance and confusion. I realize it can come off as pedantic, but what may be obvious to those with of us with a lot of experience with different operating systems over the years can easily slip past a novice. BTW, there are several short and unambiguous terms one can use to refer to the Windows CLI environment (or parts thereof): cmd, command prompt, command line, terminal, console, etc.. Also, I don't think I've ever encountered anyone who prefers to call it DOS even though they know it's not correct, but if you say it's not unusual, then they're obviously out there, and I'll keep that in mind before jumping in to correct them. -- CPython 3.3.2 | Windows NT 6.2.9200 / FreeBSD 9.1 -- http://mail.python.org/mailman/listinfo/python-list
