lxml and xpath(?)
Hey; Reasonably new to python and incredibly new to xml much less trying to parse it. I need to identify cluster nodes from a series of weblogic xml configuration files. I've figured out how to get 75% of them; now, I'm going after the edge case and I'm unsure how to proceed. Weblogic xml config files start with namespace definitions then a number of child elements some of which have children of their own. The element that I'm interested in is which will usually have a subelement called containing the hostname that I'm looking for. Following the paradigm of "we love standards, we got lots of them", this model doesn't work everywhere. Where it doesn't work, I need to look for a subelement of called . That element contains an alias which is expanded in a different root child, at the same level as . So, picture worth a 1000 words: < [[ heinous namespace xml snipped ]] > [[text]] ... EDIServices_MS1 ... EDIServices_MC1 ... EDIServices_MS2 ... EDIServices_MC2 ... EDIServices_MC1 EDIServices_MC1 SSL host001 7001 EDIServices_MC2 EDIServices_MC2 host002 7001 So, running it on 'normal' config, I get: $ ./lxml configs/EntsvcSoa_Domain_config.xml EntsvcSoa_CS=> host003.myco.com EntsvcSoa_CS => host004.myco.com Running it against the abi-normal config, I'm currently getting: $ ./lxml configs/EDIServices_Domain_config.xml EDIServices_CS => EDIServices_MC1 EDIServices_CS => EDIServices_MC2 Using the examples above, I would like to translate EDIServices_MC1 and EDIServices_MC2 to host001 and host002 respectively. The primary loop is: for server in root.findall('ns:server', namespaces): cs = server.find('ns:cluster', namespaces) if cs is None: continue # cluster_name = server.find('ns:cluster', namespaces).text cluster_name = cs.text listen_address = server.find('ns:listen-address', namespaces) server_name = listen_address.text if server_name is None: machine = server.find('ns:machine', namespaces) if machine is None: continue else: server_name = machine.text print("%-15s => %s" % (cluster_name, server_name)) (it's taken me days to write 12 lines of code... good thing I don't do this for a living :) ) Rephrased, I need to find the under the child who's name matches the name under the corresponding child. From some of the examples on the web, I believe xpath might help but I've not been able to get even the simple examples working. Go figure, I just figured out what a namespace is... Any hints/tips/suggestions greatly appreciated especially with complete noob tutorials for xpath. Thanks for your time. Doug O'Leary -- https://mail.python.org/mailman/listinfo/python-list
Re: xml parsing with lxml
On Friday, October 7, 2016 at 3:21:43 PM UTC-5, John Gordon wrote: > root = doc.getroot() > for child in root: > print(child.tag) > Excellent! thank, you sir! that'll get me started. Appreciate the reply. Doug O'Leary -- https://mail.python.org/mailman/listinfo/python-list
xml parsing with lxml
Hey; I'm trying to gather information from a number of weblogic configuration xml files using lxml. I've found any number of tutorials on the web but they all seem to assume a knowledge that I apparently don't have... that, or I'm just being rock stupid today - that's distinct possibility too. The xml looks like: Domain1 10.3.5.0 [[snipp]] [[realm children snipped] myrealm [[snip]] [[snip]] [[snip]] [[snip]] [[snip]] byTime 14 02:00 Info [[snip]] 40024 true snip]] [[children snipped]] ${hostname} ${hostname} 40022 javac [[children snipped] [[rest snipped] The tutorials all start out well enough with: $ python Python 3.5.2 (default, Aug 22 2016, 09:04:07) [GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> from lxml import etree >>> doc = etree.parse('config.xml') Now what? For instance, how do I list the top level children of .*?? In that partial list, it'd be name, domain-version, security-configuration, log, and server. For some reason, I'm not able to make the conceptual leap to get to the first step of those tutorials. The end goal of this exercise is to programatically identify weblogic clusters and their hosts. thanks Doug O'Leary -- https://mail.python.org/mailman/listinfo/python-list
Re: more python3 regex?
Hey, all; The print suggestion was the key clue. Turned out my loop was slurping the whole of data in one big line. Searching for a line that begins with Name when it's in the middle of the string is... obviously not going to work so well. Took me a bit to get that working and, once I did, I realized I was on the wrong track altogether. In perl, if possible, I will read a file entirely as manipulation of one large data structure is easier in some ways. Even with perl, though, that approach is the wrong one for this data. While I learned lots, the key lesson is forcing data to match an algorithm works as well in python as it does in perl. Go figure. My 200+ script that didn't work so well is now 63 lines, including comments... and works perfectly. Outstanding! Thanks for putting up with noob questions Doug -- https://mail.python.org/mailman/listinfo/python-list
more python3 regex?
Hey This one seems like it should be easy but I'm not getting the expected results. I have a chunk of data over which I can iterate line by line and print out the expected results: for l in q.findall(data): # if re.match(r'(Name|")', l): # continue print(l) $ ./testies.py | wc -l 197 I would like to skip any line that starts with 'Name' or a double quote: $ ./testies.py | perl -ne 'print if (m{^Name} || m{^"})' Name IP Address,Site, "",,7 of 64 Name,IP Address,Site, "",,,8 of 64 Name,IP Address,Site, "",,,9 of 64 Name,IP Address,Site, "",,,10 of 64 Name,IP Address,Site, "",,,11 of 64 Name IP Address,Site, $ ./testies.py | perl -ne 'print unless (m{^Name} || m{^"})' | wc -l 186 When I run with the two lines uncommented, *everything* gets skipped: $ ./testies.py $ Same thing when I use a pre-defined pattern object: skippers = re.compile(r'Name|"') for l in q.findall(data): if skippers.match(l): continue print(l) Like I said, this seems like it should be pretty straight forward so I'm obviously missing something basic. Any hints/tips/suggestions gratefully accepted. Doug O'Leary -- https://mail.python.org/mailman/listinfo/python-list
Re: iterating over multi-line string
Hey; Never mind; I finally found the meaning of stopiteration. I guess my google-foo is a bit weak this morning. Thanks Doug -- https://mail.python.org/mailman/listinfo/python-list
iterating over multi-line string
Hey; I have a multi-line string that's the result of reading a file filled with 'dirty' text. I read the file in one swoop to make data cleanup a bit easier - getting rid of extraneous tabs, spaces, newlines, etc. That part's done. Now, I want to collect data in each section of the data. Sections are started with a specific header and end when the next header is found. ^1\. Upgrade to the latest version of Apache HTTPD ^2\. Disable insecure TLS/SSL protocol support ^3\. Disable SSLv2, SSLv3, and TLS 1.0. The best solution is to only have TLS 1.2 enabled ^4\. Disable HTTP TRACE Method for Apache [[snip]] There's something like 60 lines of worthless text before that first header line so I thought I'd skip through them with: x=0 # Current index hx=1 # human readable index rgs = '^' + str(hx) + r'\. ' + monster['vulns'][x] hdr = re.compile(rgs) for l in data.splitlines(): while not hdr.match(l): next(l) print(l) which resulted in a typeerror stating that str is not an iterator. More googling resulted in: iterobj = iter(data.splitlines()) for l in iterobj: while not hdr.match(l): next(iterobj) print(l) I'm hoping to see that first header; however, I'm getting another error: Traceback (most recent call last): File "./testies.py", line 30, in next(iterobj) StopIteration I'm not quite sure what that means... Does that mean I got to the end of data w/o finding my header? Thanks for any hints/tips/suggestions. Doug O'Leary -- https://mail.python.org/mailman/listinfo/python-list
Re: python3 regex?
Hey, all; thanks for the replies - reading data in one slurp vs line by line was the issue. In my perl programs, when reading files, I generally do it all in one swell foop and will probably end up doing so again in this case due to the layout of the text; but, that's my issue. Thanks again. I appreciate the tip. Doug O'Leary -- https://mail.python.org/mailman/listinfo/python-list
Re: Python enabled gdb on Windows and relocation
On Sun, May 15, 2011 at 9:11 AM, Ruben Van Boxem wrote: > I am sorry for the repeated messages that no one cares about, but I > may have discovered GDB in its current form already allows what I > want: I tried to figure out what exact paths the snake in gdb was > using to search for its modules, and came up with this: > (gdb) python import sys > (gdb) python print sys.path > ['m:\\development\\mingw64\\share\\gdb/python', > 'M:\\Development\\mingw64\\bin\\python27.zip', > 'M:\\Development\\mingw64\\bin\\DLLs', > 'M:\\Development\\mingw64\\bin\\lib', > 'M:\\Development\\mingw64\\bin\\lib\\plat-win', > 'M:\\Development\\mingw64\\bin\\lib\\lib-tk', > 'M:\\Development\\mingw64\\bin', > 'M:\\Development\\mingw64\\bin\\lib\\site-packages'] > > This means that every python command within gdb searches > /share/gdb/python FIRST (even before an environment's > PYTHONPATH), alleviating any concerns or problems I or anyone would > have with another python installation, as this apparently built-in > path comes up first. All I, or anyone interested in doing this kind of > thing, have to do is copy all the python scripts from the Windows > installation's Lib directory to the /share/gdb/python > directory. > > I don't know where this path comes from, but it is quite handy, and > makes this whole discussion moot for Python people. Only "issue" that > I'll have to work around is the --with-python-includes and > --with-python-libs that are missing, using either manual > CFLAGS/LDFLAGS or a variant of your script. IMO *if* gdb wanted to support people adding files to *its* /share/gdb directory, more thought is needed - e.g. maybe document a "site" directory for such files. Dunno. IMO we certainly don't want to formally allow folks to willy-nilly put anything there - no guarantees a future release might add something that collides with something the user put there. If and until then, you're probably pretty safe if you put everything in a subdirectory with a unique enough name, if you really wanted to go this route. Btw, there is the system.gdbinit file which sites *are* free to customize. E.g., configure --with-system-gdbinit=/share/gdb/system.gdbinit. You can put whatever you want in that file. E.g., you could add a directory to python's sys.path. [Technically speaking, the path /share/gdb/system.gdbinit goes against what I just said, but IMO this name is safe.] -- http://mail.python.org/mailman/listinfo/python-list
Re: Python enabled gdb on Windows and relocation
On Sun, May 15, 2011 at 6:26 AM, Ruben Van Boxem wrote: > Wow, I think I have a partial solution. Delving into the Python docs, > for example here: > http://docs.python.org/using/windows.html#finding-modules, you can see > that PYTHONPATH is used first, then the Windows registry, then > PYTHONHOME, then some default relative paths. I placed the python > scripts all in the directory structure like so: > > /bin/gdb > /bin/Lib/ > /bin/python27.dll > > This works, even without any manual PYTHONPATH intervention. Problem > is though, that as soon as someone has a PYTHONPATH environment > variable from a (incompatible) Python installation (think different > bitness or version 3.x instead of 2.7.1), I cannot predict what will > go wrong. This problem originates in Python's way of filling in the > search path (sys.path). A true solution in the GDB case to prevent > this collision of an incompatible PYTHONPATH would be that GDB sets an > internal PYTHONPATH as directed by configure, uses that to load its > Python internals, and allows the GDB child processes (apps being > debugged) to use the environment PYTHONPATH. For now, I have a > functional installation, but it will break as soon as someone installs > Python on their system. What if the user *wants* gdb's python to use $PYTHONPATH from his/her environment? To handle *this* case, *and* the case of an incompatible python installation using $PYTHONPATH, there is the $GDB_PYTHONPATH proposal (see earlier email for details). It feels problematic to decide at configure time whether there will or will not be an incompatible python at runtime. [I realize you have subsequent messages. Just replying in sequence.] -- http://mail.python.org/mailman/listinfo/python-list
Re: Python enabled gdb on Windows and relocation
On Sat, May 14, 2011 at 11:30 AM, Doug Evans wrote: > Note that --exec-prefix is the runtime location of python. > GCC uses this to tell libpython where to find its support files. > [grep for Py_SetProgramName in gdb/python/python.c] Oops. s/GCC/GDB/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Python enabled gdb on Windows and relocation
On Sat, May 14, 2011 at 2:29 AM, Eli Zaretskii wrote: >> Date: Sat, 14 May 2011 11:09:13 +0200 >> From: Ruben Van Boxem >> Cc: g...@sourceware.org, python-list@python.org >> >> 1. Check hardcoded path; my suggestion would be "> executable>/../lib/python27" >> 2. If this fails to find the necessary files/scripts, find it like you >> described above in Linux, without PYTHONPATH set. >> 3. Check PYTHONPATH. >> >> I would think only number one would change, and perhaps be only >> enabled with a special configure option. Nothing else would have to >> change, and Windows users would rejoice :) > > The problem, I think, is that it's not so easy on Unix to get the > place where the GDB executable leaves. There isn't a system call to > do that (similar to what Windows gives you). > > So I think on Posix platforms, number 2 would be used most of the > time. For reference sake, gdb is "relocatable". [meaning, if you take a gdb installation and move it, it should continue to work fine] And if gdb's python lives inside the gdb tree, that too should continue to work fine if moved with gdb (the value to pass to Py_SetProgramName is appropriately (re-)computed when gdb is run). [For completeness sake, IIRC the calculation of a path being "relocatable" isn't bulletproof, but it works in practice.] It's not impossible for gdb to find where it lives, but you're right it can be moderately difficult (basically, if argv[0] isn't an absolute path then scan $PATH for it). -- http://mail.python.org/mailman/listinfo/python-list
Re: Python enabled gdb on Windows and relocation
On Sat, May 14, 2011 at 2:09 AM, Ruben Van Boxem wrote: > 2011/5/14 Doug Evans : >> On Thu, May 12, 2011 at 9:19 AM, Ruben Van Boxem >> wrote: >>> (now in plain-text as required by gdb mailing list) >>> >>> Hi, >>> >>> I am currently trying to integrate Python support into my toolchain >>> build (including GDB of course). It is a sysrooted >>> binutils+GCC+GDB+mingw-w64 toolchain. >>> >>> I currently have the basic setup working: I can link gdb with my >>> manually generated import lib to the python dll from the official >>> Windows install. If there is anything I am missing or a very easy >>> solution to the problems decsribed below, please just say so. I am >>> only suggesting what I would like to happen. >>> >>> Now on to the problems I'd like to discuss: >>> >>> 1. gdb.exe won't start without me having set PYTHONPATH manually. >> >> In a properly configured/built gdb on linux this isn't necessary, even >> if python is installed in some random place. >> I'm not sure about windows though. >> Did you specify --with-python when you configured gdb, and if so did >> you specify a value? >> e.g., --with-python=SOME_VALUE > > I was cross-compiling a mingw toolchain+gdb from Linux, so I used > --with-python without a value (because gdb configure tries to find the > Python executabe), and I added -I"/path/to/python/includes" to CFLAGS > and -L"/path/to/pythondll/importlib" to LDFLAGS, which built as it > should. This is hacky though, and gdb configure should provide > --with-python-libs and --with-python-include to make it more > streamlined with any other build prerequisite (like > gmp/mpfr/mpc/cloog/ppl in GCC for example). Ah. Cross-compiling gdb with python is in need of improvement. Alas python hasn't been designed with cross-compilation in mind (e.g. build on linux, run on windows). AIUI, the way to get the parameters required for compiling with libpython is to get them from python's "distutils": kinda hard to do in a cross-compile. Done correctly there's no need to run python. I haven't done anything more to support python in gdb's configure.ac because it's not clear to me what the right thing to do is: distutils provides more than just --libs and --includes (btw, we don't use --libs though, we use --ldflags which includes all of: the directory in which to find libpython, the -l for libpython, and the -l's for all the other libraries python needs). [Which isn't to say that someone else isn't free to tackle this.] In the meantime, what I've been doing is a hack: write a script that responds to: --includes --ldflags --exec-prefix and pass that as --with-python. E.g. bash$ cat $HOME/my-python-for-config #! /bin/sh if [ $# -ne 2 ] then echo "Bad # args. Blech!" >&2 exit 1 fi # The first argument is the path to python-config.py, ignore it. case "$2" in --includes) echo "-I/usr/include/python2.6 -I/usr/include/python2.6" ;; --ldflags) echo "-L/usr/lib/python2.6/config -lpthread -ldl -lutil -lm -lpython2.6" ;; --exec-prefix) echo "/usr" ;; *) echo "Bad arg $2. Blech!" >&2 ; exit 1 ;; esac exit 0 bash$ ./configure --with-python=$HOME/my-python-for-config [...] [...] Note that --exec-prefix is the runtime location of python. GCC uses this to tell libpython where to find its support files. [grep for Py_SetProgramName in gdb/python/python.c] >>> I understand the need for this, but as gdb requires Python 2, and users >>> of my toolchain may have installed Python 3 or a 32-bit version python >>> they want to use from the same environment (without changing their own >>> PYTHONPATH), there is no way to run python-enabled gdb. >>> [...] >> >> Yeah. >> There is a proposal to add GDB_PYTHONPATH (or some such IIRC) and have >> gdb use that instead of PYTHONPATH if it exists, but there's been >> resistance to it. >> I think(!) what would happen is that gdb would set $PYTHONPATH to the >> value of $GDB_PYTHONPATH. >> [Inferiors started by gdb should still get the original value of >> PYTHONPATH though.] > > That way would be almost ideal, but a hardcoded *relative* path to the > python scripts (that is standardized within gdb) wouldn't hurt. See above re: --exec-prefix. > An > extra environment variable would require a lot of explaining for > Windows, and is not "plug-and-play", like the rest of a sysrooted > toolchain is supposed to be like. I think this should work on all > setups: > > 1. Check hardcoded path; my suggestion would
Re: Python enabled gdb on Windows and relocation
On Thu, May 12, 2011 at 9:19 AM, Ruben Van Boxem wrote: > (now in plain-text as required by gdb mailing list) > > Hi, > > I am currently trying to integrate Python support into my toolchain > build (including GDB of course). It is a sysrooted > binutils+GCC+GDB+mingw-w64 toolchain. > > I currently have the basic setup working: I can link gdb with my > manually generated import lib to the python dll from the official > Windows install. If there is anything I am missing or a very easy > solution to the problems decsribed below, please just say so. I am > only suggesting what I would like to happen. > > Now on to the problems I'd like to discuss: > > 1. gdb.exe won't start without me having set PYTHONPATH manually. In a properly configured/built gdb on linux this isn't necessary, even if python is installed in some random place. I'm not sure about windows though. Did you specify --with-python when you configured gdb, and if so did you specify a value? e.g., --with-python=SOME_VALUE > I understand the need for this, but as gdb requires Python 2, and users > of my toolchain may have installed Python 3 or a 32-bit version python > they want to use from the same environment (without changing their own > PYTHONPATH), there is no way to run python-enabled gdb. > [...] Yeah. There is a proposal to add GDB_PYTHONPATH (or some such IIRC) and have gdb use that instead of PYTHONPATH if it exists, but there's been resistance to it. I think(!) what would happen is that gdb would set $PYTHONPATH to the value of $GDB_PYTHONPATH. [Inferiors started by gdb should still get the original value of PYTHONPATH though.] > 2. With PYTHONPATH set as a temporary workaround, gdb starts, but > spits out a traceback: > Traceback (most recent call last): > File "", line 35, in > File "m:\development\mingw64\share\gdb/python/gdb/__init__.py", line > 18, in > gdb.command.pretty_printers.register_pretty_printer_commands() > File > "m:\development\mingw64\share\gdb/python/gdb\command\pretty_printers.py", > line 368, in register_pretty_printer_commands > InfoPrettyPrinter() > File > "m:\development\mingw64\share\gdb/python/gdb\command\pretty_printers.py", > line 100, in __init__ > gdb.COMMAND_DATA) > RuntimeError: Could not find command prefix info. > > This is a minor problem I think, as "python import time" "python print > time.clock()" works as expected. What is wrong? I'm not sure. The error message is complaining that the "info" command prefix doesn't exist. I don't see how that can happen as python is initialized long after the info command is created. -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question about PYTHONPATH
The best way I have found is to place that definition of your PYTHONPATH in your .bash_profile in your home directory and export it from there. PYTHONPATH=/home/foo/prog/learning_python export PYTHONPATH This way your PYTHONPATH is picked up each time you log on. You might have to restart IDLE for the changes you mention below to take effect. On 2/15/2011 12:49 PM, Tim Hanson wrote: I am to the point in _Learning_Python_ where functions are introduced. I decided to experiment by putting a function into a file and importing it into Idle. Of course, Idle couldn't find it, so I executed the following command in Bash: PYTHONPATH=/home/foo/prog/learning_python export PYTHONPATH env | grep PYTHONPATH ~$PYTHONPATH=/home/foo/prog/learning_python Idle still won't find it. I'm doing something wrong? -- http://mail.python.org/mailman/listinfo/python-list
Another related OO Python ?
hey, does anyone find the UML useful during Python development of larger projects? -- http://mail.python.org/mailman/listinfo/python-list
Re: Which non SQL Database ?
On 12/4/2010 5:42 PM, Jorge Biquez wrote: Hello all. Newbie question. Sorry. As part of my process to learn python I am working on two personal applications. Both will do it fine with a simple structure of data stored in files. I now there are lot of databases around I can use but I would like to know yoor advice on what other options you would consider for the job (it is training so no pressure on performance). One application will run as a desktop one,under Windows, Linux, Macintosh, being able to update data, not much, not complex, not many records. The second application, running behind web pages, will do the same, I mean, process simple data, updating showing data. not much info, not complex. So, why not LDAP? As an excersice it is more than enough I guess and will let me learn what I need for now. Talking with a friend about what he will do (he use C only) he suggest to take a look on dBase format file since it is a stable format, fast and the index structure will be fine or maybe go with BD (Berkley) database file format (I hope I understood this one correctly) . Plain files it is not an option since I would like to have option to do rapid searches. What would do you suggest to take a look? If possible available under the 3 plattforms. Thanks in advance for your comments. Jorge Biquez -- http://mail.python.org/mailman/listinfo/python-list
Re: Wing in mod_python vs wsgi?
I don't know about your IDE, I am using the default IDLE just because it is handy. But I have made the switch from mod_python. It was a good idea, but mod_wsgi is a better idea. And as you know, mod_python is no longer supported. I am running Apache with mod_wsgi in a windows 7 environment -- I am working on implementing Pylons. Also, I have another Apache server with mod_wsgi serving a MoinMoin wiki. This one is on a good os -- Fedora. On 2/8/2011 6:57 PM, Tom Stambaugh wrote: I'm still using mod_python to deploy my framework for production (CentOS running Python 2.5.5, Apache 2.2.3, mod_python 3.3.1). I'm acutely aware of how elderly mod_python is, and I've had some frustrations using Wing to debug inside it -- at least its possible, which is not true for any other Python IDE I've tried. Does Wing do better in mod_wsgi? Is it time for me to migrate from mod_python to mod_wsgi? Has anybody tried to do this (mod_wsgi and apache) in a Windoze environment? Thx, Tom S. -- http://mail.python.org/mailman/listinfo/python-list
Supporting Python 2.x and 3.x on a PC
I support multiple projects, some of which will remain on Python 2.x and some of which want to use Python 3.1.2. While I have installed both on my Windows PC, only the last installed version can be used. I do not have admin rights on the machine, so altering registry settings is not an option. Any guidance on how I can select between the versions? Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Using elementtree to Create HTML Form / Set "selected"
On Aug 12, 10:47 am, Peter Otten <__pete...@web.de> wrote: > Doug wrote: > > I'm using elementtree to create a form. > > > I would like to set the "selected" attribute. > > > Setting using the usual > > option.set( "selected" = "" ) > > Maybe that should be option.set(selected="selected"). I think > > > > and > > > > are equivalent. > > http://www.w3.org/TR/html4/intro/sgmltut.html#h-3.3.4.2 > > > > > gives me > > Operations > > how does one make > > Operations > > which is what I need. Makes sense to me. Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Using elementtree to Create HTML Form / Set "selected"
I'm using elementtree to create a form. I would like to set the "selected" attribute. Setting using the usual option.set( "selected" = "" ) gives me Operations how does one make Operations which is what I need. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to run python script in emacs
When I type C-c C-c my emacs window just hangs. If I use Task Manager to kill cmdproxy I can get emacs back but of course interactivity with Python is not accomplished. By the way, if I do C-c ! then I get a functional python shell. Does anybody know a solution to this? On Oct 13, 7:12 am, rustom wrote: > On Sep 26, 8:54 pm, devilkin wrote: > > > I'm just starting learning python, and coding in emacs. I usually > > split emacs window into two, coding in one, and run script in the > > other, which is not very convenient. anyone can help me with it? is > > there any tricks like emacs short cut? > > > also please recommand some emacs plug-ins for python programming, i'm > > also beginner in emacs.currently i'm only using python.el. > > python.el comes with emacs > python-mode.el comes from python https://launchpad.net/python-mode/ > Because of some emacs politics the first ships with emacs although > most uses prefer the second. > Note 1. The key bindings are different > Note 2. Does not work with python3. See my > posthttp://groups.google.com/group/comp.lang.python/browse_thread/thread/... > > > Are any plugins supply code folding and autocomplete? > > See ropehttp://rope.sourceforge.net/ropemacs.htmlif you want > but its an installation headache (requires pymacs bleeding edge > version etc) > I suggest you just get used to python-mode first (C-c ! and C-c C-c) > and then explore these questions a bit later. > > > > > BTW, I'm not a english native speaker, any grammer mistakes, please > > correct them. :) > > grammer is spelt grammar :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Writing a Carriage Return in Unicode
Hi! Thanks for clearing this up!! -- http://mail.python.org/mailman/listinfo/python-list
Writing a Carriage Return in Unicode
Hi! I am trying to write a UTF-8 file of UNICODE strings with a carriage return at the end of each line (code below). filOpen = codecs.open("c:\\temp\\unicode.txt",'w','utf-8') str1 = u'This is a test.' str2 = u'This is the second line.' str3 = u'This is the third line.' strCR = u"\u240D" filOpen.write(str1 + strCR) filOpen.write(str2 + strCR) filOpen.write(str3 + strCR) filOpen.close() The output looks like This is a test.âThis is the second line.âThis is the third line.â when opened in Wordpad as a UNICODE file. Thanks for your help!! -- http://mail.python.org/mailman/listinfo/python-list
print syntax
I am new to python, working by way through 'Core Python Programming'. I can find no description of using print with the built-in type for formatting. I think I have got some [most?] of it from Chun, google, and python.org. My comment is - it should not be that hard to find. I would suggest a link from the print syntax section. What is seems to be is: print "format-spec" % (variable-list) I assume the '%' is required token. _ Douglas Denault http://www.safeport.com d...@safeport.com Voice: 301-217-9220 Fax: 301-217-9277 -- http://mail.python.org/mailman/listinfo/python-list
Detecting platform architecture with Parallels and Win XP x64
Hello, I am using Python 2.5.4 on Windows XP x64 with Parallels. When I try to use: distutils.util.get_platform sys.platform I always get win32 but if I use: platform.architecture() with the amd64 installer I get 64bit for the first argument. Is there a way to detect win64 without having to use the python executable to see if the application is on a 64bit architecture? Thanks. Doug -- http://mail.python.org/mailman/listinfo/python-list
Ctypes, pthreads and pthread_mutex_t
Has any converted the structure pthread_mutex_t to a ctypes structure class ? I looking at some C code that is using pthreads and need to translate pthreads_mutex_t structure into python (via ctypes) Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Fedora: Dual Python Versions Installed System Not Picking Up Newer Version
On Wed, 25 Mar 2009 19:56:13 -0700 (PDT), *nixtechno wrote: > I have a fedora box and just installed python 2.6.1 along with 2.5.2, > so here's my issue, if I removed the "systems" garbage RPM it would > uninstall all the other crap along with it, so I went ahead and > trunked in and ./configure, build && build install and built python > 2.6.1 along with this. However how can I stipulate that I want the > WHOLE system to use Python 2.6.1 rather than 2.5.2? I know there is > something to do with PATH, which I tried under my /root/.cshrc file, > but to no avail it didn't work. So is there something special I should > do with getting the system to pick up this directy: > > /usr/local/lib/python2.6/ > > Which the v2.6 binary is in: > > /usr/local/bin/python.2.6 > > Rather than this: > > /usr/lib64/python2.5/ > > Which the v2.5 binary is in: > > /usr/bin/python > > Perhaps it's Fedora not picking it up? > > Here's my server's build: > # uname -rm > 2.6.27.19-170.2.35.fc10.x86_64 x86_64 > > I've gone through and tried to figure it out, to no avail, so if > anyone is pretty familiar with this, because I do NOT want to > stipulate which binary to use in all my source files... Hi, One option would be to use the alternatives system, which RHL / Fedora install by default. Run "man alternatives" for documentation and the contents of /etc/alternatives for examples already in use on your system. Hope this helps. Cheers, Doug -- http://mail.python.org/mailman/listinfo/python-list
Re: A different kind of interface
On Thu, 22 Jan 2009 08:13:49 -0800 (PST), Vic Kelson wrote: > > > How about IDLE? It's a nice tool for the Python programmer. I've tried > lots of IDEs, but when it comes down to it, on small-to-medium jobs I > am be very productive indeed using IDLE... > > --v I find Stani's Python Editor (SPE) also good for small to medium jobs, and I think that it might achieve many of the OP's objectives. -- http://mail.python.org/mailman/listinfo/python-list
Re: Soap Client
I believe that I have answered my own question. If anyone else is interested in what I did ... using iPython's code completion (. then hit tab tab) I noticed that msg had a _request attribute. I set that attribute to "1" and that sent the message that I needed! Hope everyone has a great day! Doug -- http://mail.python.org/mailman/listinfo/python-list
Re: Core Dump - Segmentation Fault -Newbie
On Fri, 18 Jul 2008 15:56:10 +0200, Stefan Behnel <[EMAIL PROTECTED]> wrote: > [EMAIL PROTECTED] wrote: > > Hi - I am very new to python. I get this random core dump and am > > looking for a good way to catch the error. I know the function my core > > dump occurs. Is there any error catching/handling that I could use in > > python? > > Since you are using Windows, this is somewhat non-trivial due to the lack of > tools shipped by Microsoft. Are you really getting crashes of the interpreter > and not just an exception with a stacktrace? > > Stefan Hi John, Well, I must be missing something re: why Stefan states that you are using Windows. I don't see that stated in your original post, and, AFAIK, the phrase "core dump" is seen much more in the Unix world than in the Windows world. So, just in case you are on some *nix variant, you can of course log all the system calls up until your core dump by running: $ strace -o logfile.txt python [...] where [...] should be replaced with any parameters to the python interpreter, such as the Python script you're running, e.g., $ strace -o logfile.txt python Hello.py The trace of system calls will be in the file logfile.txt. For more info on strace, see the strace(1) man page (i.e., run "man strace"). Doug -- http://mail.python.org/mailman/listinfo/python-list
Re: Formatting Output
On Mon, 2 Jun 2008 12:42:12 -0700 (PDT), Mensanator <[EMAIL PROTECTED]> wrote: > On Jun 2, 3:38 am, Chris <[EMAIL PROTECTED]> wrote: > > On Jun 2, 9:34 am, "[EMAIL PROTECTED]" > > > > <[EMAIL PROTECTED]> wrote: > > > Hi, > > > > > i am building a little script and i want to output a series of columns > > > more or less like this: > > > > > 1 5 6 > > > 2 2 8 > > > 2 9 5 > ... I have a related question: Does Python have (or can emulate) the formatted output capability found in Perl? For example, all I have to do to get nicely formatted (i.e., aligned) output is provide values for special STDOUT variables (i.e., STDOUT_TOP, STDOUT, STDOUT_BOTTOM, etc.), exemplified by: format STDOUT_TOP = -- ~ . format STDOUT = @<<<<<<<<<<<<<<<<<<< @<<<<<<<<<<<<<<<<<<<<<<<< @<<<<<<<<<<<<<<<<<<<<<<<< $res->{'full_name'}, $res->{'phone_1'}, $res->{'phone_1_type'} @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~ $res->{'address_1a'},$res->{'address_2a'} @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~ $res->{'address_1b'},$res->{'address_2b'} @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~ $res->{'address_1c'},$res->{'address_2c'} @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~ $city_1 $city_2 @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~ $res->{'email_1'}, $res->{'email_2'} -- ~ . Then, all I have to do is populate my $res object/hash as desired -- in this example simple the results of a SQL query -- and lastly just call the "write" function: write; and Perl will produce very nicely formatted results. This is useful not only for producing human readable output, but also fixed-column-width data files, etc. I'd love to learn the Pythonistic way of doing the same thing. Thanks! Doug -- http://mail.python.org/mailman/listinfo/python-list
Re: app runs fine with interpreter, but not under py2exe
Hi Harald, Bond here, James Bond. I accepted your mission. :) Unfortunately, the mission failed. Creating a "testapp.py" as you described (i.e., with the suggested import statements) runs just fine with the interpreter. again, however, py2exe does the same thing as the original problem -- that is, copies numpy.core's versions of multiarray.pyd and umath.pyd into dist/, creates what look like stub multiarray.pyc and umath.pyc files in library.zip/ and library.zip/numpy/core/. when this py2exe version is run, it throws the same (original) TypeError: data type not understood error. Also, with either my original program or testapp.py, I cannot seem to modify library.zip in such a way as to get the program to run. Basically, I unzipped library.zip, made the same modifications to it's contents as I did when using the --skip-archive option (i.e., remove the stub files and put the right .pyd files in the right locations) and then recreated the library.zip file. Afterwards, running either origapp.exe or testapp.exe, the program bombs out with ImportError: no module named multiarray. In addition, I tried using py2exe to make a simple "Hello, world" program. It runs just fine. Then, I "zip -m library.zip *.pyd" in the dist/ directory to move the .pyd files into library.zip. Then, running hello.exe again works just fine. However, if I add "import bz2; print bz2.__author__" after "print 'Hello, world!'" (the only line in hello.py), hello.exe bombs out with "ImportError: DLL load failed: The specified module could not be found" when I run it after having moved *.pyd into library.zip/. (bz2 was one of only two .pyd files that py2exe put into dist/.) So, I can seem to figure out how to get .pyd files into library.zip, even when there are no name conflicts. What am I doing wrong? Finally, regarding the stub files, if I use vi to edit the py2exe-generated, 536-byte bz2.pyc file (there is no such file in my python install directory hierarchy), I see the word "import" very close to the word "bz2.pyd". This suggests to me that py2exe might indeed be creating simple import statements in a short .py file for each .pyd file and then compiling it into a .pyc stub file -- or at least doing something similar. Of course I can't be sure of this, but it seems likely to me. Thanks again to you and everyone. I'll definitely visit the py2exe wiki and see what I can come up with (and or course will report back with success / failures). If you or anyone has any further thoughts based on this post, I'm all ears and would be most grateful. Regards, Doug On Sun, 16 Mar 2008 00:33:31 -0700 (PDT), GHUM <[EMAIL PROTECTED]> wrote: > Doug, > > > as I quickly noticed that "library.zip" does NOT contain ANY .pyd files. > > I'm guessing that they can't be in library.zip for a reason (i.e., they are > > DLL files, essentially, and thus must be readily available to be loaded > > into memory). > > .dll and .pyd files CAN be within library.zip and even within the > single-file-exe. > > There is some Hellermagic within _memimporter.pyd that loads the .dll > and .pyd from a zipfile. When you scan the build_exe.py, you will > explicitely find: > > print "*** finding dlls needed ***" > dlls = self.find_dlls(extensions) > self.plat_finalize(mf.modules, py_files, extensions, dlls) > dlls = [item for item in dlls > if os.path.basename(item).lower() not in > self.dll_excludes] > # should we filter self.other_depends in the same way? > > > Is there a work-around for this, then? > -rwxr-xr-x 1 morse None 26624 Nov 28 2006 dist/multiarray.pyd > -rwxr-xr-x 1 morse None 348160 Nov 8 16:16 dist/numpy/core/ > multiarray.pyd > -rwxr-xr-x 1 morse None 192512 Nov 8 16:16 dist/numpy/core/ > umath.pyd > -rwxr-xr-x 1 morse None 54272 Nov 28 2006 dist/umath.pyd > > let's try: your mission is, should you chose to accept it, to make a > py2exed application to load two different multiarray.pyd, who are on > the visible level only different by their place in the file system. > > So, please make a minimal script: > > import multiarray > import numpy.core.multiarray as ncmultiarray > > and, using Peters test > >>> from multiarray import zeros > assert zeros((1,), "1") == array([0], '1') > > and check, if those multiarrays are the correct ones. If yes, you can > try to build upon this by making all imports explicit as described > above. (Yes, I know, that's not necessary in plain python ... but it > saved me in some weird "import from .zip" and "import from database" > sit
Re: app runs fine with interpreter, but not under py2exe
Hi, Well, my attempt to not use the --skip-archive option didn't get very far, as I quickly noticed that "library.zip" does NOT contain ANY .pyd files. I'm guessing that they can't be in library.zip for a reason (i.e., they are DLL files, essentially, and thus must be readily available to be loaded into memory). Is there a work-around for this, then? That is, is there a way to either (a) tell py2exe how to *correctly* handle multiple multiarray.pyd and umath.pyd files or (b) perhaps rename one set of the .pyd files -- say the numpy/core versions -- to say multiarray2.pyd and umath2.pyd, and then manual create the "stub"-like .pyc files that py2exe creates to point to these alternate .pyd files and then place these stubs in library.zip/numpy/core? Or am I just hoping for too much here and am going to be stuck with using the --skip-archive option? Thanks, Doug On Fri, 14 Mar 2008 14:37:32 + (UTC), Doug Morse <[EMAIL PROTECTED]> wrote: > Peter, > > Genius! You nailed it -- thanks! > > py2exe is apparently getting confused by the fact that packages "Numeric" > ... > > > So, my next step will be to try to not use the --skip-archive option and > then make these same modifications regarding multiarray.pyd and umath.pyd > to the py2exe-generated library.zip file and see if I can get things > running that way as well (and in so doing reduce my "dist" directory by > about 10mg). I may also try creating a dist/Numeric subdirectory and > moving dist/multiarray.pyd and dist/umath.pyd to this dist/Numeric > subdirectory -- for the goal of more accurately mirroring the actual > file/directory structure found in $PYTHONHOME/Lib/site-packages. > > -- http://mail.python.org/mailman/listinfo/python-list
Re: app runs fine with interpreter, but not under py2exe
Peter, Genius! You nailed it -- thanks! py2exe is apparently getting confused by the fact that packages "Numeric" and "numpy" both have files multiarray.pyd and umath.pyd. It copies just one of each -- from $PYTHONHOME/Lib/site-packages/numpy/core -- and puts both of them into the top-level of the created "dist" directory. Also, there are no such files as multiarray.pyc and umath.pyc in my python installation, but py2exe seems to create these (in the dist and dist/numpy/core directories) -- they are small (e.g., 526 bytes) and I'm guessing that they are stubs that simply point python to the matching .pyd that py2exe relocated. So, by using the --skip-archive option to py2exe (i.e., python setup.py py2exe --skip-archive) to create the dist and build directories, and then within the dist directory hierarchy removing all the occurrances of multiarray.pyc and umath.pyc, and then moving dist/multiarray.pyd and dist/umath.pyd to the dist/numpy/core directory, and finally by copying multiarray.pyd and umath.pyd from $PYTHONHOME/Lib/site-packages/Numeric to the dist directory, I am able to get my application to run correctly and as a standalone executable. HOORAH!!! Just for completeness and perhaps a bit of additional clarity, here's a limited directory listing of what the steps in the previous paragraph produce: morse> find dist | egrep "(multia|umath)" | xargs ls -l -rwxr-xr-x 1 morse None 26624 Nov 28 2006 dist/multiarray.pyd -rwxr-xr-x 1 morse None 348160 Nov 8 16:16 dist/numpy/core/multiarray.pyd -rwxr-xr-x 1 morse None 192512 Nov 8 16:16 dist/numpy/core/umath.pyd -rwxr-xr-x 1 morse None 54272 Nov 28 2006 dist/umath.pyd morse> (This is still WinXP; I'm just using the Cygwin bash and fileutils here. Also, note that there are NO multiarray.pyc or umath.pyc files.) So, my next step will be to try to not use the --skip-archive option and then make these same modifications regarding multiarray.pyd and umath.pyd to the py2exe-generated library.zip file and see if I can get things running that way as well (and in so doing reduce my "dist" directory by about 10mg). I may also try creating a dist/Numeric subdirectory and moving dist/multiarray.pyd and dist/umath.pyd to this dist/Numeric subdirectory -- for the goal of more accurately mirroring the actual file/directory structure found in $PYTHONHOME/Lib/site-packages. Again, thanks to everyone for their assistance, esp. Harald and Peter. Is this something I should pursue getting the py2exe folks to fix / work with them on fixing? In investigating this issue, I noted that a lot of other py2exe problems seem to revolve around confusions when duplicate files exist in different modules. I wouldn't thinking that getting py2exe to pay better attention to the containing modules when building it's dependency tree would be that difficult (or is it)? Cheers, Doug On Fri, 14 Mar 2008 12:39:23 +0100, Peter Otten <[EMAIL PROTECTED]> wrote: > Doug Morse wrote: > > > from multiarray import zeros > > import string > > > > typecodes = {'Character':'c', 'Integer':'1sil', 'UnsignedInteger':'bwu', > > 'Float':'fd', 'Complex':'FD'} > > > > def _get_precisions(typecodes): > > lst = [] > > for t in typecodes: > > lst.append( (zeros( (1,), t ).itemsize()*8, t) ) <-- Line 18 > > return lst > > > > def _fill_table(typecodes, table={}): > > for key, value in typecodes.items(): > > table[key] = _get_precisions(value) > > return table > > > > _code_table = _fill_table(typecodes) > > > > I can't find any reason why line 18 is throwing a "data type not > > understood" error. It doesn't seem to have anything to do with dynamic > > importing, but I can't be sure. I would note that "zeros" is a built-in > > function found in the "python dll" multiarray.pyd (in the Numeric module > > directory). > > I don't know why, but your module seems to use numpy's multiarray instead of > Numeric's: > > >>> from multiarray import zeros > >>> zeros((1,), "1") > array([0], '1') > >>> from numpy.core.multiarray import zeros > >>> zeros((1,), "1") > Traceback (most recent call last): >File "", line 1, in > TypeError: data type not understood > > Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: app runs fine with interpreter, but not under py2exe
Harald, Great suggestion, thanks! Unfortunately, "no help there". Adding "import multiarray" to Precision.py where you suggested (i.e., before the "from multiarray import zeros" line) did not fix the problem. I'm getting the same exception and traceback as before except, of course, on line 19 now instead of line 18. Doug On Thu, 13 Mar 2008 11:46:41 -0700 (PDT), GHUM <[EMAIL PROTECTED]> wrote: > Doug, > > > Precision.py is part of the Numeric package. AFAIKT, the problem is during > > the module initialization. The first lines of Precision.py are: > > > > from multiarray import zeros > > import string > > > [.] > and your program is crashing on the > > lst.append( (zeros( (1,), t ).itemsize()*8, t) ) <-- Line 18 > > line... Please, try the following: > > import multiarray > from multiarray import zeros > import string > > (adding the line "import multiarray" before zeros are imported from > it) > > I used this workaround with various packages I py2exed - maybe it also > works for you? > > please keep us updated, > > Harald -- http://mail.python.org/mailman/listinfo/python-list
Re: app runs fine with interpreter, but not under py2exe
Hi Harald and C.L.P., Precision.py is part of the Numeric package. AFAIKT, the problem is during the module initialization. The first lines of Precision.py are: from multiarray import zeros import string typecodes = {'Character':'c', 'Integer':'1sil', 'UnsignedInteger':'bwu', 'Float':'fd', 'Complex':'FD'} def _get_precisions(typecodes): lst = [] for t in typecodes: lst.append( (zeros( (1,), t ).itemsize()*8, t) ) <-- Line 18 return lst def _fill_table(typecodes, table={}): for key, value in typecodes.items(): table[key] = _get_precisions(value) return table _code_table = _fill_table(typecodes) I can't find any reason why line 18 is throwing a "data type not understood" error. It doesn't seem to have anything to do with dynamic importing, but I can't be sure. I would note that "zeros" is a built-in function found in the "python dll" multiarray.pyd (in the Numeric module directory). Thanks again, Doug On Wed, 12 Mar 2008 03:09:59 -0700 (PDT), GHUM <[EMAIL PROTECTED]> wrote: > to my knowledge, "data type not understood" is a message not from core > Python, but rather thrown from "your" code. What is happening around > Precision.py, line 18? > > What does trigger that exception? > > My guess is, you are dealing with some custom imported modules which > define "data type"s. > (PIL does something similiar for supported images)... that is, some > module is trying to import all definitions from a specific directory. > > That "dynamic importing" fails within py2exe --- all the importing has > to be definit at py2exing-time. Please ready http://www.py2exe.org/ > index.cgi/PIL_and_py2exe > and the other receipe on py2exe.org and try to adapt that knowledge to > your application. -- http://mail.python.org/mailman/listinfo/python-list
app runs fine with interpreter, but not under py2exe
Hi, I have an application that runs just fine using the standard Python distro interpreter (v2.5.1 on WinXP) but throws the following exception when run as an executable built with py2exe. My questions are: (a) does anyone have any thoughts on why this exception is occurring and what to do about it, and (b) more generally, why would a problem like this occur under py2exe but not with the standard distro? Thanks in adavance for any and all help. Cheers, Doug Traceback (most recent call last): File "VisionTrainer.py", line 49, in File "SessionController.pyc", line 53, in File "VisionEgg\__init__.pyc", line 42, in File "VisionEgg\ParameterTypes.pyc", line 28, in File "Numeric.pyc", line 93, in File "Precision.pyc", line 26, in File "Precision.pyc", line 23, in _fill_table File "Precision.pyc", line 18, in _get_precisions TypeError: data type not understood -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie: How can I use a string value for a keyword argument?
On Mon, 25 Feb 2008 04:20:37 -0800 (PST), John Machin <[EMAIL PROTECTED]> wrote: > On Feb 25, 10:42 pm, Doug Morse <[EMAIL PROTECTED]> wrote: > > Hi, > > > > My apologies for troubling for what is probably an easy question... it's > > just > > that can't seem to find an answer to this anywhere (Googling, pydocs, > > etc.)... > > > > I have a class method, MyClass.foo(), that takes keyword arguments. For > > example, I can say: > > > > x = MyClass() > > x.foo(trials=32) > > > > Works just fine. > > > > What I need to be able to do is call foo() with a string value specifying > > the > > keyword (or both the keyword and value would be fine), something along the > > lines of: > > > > x = MyClass() > > y = 'trials=32' > > x.foo(y)# doesn't work > > > > or > > > > x.MyClass() > > y = 'trials' > > x.foo(y = 32) # does the "wrong" thing > > > > Surely there's some way to use a string's value as the key for making a > > method > > call with a keyword argument? > > > > Just for completeness, my goal is simply to read a bunch of key/value pairs > > from an INI file (using ConfigObj) and then use those key/value pairs to > > set a > > (3rd party) object's parameters, which must be done with a call along the > > lines of "instance.set(key=value)". Obviously, I could create a huge > > if..elif > > statement along the lines of "if y = 'trials': x.foo(trials=32); elif y = > > 'speed': x.foo(speed=12);" etc., but then the statement has to be maintained > > every time a new parameter is added/changed etc. Plus, such a solution > > seems > > to me grossly inelegant and un-Pythonic. > > > > I'm not quite sure what foo() is really supposed to do ... however the > built-in function setattr is your friend. Assuming that ini_dict > contains what you have scraped out of your .ini file, you can do: > x = MyCLass() > for key, value in ini_dict.items(): > setattr(x, key, value) > You may prefer (I would) to do it inside the class, and maybe do some > checking/validation: > class MyClass(object): > def load(self, adict): > for k, v in adict.items(): > # do checking here > setattr(self, k, v) > # much later > x = MyClass() > x.load(ini_dict) > > HTH, > John Hi John, Your response is most helpful and informative -- thanks! I don't think that setattr() is exactly what I need, though, as foo() doesn't actually create or update its instance attributes. What I need to be able to do is call foo() specifying keyword arguments not directly but viz a viz another variable or variables that contain the keywords and values. I'm pretty sure I just found the solution, which is to use the **-operator on a dictionary. Actually, ConfigObj (the INI file reader) subclasses from __builtin__.dict (i.e., the class/object *is* a dictionary), so the following seems to work perfectly: x.foo(**config) This sends ALL the key/value pairs in config as keyword/value pairs to foo(), which is exactly what I need. Just FYI, I located this solution via Google shortly after posting, so I have sent a cancel request on my original post. Thanks again! Doug -- http://mail.python.org/mailman/listinfo/python-list
Newbie: How can I use a string value for a keyword argument?
Hi, My apologies for troubling for what is probably an easy question... it's just that can't seem to find an answer to this anywhere (Googling, pydocs, etc.)... I have a class method, MyClass.foo(), that takes keyword arguments. For example, I can say: x = MyClass() x.foo(trials=32) Works just fine. What I need to be able to do is call foo() with a string value specifying the keyword (or both the keyword and value would be fine), something along the lines of: x = MyClass() y = 'trials=32' x.foo(y)# doesn't work or x.MyClass() y = 'trials' x.foo(y = 32) # does the "wrong" thing Surely there's some way to use a string's value as the key for making a method call with a keyword argument? Just for completeness, my goal is simply to read a bunch of key/value pairs from an INI file (using ConfigObj) and then use those key/value pairs to set a (3rd party) object's parameters, which must be done with a call along the lines of "instance.set(key=value)". Obviously, I could create a huge if..elif statement along the lines of "if y = 'trials': x.foo(trials=32); elif y = 'speed': x.foo(speed=12);" etc., but then the statement has to be maintained every time a new parameter is added/changed etc. Plus, such a solution seems to me grossly inelegant and un-Pythonic. Thanks in advance for any and all assistance! Doug -- http://mail.python.org/mailman/listinfo/python-list
Re: OT: Speed of light [was Re: Why not a Python compiler?]
So, showing of my physics ignorance: I presume then that this means that light, say from the sun, is actually sending particles to the earth, since the space between is mostly vacuum? Or is there enough material in the near-vacuum of space for propogation to occur? On Sat, 09 Feb 2008 12:25:51 -0800, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote: > ... > Or just the old particle/wave dichotomy... particles travel, waves > propagate (that is, the wave form -- crest/dip -- changes position, but > the material of the medium it is in just jiggles in place). -- http://mail.python.org/mailman/listinfo/python-list
Re: ISO books of official Python docs
Hi Fredrik, I'm terribly confused. You want me to apologize for recommending that someone buy your books? To apologize for noting that they are a quality reference sources for Python? Doug On Wed, 09 Jan 2008 21:59:34 +0100, Fredrik Lundh <[EMAIL PROTECTED]> wrote: > Doug Morse wrote: > > > Several of the O'Reilly & Assoc. books -- such as Python in a Nutshell, The > > Python Standard Library, etc -- are in large part reproductions of the > > official docs and references. > > if you're using "reproduction" to mean "copy", I think you owe both me > and Alex a big apology. > > -- http://mail.python.org/mailman/listinfo/python-list
Re: ISO books of official Python docs
Several of the O'Reilly & Assoc. books -- such as Python in a Nutshell, The Python Standard Library, etc -- are in large part reproductions of the official docs and references. So, while not exactly what you asked for, the ORA books might be a viable alternative if what you want isn't available. On Wed, 9 Jan 2008 19:55:10 + (UTC), kj <[EMAIL PROTECTED]> wrote: > > > > Is it possible to buy the official Python docs in book form? If > so, I'd very much appreciate the name(s) and author(s) of the > book(s). > > TIA! > > kynnjo -- http://mail.python.org/mailman/listinfo/python-list
Extracting images from a PDF file
Hi all, Does anyone know how to extract images from a PDF file? What I'm looking to do is use pdflib_py to open large PDF files on our Linux servers, then use PIL to verify image data. I want to do this in order to find corrupt images in the PDF files. If anyone could help me out, or point me in the right direction, it would be most appreciated! Also, does anyone know of a way to validate a PDF file? Thanks in advance, Doug -- http://mail.python.org/mailman/listinfo/python-list
Re: Is Python really a scripting language?
although perhaps not a part of the definition of scripting languages per se, one aspect of them is that they are often used to "glue" a wide variety of other components together. perl's initial and continued success is in no small part to all the wrappers and interfaces it has to all sorts of other software components and applications. part of python's utility, IMHO, is the ease with which it can be used, like perl, to glue together a lot of disparate parts. > >> But here's my problem, > >> most of my coworkers, when they see my apps and learn that they are > >> written in Python ask questions like, "Why would you write that in a > >> scripting language?" Whenever I hear a comment like that I can feel > >> myself boiling inside. -- http://mail.python.org/mailman/listinfo/python-list
Re: changing fonts?
Hi Jay, I'm not *that* familiar with the Terminal program on OS/X, but regardless perhaps I can point out a possibly useful path to explore... With terminal programs generally -- especially more in the past, as then they were much more about emulating "real" terminals -- a lot of the terminal progam's behavior and configuration could be controlled with what are called "escape sequences". Escape sequences were named as such because, most often, these control sequences were output from the computer to the terminal (often over a serial port) and, crucially, started with the escape character (ASCII 27, also known as Ctrl-]). This escape character signaled to the terminal that the output arriving from the computer was not to be displayed, but rather flagged the output as control information for the terminal itself, such as "switch to boldface", "change the text color to blue", "move the cursor to position 11, 43", or "change your character set to Latin-1", etc. (My apologies if you already know this stuff. It's necessary background, though, so I figured better to include it just in case...) So, hopefully you can see where I'm going with this. It's quite possible that OS/X's Terminal window understands a certain escape sequence to instruct it change the active font as well (since it's an Xterm emulator, I'm confident that escape sequences are used to control typeface, cursor location, text color, and many other things). If so, then having Python change the font is simply a matter of having your Python program emit the correct escape sequence at the time you desire the font to change. Note, however, that the font will most likely change for the ENTIRE Terminal screen, all at once. Historically, while many "real" terminals might have supported multiple fonts, very few supported multiple fonts SIMULTANEOUSLY. Terminal emulators such as OS/X's Terminal, being based on the "real" terminals of days past, generally behave in the same way. So, the good news is that this could be pretty easy to implement. The trick, however, will be figuring out if such an escape sequence exists for Terminal, and, if so, what it is. Google is your friend. Also, check out the termcap and/or terminfo entries -- /etc/termcap and (probably) /usr/share/terminfo/*/*, respectively -- for Terminal's TERM type. If such an escape sequence exists, it might well already be documented in one or both of these terminal databases. The only other alternative that readily comes to mind is that perhaps there's some programmatic interface to Terminal to tell it to change it's font. I tend to doubt this, but if it does exist then it will likely involve IPC (inter-process communication) and not be trival to implement (although not outrageously hard, either) -- you'd have to establish a connection between Python and the correct Terminal instance, and then send the right IPC message. Also, I guess that perhaps Terminal might even accepts signals to change its font (again, doubtful though). Check out Terminal's manual page (i.e., run "man Terminal") and see what signals it accepts and what they do. If you find one that changes the font, then just running something like "kill -SIGXXX 99" might work (where SIGXXX is a real and valid signal name and 99 is a real and valid process number for the correct Terminal instance). I hope this is helpful, at least in terms of the alternative you have before you (as I see them): escape sequences, some sort of IPC, or system signals. Again, I think you might get luckly with the first option, whereas I have serious doubts that Terminal supports the latter two options (but ya never know...) Good luck, Doug P.S. -- I just realized that you probably need to switch Terminal's CHARACTER SET, not it's FONT. That said, though, everything I wrote is still applicable -- just replace "character set" wherever I talk about "font". Plus, I think there's a MUCH higher probability that there exists escape sequences to switch Terminal's active character set (as compared to switching its font). However, you may run into the problem that -- as I described as a possibility concerning fonts -- Terminal might not be able to display but one character set at a time (i.e., it can only change the character set for the entire window at once), which could be add odds with your requirements. If Terminal can only have one active character set at a time, then IF there's a character set it supports that has BOTH Greek and English characters, you'd still be able to pull it off. A lot of the European character sets ARE like this (i.e., English chars mixed with specific European chars) -- but not the Symbol character set, I believe -- so I suspect that you're in good luck! Once you can successful
RE: Database Access using pyodbc. I've a problem
> -Original Message- > From: [EMAIL PROTECTED] > [mailto:[EMAIL PROTECTED] On > Behalf Of Rajendran > Sent: Sunday, June 17, 2007 3:06 AM > To: python-list@python.org > Subject: Re: Database Access using pyodbc. I've a problem > > Hi Robert, > Thanks for your response. > The problem I've mentioned comes up only with the Python but not with > the PHP. Is it because PHP has been integrated with Apache and Python > isn't? I mean, we have included these > > # For PHP 5 do something like this: > LoadModule php5_module "c:/php/php5apache2_2.dll" > AddType application/x-httpd-php .php > > # configure the path to php.ini > PHPIniDir "C:/php" > > > lines in the httpd.conf for Apache to understand PHP and no > corresponding lines for Python? > > Does this make Apache to run PHP with the permissions same as user? There are two user execution settings in Apache. The first (User) tells Apache which user to run as. The second (SuExec User) tells Apache which user to run CGI files as. These can (and should) be handled differently in a production system. I'm not familiar with how apache handles these functions in a Windows environment, but the references in a prior answer to this thread should help you out. -Doug -- http://mail.python.org/mailman/listinfo/python-list
RE: Are there any python jobs worked at home from the internet?
> I know of http://www.rentacoder.com/ but I've never actually used it. http://www.guru.com and http://www.getafreelancer.com are also good sites (in fact I got my current employment starting off as a contractor on guru.com) There are others, but these are the three I've worked with and felt comfortable working with. Hope this helps. -Doug -- http://mail.python.org/mailman/listinfo/python-list
RE: Python optimization (was Python's "only one way to do it"philosophy isn't good?)
> Is anyone out there who uses MS Word and doesn't deactivate > the "suggest" mode i.e. Clippy? Me... I don't install Clippy (or any of his horribly annoying friends) to start with. :) On the topic though, the suggest mode of the MS help system is generally way off-base, even for my 80-yr-old grandmother's needs. -- http://mail.python.org/mailman/listinfo/python-list
RE: installing cx_Oracle.
> It also works the other way around, at least on the non-empty > set of systems that contains my workstation. export simply > marks the variable name for automatic export to the > environment of subsequent commands. The value at that time > doesn't matter. What matters is the value that the name has > at the time the command is run: > > [EMAIL PROTECTED] ~]$ export FOOD > [EMAIL PROTECTED] ~]$ FOOD=spam > [EMAIL PROTECTED] ~]$ python -c "import os; print os.environ['FOOD']" > spam > [EMAIL PROTECTED] ~]$ FOOD=eggs > [EMAIL PROTECTED] ~]$ python -c "import os; print os.environ['FOOD']" > eggs Just tried on a FreeBSD 6.1 development box with stock /bin/sh and it works there too... ... And I just learned something new! -Doug -- http://mail.python.org/mailman/listinfo/python-list
Re: Bullet proof passing numeric values from NMEA data stream.
On Wed, 21 Mar 2007 00:29:00 +1100, Steven D'Aprano wrote: > On Tue, 20 Mar 2007 12:09:29 +0000, Doug Gray wrote: > >> Folks, >> I am looking for a fast but most importantly a bullet proof method to pass >> and NMEA data stream (GPS output) ascii numeric strings. The best I can >> offer is: >> >> def fint(a): >> try: return int(float(a)) >> except: return 0 > > > Will your application calculate the wrong results if it starts getting a > whole lot of spurious zeroes? Wouldn't it better to signal "this value is > invalid" rather than a false zero? > > Do you actually want ints? It seems to me that if your data stream is > delivering floats, you're throwing away a lot of data. For example, if the > data stream is: > > 2.4, 5.7, 3.9, 5.1, ... > > you're getting: > > 2, 5, 3, 5, ... > > which is possibly not even the right way to convert to ints. Shouldn't you > be rounding to nearest (i.e. 2, 6, 4, 5, ...)? > > [snip] > Thanks, a very helpful response. I'll need some time to fully digest. Yes I will need a float variant, the int version was by way of example. I can deal with the rounding etc as necessary, but I was after an pythonistic view of the generic problem. Re the examples: whitespace and mal positioned signs and decimal point would be the obvious errors I might expect but of course this is speculation. The few GPS units I have tried have all tripped up my first cut less tolerant code. I am going to revise the interface to work around potential problems and my preliminary test efforts highlighted more exceptions than I expected. Doug -- http://mail.python.org/mailman/listinfo/python-list
Re: Eureka moments in Python
On Tue, 13 Mar 2007 18:16:15 +1100, Steven D'Aprano wrote: > I'd be interested in hearing people's stories of Eureka moments in Python, > moments where you suddenly realise that some task which seemed like it > would be hard work was easy with Python. Mine was the discovery of the pybluez module. I had been sweating the task of interfacing a bluetooth GPS unit to my python applicaton. I googled for 'python bluetooth GPS' and found 20 lines of python code that had the interface up and running before breakfast. This included the package install with 'yum install pybluez' in Fedora Core 5. See: http://www.robertprice.co.uk/robblog/archive/2007/1/Using_A_Bluetooth_GPS_From_Python.shtml Doug Gray -- http://mail.python.org/mailman/listinfo/python-list
Bullet proof passing numeric values from NMEA data stream.
Folks, I am looking for a fast but most importantly a bullet proof method to pass and NMEA data stream (GPS output) ascii numeric strings. The best I can offer is: def fint(a): try: return int(float(a)) except: return 0 The reason for this is the quality of the data from the huge variety of GPS units available varies considerably. Some units do not follow the standard and I want to pass the data as best I can without hanging the code for an oddball data value. Can anyone suggest better? For example, each of the following throw the exception so do not return the correct value: int('00.') int(' 00.') float('- 00') float(' - 00') float(' - 00') float(' - 00.') float('- 00.') float('- 10.') float('- 10.') float('- 10.') int('- 10.') int('- 10.') float('- 10.') int('1.0') Also, why should I consider the string module? Is it faster/better? TIA, Doug -- http://mail.python.org/mailman/listinfo/python-list
Re: book for a starter
Excellent choice. I used the 2nd edition for better than a year as a reference as I "came up to speed" on the language. Didn't know there was a 3rd edition out. Doug On Tue, 2007-02-27 at 11:08 -0800, Sriram wrote: > Hi, > > If you have experience programming, just read the online tutorial at > http://docs.python.org/tut/tut.html > > I find Python Essential Reference (3rd Edition) (Developer's Library) > (Paperback) invaluable though. BTW I have the 2nd edition. > Amazon link : > http://www.amazon.com/gp/pdp/profile/A9N9B1L0O4BYJ/ref=cm_blog_dp_pdp/002-7062034-2980840 > > > On Feb 27, 10:58 am, Bjoern Schliessmann [EMAIL PROTECTED]> wrote: > > Wensui Liu wrote: > > > I just start learning python and have a question regarding books > > > for a newbie like me. > > > > http://wiki.python.org/moin/IntroductoryBooks > > > > > If you are only allowed to buy 1 python book, which one will you > > > pick? ^_^. > > > > I'd pick a reference. YMMV. > > > > Regards, > > > > Björn (having been allowed to buy more than one Python book) > > > > -- > > BOFH excuse #314: > > > > You need to upgrade your VESA local bus to a MasterCard local bus. > > -- http://mail.python.org/mailman/listinfo/python-list
Inconsistent list/pointer problem
I am having a problem with the corruption of a list. It occurs only the first time that I call a function and never happens on subsequent calls. Any suggestions would be appreciated. I call the function, passing in a list as the input data. The function must manipulate and operate on a copy of that list's data, without altering the list in the calling routine. def myFunc(listA): listB = listA work on & modify listB return(listB) The first time this function touches listB, listA is corrupted. However, I get the right results from the function. On subsequent calls to the function, listA is not corrupted further and the function will always return the same wrong results, which would be correct given the corruption of listA created in the first call. I concluded that it appears that listB is still pointing at elements of listA and I need to force Python to reassign those pointers to point to copies of listA's elements. I've tried copying listA to a tuple and then change the copy back to a list. That sometimes works if the input data is a simple list. It does not work if the input data is a list extracted from a list of lists. listB = tuple(listA) listB = list(listB) I've tried building the copy of listA, element by element, but that doesn't work. listB = [] for x in listA: listB.append(x) I finally had to do some type changing during the element by element copy and that does seem to work. Thanks in advance for any suggestions. Doug -- http://mail.python.org/mailman/listinfo/python-list
Re: Molten Metal Pools in WTC after weeks, only micronuke could have produced so much heat
<[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > W88 warhead design > > http://www.thepriceofliberty.org/06/09/25/wardpics-5.htm > > http://www.thepriceofliberty.org/06/09/25/wardpics-4.htm the diagrams are all wrong, they are fiction. -- http://mail.python.org/mailman/listinfo/python-list
Re: Py3K idea: why not drop the colon?
Michael Hobbs wrote: > Can anyone find a flaw with this change in syntax? > > Instead of dividing a compound statement with a colon, why not divide it > on a newline? For example, the colon could be dropped from this statement: > if self.hungry: > self.eat() > to > if self.hungry > self.eat() > > Python is already sensitive to whitespace and the newline anyway, so why > not put it to good use? For example, Python rejects this statement > because of the newline present: > if self.hungry or > self.depressed: > self.eat() > You need to use the backslash to continue the expression on the next line: > if self.hungry or \ > self.depressed: > self.eat() > The colon that divides the statement therefore seems redundant. The > colon could continue to be used for single-line statements: > if self.hungry: self.eat() > > I think the colon could be omitted from every type of compound > statement: 'if', 'for', 'def', 'class', whatever. Am I missing anything? > > Thanks, > - Mike It is a very good idea as the colon is technically redundant (not necessary for parsing, aside from one liners) and actually hurts readability (and writeability). The "evidence" people cite for the advantage of using a colon is research done by users of the ABC language, python's predecessor. They forget that A) that was like 20 years ago, B) the language was designed for children, and C) the keywords in ABC are IN ALL CAPS LIKE THIS (hurting readability and writeability) and thus adding a colon obviously helps restore some readability for users in that case but not in python's. However, python is far too old to accept any fundamental changes to syntax at this point. -- http://mail.python.org/mailman/listinfo/python-list
Fredrik Lundh [was "Re: explicit self revisited"]
Fredrik Lundh wrote: > Doug wrote: >> >> Fredrik Lundh wrote: >>> Fredrik Lundh wrote: >>> > cannot all you clueless trolls who cannot think of a single useful thing >>> > to contribute to Python start your own newsgroup? >> >>> and before anyone complains; please note that they're working through >> >>> http://www.effbot.org/pyfaq/design-index.htm >> >> That site is a bunch of FUD - >> The explicit self is there simply because OOP was tacked onto python as >> an afterthought. >> Why not just be honest about it. It's too late to change Python's >> syntax. It just means a little extra typing. If it really bothers >> someone, use "s" instead of "self" or else use Ruby. > > the official FAQ is a bunch of FUD? are you sure you know what FUD means? > > You idiot. Putting the word "official" in front of something doesn't mean it can't be FUD. Especially when it is written by people such as yourself. Have you not paid attention to anything happening in politics around the world during your lifetime? And yes, actually, the dash after FUD was where I was going to link to a definition of FUD to show I really meant to use that term. It doesn't appear that you believe anything that isn't on your own effbot site, however. -- http://mail.python.org/mailman/listinfo/python-list
Re: explicit self revisited
Fredrik Lundh wrote: > Fredrik Lundh wrote: > > cannot all you clueless trolls who cannot think of a single useful thing > > to contribute to Python start your own newsgroup? > > and before anyone complains; please note that they're working through > > http://www.effbot.org/pyfaq/design-index.htm That site is a bunch of FUD - The explicit self is there simply because OOP was tacked onto python as an afterthought. Why not just be honest about it. It's too late to change Python's syntax. It just means a little extra typing. If it really bothers someone, use "s" instead of "self" or else use Ruby. -- http://mail.python.org/mailman/listinfo/python-list
py2exe questions
I have 2 questions about py2exe or any similar utility. 1. Is it possible to create a single Windows executable that does not blow out to a folder full of files and can be called from scripts using command line arguments? 2. If the above can be done, it is possible to hide parts of the Python source code from users? These users are software developers, but we don't want them to see how the code does what it does. thanks, doug -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for the Perfect Editor
Try www.TextPad.com. I've used it for years and love it. It understands many programming language constructs and can be taught to understand python so that things show up in color. On 7 Sep 2006 13:18:22 -0700, "Omar" <[EMAIL PROTECTED]> wrote: >I'd love the perfect editor that would be: > >a) free > >b) enable me to drag and drop code snippets from a sort of browser into >the code > >c) can run programs right from within > >d) can edit > - PYTHON > - Javascript > - HTML > - actionscript (since I'm also learning flash) > >e) easy to learn > >suggestions? -- http://mail.python.org/mailman/listinfo/python-list
Re: ASN.1 encoder & decoder
Thanks Paul. This is exactly the type andlevel of implementation that I was looking for. I will look at the other implementation again. On 25 Aug 2006 16:32:46 -0700, Paul Rubin <http://[EMAIL PROTECTED]> wrote: >Doug Stell <[EMAIL PROTECTED]> writes: >> Can anyone provide guidance on building an ASN.1 decoder and encoder >> in Python? This does not have to be a general purpose implementation, >> drivenf from an ASN.1 template. It can be dedicated hard coded to a >> particular template. > >There might be some useful code in www.trevp.com/tlslite . -- http://mail.python.org/mailman/listinfo/python-list
Re: ASN.1 encoder & decoder
I looked at pyasn1. Unfortunately, it is not useful and provides a C interface. Thanks, anyhow. I figure that I will have to write my own, but am unsure of the best approach. Nested lists and distionaries might be useful and I am looking to the feasibility of those mechanisms. On Fri, 25 Aug 2006 23:20:41 +0100, Bruce Stephens <[EMAIL PROTECTED]> wrote: >Doug Stell <[EMAIL PROTECTED]> writes: > >> Can anyone provide guidance on building an ASN.1 decoder and encoder >> in Python? > ><http://sourceforge.net/projects/pyasn1/>? -- http://mail.python.org/mailman/listinfo/python-list
ASN.1 encoder & decoder
Can anyone provide guidance on building an ASN.1 decoder and encoder in Python? This does not have to be a general purpose implementation, drivenf from an ASN.1 template. It can be dedicated hard coded to a particular template. Doug Stell, [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Accessing USGS Web Service Using Python
Hi! ** Accessing the USGS Web Service Using Python ** I am trying to access the US Geological Survey's gazetteer SOAP web service using Python to find the locations of all the places with the name 'Alexandria.' I tried to keep this simple by putting a soap message in a string and sending the request using httplib. I am receiving the following error message. Reply: 400 Bad Request Bad Request ` I apologize in advance if this is not the correct approach. -- Here is my code ... import httplib # soap string to send soapstr = """ http://www.w3.org/2001/XMLSchema-instance"; xmlns:xsd="http://www.w3.org/2001/XMLSchema"; xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/";> http://gisdata.usgs.net/XMLWebServices/";> Alexandria ppl 10 1 """ # send request h = httplib.HTTP('gisdata.usgs.net') h.putrequest("POST", "/XMLWebServices/TNM_Gazetteer_Service.asmx HTTP/1.1") h.putheader("Content-Type", "text/xml; charset=utf-8") h.putheader("Content-Length", str(len(soapstr))) h.putheader ("SOAPAction", "http://gisdata.usgs.net/XMLWebServices/searchName";) h.endheaders() # send soap string h.send(soapstr) # get the HTTP response reply, message, headers = h.getreply() print "Reply: ", reply, message # print the results result = h.getfile().read() print result --- Here is the guidance from the USGS Web Site http://gisdata.usgs.net/XMLWebServices/TNM_Gazetteer_Service.asmx?op=searchName The following is a sample SOAP request. The placeholders shown need to be replaced with actual values. POST /XMLWebServices/TNM_Gazetteer_Service.asmx HTTP/1.1 Host: gisdata.usgs.net Content-Type: text/xml; charset=utf-8 Content-Length: length SOAPAction: "http://gisdata.usgs.net/XMLWebServices/searchName"; http://www.w3.org/2001/XMLSchema-instance"; xmlns:xsd="http://www.w3.org/2001/XMLSchema"; xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/";> http://gisdata.usgs.net/XMLWebServices/";> string string string string --- Thank you! -- http://mail.python.org/mailman/listinfo/python-list
Re: How do you practice Python?
On 6/2/06, Norbert Kaufmann <[EMAIL PROTECTED]> wrote: Ray wrote:[...]> Um, I mean, what if you have to use something other than> Python/Jython/IronPython? :) How do you keep your Python skill sharp?>You could use IPython as your primary shell. Than you have the opportunity to do all these nasty automation tasks -- create test data,deploy configuration files, search in logfiles for errors, etc. -- foryour project in Python.Convince your project manager to develop prototypes. No one in your company is better and faster in prototyping than the Python expert Ray.HTHNorbert--It is easier to get forgiveness than permission.-- http://mail.python.org/mailman/listinfo/python-listI've got a couple of posts at my blog that could help you here because I've often had your problem with new languages. http://straw-dogs.co.uk/blog/01/26/practice-makes-perfect/ <-- A list of resources such as quizes, practice, games, tests and info.http://straw-dogs.co.uk/blog/05/31/scripting-an-easy-life/ <-- Just some ideas for automating tasks on your system(s).All the best.Doug -- http://mail.python.org/mailman/listinfo/python-list
Re: Best IDE for Python?
On 5/5/06, Christoph Haas <[EMAIL PROTECTED]> wrote: On Fri, May 05, 2006 at 04:50:11PM +0100, Doug Bromley wrote:> I have a Python IDE review I did a few months back you may want to view:> http://www.straw-dogs.co.uk/blog/python-ide-review Sounds interesting. Could you fix the screenshots? I just get a 404 here.Kindly ChristophP.S.: [Rant about TOFU posting suppressed.]-- http://mail.python.org/mailman/listinfo/python-listApologies for that - Thanks for pointing it out. The links and images are now fixed.All the best.Doug -- http://mail.python.org/mailman/listinfo/python-list
Re: Best IDE for Python?
I have a Python IDE review I did a few months back you may want to view:http://www.straw-dogs.co.uk/blog/python-ide-reviewHope that helps. DougOn 5 May 2006 08:28:00 -0700, Saurabh Sardeshpande <[EMAIL PROTECTED]> wrote: Pardon if this is already discussed extensively. But what is the bestIDE for Python for a newbie? I have experience in C++ and Java and thisis the first time I am learning a scripting language.Thanks in advance --http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Can I use python for this .. ??
Careful of using the wrong tool for the job. Don't use Python for the sake of it unless its as a learning experience.All of the things you ask for can be done by simply using the Windows start menu to launch a shortcut with various command line options. Voila - problem solved. On 5 May 2006 05:15:46 -0700, nikie <[EMAIL PROTECTED]> wrote: san wrote:> Hi>> I am using windows xp and have installed python and win32. I am> familiar with basic Python. I wanted to control some of the> applications via python script.> > I would like to write a python script to say:> 1. Open firefox and log on to gmail> 2. Another firefox window to visit slickdeals> 3. Open winamp and tune in to a shoutcast station> 4. Open groupwise ... > etc ..>> These are the task I do every day whenever I log on my computer .. it> just seems repetitive and hence probably can be coded in python.>> Can I do this in python? Where do I find the COM objects/interfaces for > all these different programs? Are there any sample codes ?I just googled for "iTunes com python", there are lots of samples. Ifyou can't find any, or want to find out about an applications interfaces yourself, you can sill use MakePy to find out what cominterfaces are installed on your computer, and simply use the "dir" and"help" commands in the interactive console on those interfaces to find out what they do. (There are other tools to explore COM interfaces,like OleView, but if you're familiar with Python already, usingdir/help is probably going to be easier)Reading Mark Hammond's excellent book (or at least the sample chapter on automation) wouldn't hurt either ;-)--http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Best IDE for Python?
You may find the IDE review at Straw Dogs worth a look: http://www.straw-dogs.co.uk/blog/python-ide-reviewOn 3/31/06, Keith B. Perry <[EMAIL PROTECTED]> wrote: To me, it just doesn't behave the same way as Eclipse for java. I have used the plug-in, and I usually use it on my home machine ( I am still a student). For example, in Java eclipse, if you import a module like math, then if you want to use a math function, you just type math + period, and then all the functions pop up in a scroll menu. I love this. I am not searching through online documentation...etc just to find some stupid method/function that I know is there. It doesn't seem to behave like this for PythonI wish it did. I still love programming in Python, though. On 3/31/06, Fabio Zadrozny <[EMAIL PROTECTED] > wrote: On 31 Mar 2006 06:46:35 -0800, kbperry <[EMAIL PROTECTED] > wrote: I have recently been trying out NewEdit, and it is a pretty good "IDE"for Python. The reason that I have it in quotes is because I haven't really found atrue IDE (like the way Eclipse behaves for Java) for python. (I realize that Eclipse has a plug-in for Python, too). So, why wouldn't you consider Pydev (the python plugin for Eclipse) a Python IDE? -- 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: Programming challenge: wildcard exclusion in cartesian products
"funkyj" <[EMAIL PROTECTED]> writes: > One advantage of a generator over filtering the full product is that I, > as the user of the generator, am not obligated to iterate over the > entire solution space. > > Are there other _practical_ advantages of generators over mapping & > filtering complete sets? Storage. You can iterate over problem spaces much too large to fit in memory. Also generate + iterate can be faster because of reduced memory pressure. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python / glade fundamentals
OK, I have solved the problem. The reference was a help. The clue is that the events may not get passed through the parent. For reference here is the code that worked. It's good to finally get the basics working. Doug import gtk import gtk.glade def key_press(widget,event): print "keypress" xml = gtk.glade.XML('pgtest.glade') widget = xml.get_widget('drawingarea1') xml.signal_autoconnect({ "on_page_key_press_event": key_press, "on_page_destroy_event": gtk.main_quit }) gtk.main() ===file: pgtest.glade=== http://glade.gnome.org/glade-2.0.dtd";> True PGtestWindow GTK_WINDOW_TOPLEVEL GTK_WIN_POS_NONE False 640 480 True True True False False GDK_WINDOW_TYPE_HINT_NORMAL GDK_GRAVITY_NORTH_WEST True -- http://mail.python.org/mailman/listinfo/python-list
Python / glade fundamentals
Hi all, Can someone tell me why I do not get a connection between the events and the functions in the sample below. GUI window appears OK, just no connections seem to be made. I am new to this so may be missing something fundamental. Thanks, Doug file pgtest.glade = http://glade.gnome.org/glade-2.0.dtd";> True GDK_KEY_PRESS_MASK PGtestWindow GTK_WINDOW_TOPLEVEL GTK_WIN_POS_NONE False 640 480 True True True False False GDK_WINDOW_TYPE_HINT_NORMAL GDK_GRAVITY_NORTH_WEST True GDK_KEY_PRESS_MASK GDK_EXTENSION_EVENTS_ALL file pgtest.py == import gtk import gtk.glade def on_drawingarea1_key_press(widget): print "keypress" xml = gtk.glade.XML('pgtest.glade') widget = xml.get_widget('drawingarea1') #print type(xml) xml.signal_autoconnect({ "on_drawingarea1_key_press_event": on_drawingarea1_key_press, "on_page_destroy_event":gtk.mainquit }) gtk.main() -- http://mail.python.org/mailman/listinfo/python-list
libglade for python-2
I am having some fun running a program called pygps. This uses libglade and runs fine on my very old Redhat 7.? system running Python 1.5.2. I have not needed to make any changes to the import files (see below). The program uses a glade generated pygps.glade xml file for the gui. I like the way this works and the ability to edit the xml(?) with glade. Now on my Fedora system which has version 2 of just about everything it will not run and I cannot figure how to get the code to work. The site packages include a glade.so file but there is no libglade. Googling I have not found specifc support for libglade in anything other than ada and c, nothing for python 2.0. Is there a mechanism to invoke libglade operation (ie a separate xml file generated by glade-2 like I have with the old python 1 system? Note that I have discovered the older glade files are not compatible with glade-2. Is libglade dead now for python-2 or am I missing something? See: http://pygps.org/ Imports from pygps: import GDK from gtk import * import math import socket, string import libglade import GdkImlib import os from LatLongUTMconversion import LLtoUTM import NMEA (Ignore the last two, they are local but I have included them for completeness) Doug -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Evangelism
A defector!Release the hounds!Burn the scum! -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Evangelism
Python is in desperate need of marketing and I don't think its new site will help it.The Ruby community has a fanaticism we could learn from and its going some way to 'converting' me. The community is alive, growing, shouting from the roof tops while the Python community seems to sit in its ivory towers conducting research and corporate development in 'forward-thinking' companies such as Google. I can see Ruby overtaking Python if we don't ALL do something about it.On 9 Mar 2006 02:43:53 -0800, Gerard Flanagan < [EMAIL PROTECTED]> wrote:Steve Holden wrote:> I've been thinking (and blogging) about python evangelism since PyCon, > as a result of which I created a squidoo lens:>>http://www.squidoo.com/pythonlogy>> Imagine my surprise at discovering that this has gone up in rank (by > number of views) from # 442,000 or so to #153! Clearly there's some> mileage in marketing Python, and I'd like to keep the buzz going if it> means more people will adopt the language.>> Any suggestions for improvement? > '-nology' not '-nlogy' in the link.I like the 'What's Happening on Planet Python' section - I find theplanetpython.org gives too much of an intro to the pages it links to. A line or too, as in the lens site, would be preferable in my view.Just a thought - would a similar section be suitable for 'python.org'main page?Gerard-- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: New python.org website
I much prefer the look and feel of the potential Ruby websites being developed at the moment. The Python site is very corporate and academic which could put many early adopters off. I'm sure you've all heard accusations that Python doesn't have the marketing drive of Ruby. Perhaps this is an example where we could do with taking a leaf out of Ruby's book? ( http://redhanded.hobix.com/redesign2005/)-Doug Bromleyblog.straw-dogs.co.uk On 8 Mar 2006 14:20:29 -0800, Kay Schluehr <[EMAIL PROTECTED]> wrote: Michael Tobis wrote:> > No one> > of the complainers and negativists do claim that they could do it much> > better.>> Indeed, I do not have to be able to write a particular program to > notice it has bugs.>> On the other hand, (since I think the design, while not brilliant, is> good) fixing the logo is something that can be achieved without too> much fuss.> > > But I think at times it might be usefull to consult> > professional aid.>> In the case of the logo design, I am not sure I agree.>> I think the twisted logo>> http://saph.twistedmatrix.com/blog/archives/twisted.png>> and the PyCon logo>> http://mirrors.ccs.neu.edu/Python/pub/old-www/pics/pycon-logo.gif>> were probably not designed by professional designers but rather by> people who appreciate Python, and yet do have more appeal to the > community and the outside world alike. If we are going to use a snake> motif, we should use snakes that look like snakes.Maybe its time for me to abandone this discussion. If you and othersfeel quite well represented by a pasty and wordy snake than go for it. I do neither feel embraced nor bitten by it. And I don't just mean thelogo. We can do an awfull lot of comparisons with pages that failed butthis doesn't bring forth anything.This evening we talked at the Hofbraeuhaus at Munich about Michelangelo whose sixtine chapel images where once overpainted because his figuresappeared naked "as god created them". But maybe he was wrong and hiscustomer, the pope, was right and they were actually born with a leaf covered their pubic hairs? The pope had to take responsibility and hadto appease possible and real critics. We can assume he was far frombeing an idiot but a serious man - a politician. As a serious person myself I'm always a little splitted between Michelangelo and the pope.My own idealism expects Michelangelo doing such outstanding things thatit is beyond anything. Nothing could be better than having the uptights as the most severe enemies. What a fun! But as it seems my politicalparty is guided by ordinary indifferent humans as well and Michelangelomay be as much attracted by it as I am by e.g. the german socialdemocratic party? So I should track back and rethink "the professional aid" which might be not what I'm really looking for. Guido feels a deepjoy about the resonance between Python and an programmer and artist -Juergen Scheible - who likes the language, feels inspired by it and creates a little artwork for Nokia 60s. So there is some inversion inthe right direction. Suddenly Python appears a bit distorted withinanother context and it becomes sexy again. Should we talk about Apple next ... ?--http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: warning for google api users
Producing a SERPS scraper for Google would be very easy and possible in about 10-15 lines of code. However, its against the Google terms of service and if they decide to bite you for breaching them then you'll be in trouble. Its also a reason you'll not likely find one that trumpets its existence very much as the site promoting it would probably be taken off the Google index - severely effecting visitors. On 2/21/06, Gabriel B. <[EMAIL PROTECTED]> wrote: the google webservices (aka google API) is not even close for any kindof real use yetif you search for the same term 10 times, you get 3 mixed totals. 2mixed result order. and one or two "502 bad gateway" i did an extensive match agains the API and the regular searchservice. the most average set of results:results 1-10; total: 373000results 11-20; total: 151000results 21-30; total: 151000results 31-40; total: 373000 results 41-50; total: 373000results 51-60; total: 373000results 61-70; total: 151000( 502 bad gateway. retry)results 71-80; total: 373000results 81-90; total: 151000( 502 bad gateway. retry) results 91-100; total: 373000on the regular google search, total: 2,050,000 (for every page, ofcourse)besides that, the first and third result on the regular google search,does not apear in the 100 results from the API in this query, but this is not average, more like 1 chance in 10 :-/So, no matter how much google insists that this parrot is sleeping,it's simply dead.now, what i presume that is happening, is that they have a dozen of machine pools, and each one has a broken snapshot of the productionindex (probably they have some process to import the index and or itexplode in some point or they simply kill it after some time). andthey obviously don't run that process very often. Now... anyone has some implementation of pygoogle.py that scraps theregular html service instead of using SOAP? :)Gabriel B.--http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Python for PHP Programmers
Hi AllPlease be gentle but I'm primarily a PHP coder after a few years of academic experience in Java I've lost my object orientated programming style and have become a procedural PHP coder. I started using Python almost 12mths ago now but I'm still very much working in a PHP style. Obviously I need to learn the Python way and I have been doing a piece at a time, however, I was wondering if you had any specific advice for PHP -> Python programmers? Any habits I need to pickup/drop? Thanks for any input and thanks for your patience.Doug -- http://mail.python.org/mailman/listinfo/python-list
Re: editor for Python on Linux
I did a review of Python IDE's at my blog. If you're interested you can take a look:http://www.straw-dogs.co.uk/blog/python-ide-reviewI have a couple of links to other reviews on there too. Worth a look if you're trying to find a good IDE. On 2/20/06, Tim Parkin <[EMAIL PROTECTED]> wrote: Mladen Adamovic wrote:>Hi!>>I wonder which editor or IDE you can recommend me for writing Python>programs. I tried with jEdit but it isn't perfect.>>>I've been using wing for quite some time and it's an excellent dedicated editor for python. If you want flexible debugging in a gui environmentit's hard to beat.Tim Parkin--http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Jedit
I've often wondered this. I was thinking more along the lines of a scriptable Python editor like Emacs. The only thing I've noticed is: CUTE - *nix only. - (http://cute.sourceforge.net/) PyEditor - (http://www.rexx.com/~dkuhlman/pyeditor_howto.html) ViImproved - (http://wiki.python.org/moin/ViImproved) PythonCardEditor - (http://wiki.wxpython.org/index.cgi/PythonCardEditor) On 2/14/06, ziggy <[EMAIL PROTECTED]> wrote: > Just wondering if there is something out there like Jedit, but written > in python ( not just supporting, but actually written in it.. ) > > Nothing large like Stanzi's or Boa.. Just something quick and simple, > with code completion, and a debugger.. > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
cross compile python for linux-ppc-604
Has anyone successfully compiled python 2.4 to run under linux powerpc 604? I have the ELINOS cross compile environemnt working, but always run into problems when executing make. Unfortunately, my target embedded system does not have a complete build chain so I have to use a cross compiler. Is there a prebuilt distribution of python2.4 that runs under linux-ppc? -- http://mail.python.org/mailman/listinfo/python-list
Re: Filename case-insensitivity on OS X
In article <[EMAIL PROTECTED]>, Tom Anderson <[EMAIL PROTECTED]> wrote: > Afternoon all, > > MacOS X seems to have some heretical ideas about the value of case in > paths - it seems to believe that it doesn't exist, more or less, so "touch > foo FOO" touches just one file, you can't have both 'makefile' and > 'Makefile' in the same directory, > "os.path.exists(some_valid_path.upper())" returns True even when > "os.path.split(some_valid_path.upper())[1] in > os.listdir(os.path.split(some_valid_path)[0])" returns False, etc > (although, of course, "ls *.txt" doesn't mention any of those .TXT files > lying around). Strictly speaking, it's not OS X, but the HFS file system that is case insensitive. You can use other file systems, such as "UNIX File System". Use Disk Utility to create a disk image and then erase it (again, using Disk Utility) and put UFS on it. You'll find that "touch foo FOO" will create two files. -- Doug Schwarz dmschwarz&urgrad,rochester,edu Make obvious changes to get real email address. -- http://mail.python.org/mailman/listinfo/python-list
ElementTree - Why not part of the core?
Why is the ElementTree API not a part of the Python core? I've recently been developing a script for accessing the Miva API only to find all the core API's provided by Python for parsing XML is messy and complicated. Many of the examples I see for parsing the data using these API's uses a similar additional Class for collapsing the XML data into a more manageable format. This is clearly not following the Python-way of clean, simple code and easy development. ElementTree on the other hand provides incredibly easy access to XML elements and works in a more Pythonic way. Why has the API not been included in the Python core? -- http://mail.python.org/mailman/listinfo/python-list
Re: Some more odd behaviour from the Regexp library
In article <[EMAIL PROTECTED]>, "David Veerasingam" <[EMAIL PROTECTED]> wrote: > Can anyone explain why it won't give me my captured group? > > In [1]: a = 'exit: gkdfjgfjdfsgdjglkghdfgkd' > In [2]: import re > In [3]: b = re.search(r'exit: (.*?)', a) > In [4]: b.group(0) > Out[4]: 'exit: ' > > In [5]: b.group(1) > Out[5]: '' > > In [6]: b.group(2) > IndexError: no such group The ? tells (.*?) to match as little as possible and that is nothing. If you change it to (.*) it should do what you want. -- Doug Schwarz dmschwarz&urgrad,rochester,edu Make obvious changes to get real email address. -- http://mail.python.org/mailman/listinfo/python-list
CGI File Uploads and Progress Bars
Hey, Folks: I'm writing a CGI to handle very large file uploads. I would like to include a progress bar. I think I'm about done. I have code to handle the file upload, and I think I can add an IFrame to my page which posts to check file size (so I can tell how many bytes have been received). My problem is that I want to provide a % complete. In order to do that, of course, I need to know not only the number of bytes received, but also the total number of incoming bytes. Here's the heart of the code: while afcommon.True: lstrData = lobjIncomingFile.file.read(afcommon.OneMeg) if not lstrData: break lobjFile.write(lstrData) llngBytes += long(len(lstrData)) lobjFile.close() Assume that lobjIncomingFile is actually a file-type element coming from CGI.FieldStorage. It's already been tested to ensure that it is a file-type element. Also, assume that I've already opened a file on the server, referred to by lobjFile (so lobjFile is the target of the incoming data). If this were a client application opening a file, I would just do the following: import os print os.stat('myfile.dat')[6] But, of course, this isn't a local file. In fact, it's not really a file at all. It is the contents of a file already rolled up into the HTTP header of the incoming HTTP request to the Web server. The CGI module is kind enough to handle all of the really hard stuff for me (like unpacking and decoding the header contents, etc.). But, I still need to know the size of the incoming file data. Of course, I could do this by reading the whole thing into a string variable and then testing the length of the string, as follows: s = lobjIncomingFile.file.read() SizeOfFileIs = len(s) But that really defeats the purpose, since my whole goal here is to provide a progress bar, which is contingent upon a "chunking" approach. Besides, for the file sizes that I'll be dealing with, I surely wouldn't want to read the whole thing into memory. So, bottom line: Does anyone know how to get the size of the incoming file data without reading the whole thing into a string? Can I do something with content_header? Thanks much for any insight that you might have. Doug -- http://mail.python.org/mailman/listinfo/python-list
Re: Favorite non-python language trick?
In article <[EMAIL PROTECTED]>, "Enrico" <[EMAIL PROTECTED]> wrote: > "Joseph Garvin" <[EMAIL PROTECTED]> ha scritto nel messaggio > news:[EMAIL PROTECTED] > > --This code won't run because it's in a comment block > > --[[ > > print(10) > > --]] > > > > --This code will, because the first two dashes make the rest a comment, > > breaking the block > > ---[[ > > print(10) > > --]] > > > > So you can change whether or not code is commented out just by adding a > > dash. This is much nicer than in C or Python having to get rid of """ or > > /* and */. Of course, the IDE can compensate. But it's still neat :) > > python: > > """ > print 10 > """ > > and > > #""" > print 10 > #""" It seems to me that this trick works in Python,too. """ print 10 #""" and #""" print 10 #""" You only have to change the first triple quote. -- Doug Schwarz dmschwarz&urgrad,rochester,edu Make obvious changes to get real email address. -- http://mail.python.org/mailman/listinfo/python-list
[no subject]
Is there a good IDE for Python? I have heard that Eclipse has a plugin for Jython only. Thanks --Doug -- http://mail.python.org/mailman/listinfo/python-list
Re: Regex for repeated character?
In article <[EMAIL PROTECTED]>, Leif K-Brooks <[EMAIL PROTECTED]> wrote: > How do I make a regular expression which will match the same character > repeated one or more times, instead of matching repetitions of any > (possibly non-same) characters like ".+" does? In other words, I want a > pattern like this: > > >>> re.findall(".+", "foo") # not what I want > ['foo'] > >>> re.findall("something", "foo") # what I want > ['f', 'oo'] How's this? >>> [x[0] for x in re.findall(r'((.)\2*)', 'abbccccccbba')] ['a', 'bb', 'ccc', '', 'ccc', 'bb', 'a'] -- Doug Schwarz dmschwarz&urgrad,rochester,edu Make obvious changes to get real email address. -- http://mail.python.org/mailman/listinfo/python-list
Re: Compute pi to base 12 using Python?
In article <[EMAIL PROTECTED]>, Dick Moores <[EMAIL PROTECTED]> wrote: > Dan wrote at 18:02 4/13/2005: > >On Wed, 13 Apr 2005 03:27:06 -0700, Dick Moores <[EMAIL PROTECTED]> > >wrote: > > > > > I'm just trying to help an artist acquaintance who needs (I just > > >learned) the first 3003 digits of pi to the base 12. > > > >Now you've got me curious. Why would an artist want the first 3003 > >digits of pi to the base 12? > > He says, > Do you know how I can get "base12 pi"? > Because the chromatic scale is base12. > c c# d d# e f f# g g# a a# b > > Dick Does your artist friend have any idea what base 12 means? The chromatic scale is based on one twelfth powers of two, i.e., if the frequency of a note in the scale is f(n), then the frequency of the next note is given by f(n+1) = f(n) * 2^(1/12) so by the time you go all 12 notes in an octave you have doubled the frequency. There is nothing here involving base 12 or pi. -- Doug Schwarz dmschwarz&urgrad,rochester,edu Make obvious changes to get real email address. -- http://mail.python.org/mailman/listinfo/python-list
Re: File Uploads
You're right, of course, and I do appreciate it. I generally am calling functions and returning strings and then printing the entire string. For example: def SomeFunc(): lstrRetVal = '' lstrRetVal += 'Content-type: text/html\n\n' lstrRetVal += more HTML here... return lstrRetVal Then, the calling code does: print SomeFunc() In this case, the extra new line character is appropriate. Somehow, the extra new line character slipped in on the print statement in my upload sample code (I probably copied from a function that returns a string). But thanks just the same... Just to be complete (so that no one comments about string concatenation efficiency), in a real application I would generally use triple quotes for HTML (or append to a list and then .join into a string at the end)... Thanks to all for your help. "Tim Roberts" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > "Doug Helm" <[EMAIL PROTECTED]> wrote: > > >Hey, Folks: > > > >I'm trying to write a very simple file upload CGI. I'm on a Windows server. > >I *am* using the -u switch to start Python for CGIs, as follows: > > > >c:\python\python.exe -u %s %s > > > >I *do* have write permissions on the directory I'm trying to write to. But, > >when I click submit, it just hangs. Any help would be greatly appreciated. > >Thanks. Here's the code... > > > >Upload.py > > > >import cgi > > > >print "content-type: text/html\n\n" > > I see you got your problem solved, but you should know there is a problem > with this line. The print statement automatically adds an end-of-line, so > this will actually end up producing TWO blank lines after the header. You > should use this: > > print "Content-type: text/html\n" > -- > - Tim Roberts, [EMAIL PROTECTED] > Providenza & Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: File Uploads
Andrew: I'm a dope. You're brilliant. Thank you. That worked splendidly. Doug <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Doug Helm wrote: > > > form = cgi.FieldStorage() > > if lobjUp.Save('filename', 'SomeFile.jpg'): > > > class BLOB(staticobject.StaticObject): > > def Save(self, pstrFormFieldName, pstrFilePathAndName): > > form = cgi.FieldStorage() > > You are instantiating cgi.FieldStorage twice. This won't work for POST > requests, because instantiating a FieldStorage reads the form data from > the standard input stream (the HTTP request). > > Try to create a second one and cgi will try to read all the form data > again; this will hang, waiting for the socket to send it a load more > data which will not be forthcoming. > > When using CGI, parse the input only once, then pass the results (a > FieldStorage object if you are using the cgi module) in to any other > functions that need to read it. > > -- > Andrew Clover > mailto:[EMAIL PROTECTED] > http://www.doxdesk.com/ > -- http://mail.python.org/mailman/listinfo/python-list
Re: String Splitter Brain Teaser
In article <[EMAIL PROTECTED]>, James Stroud <[EMAIL PROTECTED]> wrote: > Hello, > > I have strings represented as a combination of an alphabet (AGCT) and a an > operator "/", that signifies degeneracy. I want to split these strings into > lists of lists, where the degeneracies are members of the same list and > non-degenerates are members of single item lists. An example will clarify > this: > > "ATT/GATA/G" > > gets split to > > [['A'], ['T'], ['T', 'G'], ['A'], ['T'], ['A', 'G']] How about this? import re s = "ATT/GATA/G" result1 = re.findall(r"./.|.", s) consensus = [c.split("/") for c in result1] -- Doug Schwarz dmschwarz&urgrad,rochester,edu Make obvious changes to get real email address. -- http://mail.python.org/mailman/listinfo/python-list
Re: String Splitter Brain Teaser
In article <[EMAIL PROTECTED]>, James Stroud <[EMAIL PROTECTED]> wrote: > Hello, > > I have strings represented as a combination of an alphabet (AGCT) and a an > operator "/", that signifies degeneracy. I want to split these strings into > lists of lists, where the degeneracies are members of the same list and > non-degenerates are members of single item lists. An example will clarify > this: > > "ATT/GATA/G" > > gets split to > > [['A'], ['T'], ['T', 'G'], ['A'], ['T'], ['A', 'G']] How about this? import re s = "ATT/GATA/G" result1 = re.findall(r"./.|.", s) consensus = [c.split("/") for c in result1] -- Doug Schwarz dmschwarz&urgrad,rochester,edu Make obvious changes to get real email address. -- http://mail.python.org/mailman/listinfo/python-list
File Uploads -- Windows Server
I should have been more clear in my subject line. I was also the poster in the "File Uploads" topic. I'm not having any luck getting file uploads to work (multi-part HTML form) on a Windows server. I'm using a very close approximation of public domain code that I found. I've tried a couple of different implementations (very similar), but I am essentially using the following test code: http://www.voidspace.org.uk/python/cgi.shtml#upload which does *not* work on my Windows / IIS server. I have CGIs (py and pyc files) configured as follows: C:\Python\Python.Exe -u %s %s C:\Python is (of course) where Python is installed on my machine. -u allows for binary data to be processed (I believe) I'm not sure what %s %s does (would be nice to know...) Anyway, I believe I have write permissions in the directory that I'm trying to write (and would expect an error if I didn't)... I'm not getting any error. I submit a multi-part form to save a file attachment to disk, and the post just hangs. Does anyone have any ideas on this? Has anyone made CGI file uploads work in a Windows / IIS environment? Thanks much for any help that you can provide. Doug -- http://mail.python.org/mailman/listinfo/python-list
Re: File Uploads
Thanks, Dimitri. Yes, I found that same code too and tried it with the exact same result as the code I've uploaded (just hangs). But, OK. You have it working, so it must be a systems issue. Are you also on a Windows IIS web server? Do you have CGI configured the same way (i.e. .py = python.exe -u %s %s)? Thanks. Doug "dimitri pater" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Maybe this helps: > http://www.voidspace.org.uk/python/cgi.shtml#upload > > I use it, it works for fine me > Maybe it will give you some clues on how to tweak your own script. > > Dimitri > > > On Sun, 27 Mar 2005 10:32:20 -0700, Doug Helm <[EMAIL PROTECTED]> wrote: > > Hey, Folks: > > > > I'm trying to write a very simple file upload CGI. I'm on a Windows server. > > I *am* using the -u switch to start Python for CGIs, as follows: > > > > c:\python\python.exe -u %s %s > > > > I *do* have write permissions on the directory I'm trying to write to. But, > > when I click submit, it just hangs. Any help would be greatly appreciated. > > Thanks. Here's the code... > > > > Upload.py > > > > import cgi > > > > print "content-type: text/html\n\n" > > > > form = cgi.FieldStorage() > > if not form: > > print """ > > > > > > > > > enctype="multipart/form-data"> > > > > > > > > > > > > """ > > else: > > import BLOB > > lobjUp = BLOB.BLOB() > > if lobjUp.Save('filename', 'SomeFile.jpg'): > > print """ > > > > > > > > File successfully saved. > > > > > > """ > > else: > > print """ > > > > > > > > Unable to save file. > > > > > > """ > > > > -- > > > > Blob.py > > > > import cgi > > import staticobject > > > > cTrue = 1 > > cFalse = 0 > > > > try: > > import msvcrt,os > > msvcrt.setmode( 0, os.O_BINARY ) # stdin = 0 > > msvcrt.setmode( 1, os.O_BINARY ) # stdout = 1 > > except ImportError: > > pass > > > > class BLOB(staticobject.StaticObject): > > > > def __init__(self): > > self.initializing = cTrue > > staticobject.StaticObject.__init__(self) > > self.initializing = cFalse > > > > def Save(self, pstrFormFieldName, pstrFilePathAndName): > > > > # tried this first -- same result -- just hangs... > > #try: > > # form = cgi.FieldStorage() > > # item = form[pstrFormFieldName] > > # if item.file: > > #data = item.file.read() > > #f = open(pstrFilePathAndName,'wb') > > #f.write(data) > > #f.close() > > #return cTrue > > # else: > > #return cFalse > > #except: > > # return cFalse > > > > form = cgi.FieldStorage() > > f = open(pstrFilePathAndName,'wb') > > f.write(form[pstrFormFieldName].value) > > f.close() > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > -- > Please visit dimitri's website: www.serpia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: String Splitter Brain Teaser
In article <[EMAIL PROTECTED]>, James Stroud <[EMAIL PROTECTED]> wrote: > Hello, > > I have strings represented as a combination of an alphabet (AGCT) and a an > operator "/", that signifies degeneracy. I want to split these strings into > lists of lists, where the degeneracies are members of the same list and > non-degenerates are members of single item lists. An example will clarify > this: > > "ATT/GATA/G" > > gets split to > > [['A'], ['T'], ['T', 'G'], ['A'], ['T'], ['A', 'G']] How about this? import re s = "ATT/GATA/G" result1 = re.findall(r"./.|.", s) consensus = [c.split("/") for c in result1] -- Doug Schwarz dmschwarz&urgrad,rochester,edu Make obvious changes to get real email address. -- http://mail.python.org/mailman/listinfo/python-list
File Uploads
Hey, Folks: I'm trying to write a very simple file upload CGI. I'm on a Windows server. I *am* using the -u switch to start Python for CGIs, as follows: c:\python\python.exe -u %s %s I *do* have write permissions on the directory I'm trying to write to. But, when I click submit, it just hangs. Any help would be greatly appreciated. Thanks. Here's the code... Upload.py import cgi print "content-type: text/html\n\n" form = cgi.FieldStorage() if not form: print """ """ else: import BLOB lobjUp = BLOB.BLOB() if lobjUp.Save('filename', 'SomeFile.jpg'): print """ File successfully saved. """ else: print """ Unable to save file. """ -- Blob.py import cgi import staticobject cTrue = 1 cFalse = 0 try: import msvcrt,os msvcrt.setmode( 0, os.O_BINARY ) # stdin = 0 msvcrt.setmode( 1, os.O_BINARY ) # stdout = 1 except ImportError: pass class BLOB(staticobject.StaticObject): def __init__(self): self.initializing = cTrue staticobject.StaticObject.__init__(self) self.initializing = cFalse def Save(self, pstrFormFieldName, pstrFilePathAndName): # tried this first -- same result -- just hangs... #try: # form = cgi.FieldStorage() # item = form[pstrFormFieldName] # if item.file: #data = item.file.read() #f = open(pstrFilePathAndName,'wb') #f.write(data) #f.close() #return cTrue # else: #return cFalse #except: # return cFalse form = cgi.FieldStorage() f = open(pstrFilePathAndName,'wb') f.write(form[pstrFormFieldName].value) f.close() -- http://mail.python.org/mailman/listinfo/python-list
Re: programmatically calling a function
In article <[EMAIL PROTECTED]>, Reinhold Birkenfeld <[EMAIL PROTECTED]> wrote: > Doug Schwarz wrote: > > > Dave, > > > > I think eval might be what you're looking for: > > > > f = eval('len') > > length = f([1,2,3]) > > But only if the string given to eval is checked thorougly for allowed > contents. Better use getattr. > > Reinhold Actually, upon reading Peter Hansen's reply more carefully, I wil defer to his approach, namely, def foo(): print "foo" f = globals()["foo"] as I suspect that it will be more efficient. You still need to make sure that the string in question is one of the keys in the globals() dictionary or else handle the error -- just as with eval. I don't see how getattr solves the original problem. What, exactly, is the first argument to getattr? -- Doug Schwarz dmschwarz&urgrad,rochester,edu Make obvious changes to get real email address. -- http://mail.python.org/mailman/listinfo/python-list
Re: programmatically calling a function
In article <[EMAIL PROTECTED]>, Dave Ekhaus <[EMAIL PROTECTED]> wrote: > hi > > i'd like to call a python function programmatically - when all i have > is the functions name as a string. i.e. > > > fnames = ['foo', 'bar'] > > for func in fnames: > > # > # how do i call function 'func' when all i have is the name of the > function ??? > # > > > > def foo(): > > print 'foo' > > def bar(): > > print 'bar' > > > i'd really appreciate any help the 'group' has to offer. > > > thanks > dave Dave, I think eval might be what you're looking for: f = eval('len') length = f([1,2,3]) By the way, are you the Dave Ekhaus I used to work with at Kodak? -- Doug Schwarz dmschwarz&urgrad,rochester,edu Make obvious changes to get real email address. -- http://mail.python.org/mailman/listinfo/python-list