Re: [Tutor] Slightly OT - Python/Java
* Kent Johnson <[EMAIL PROTECTED]> [2005-01-09 20:27]: > Liam Clarke wrote: > >Hi all, > > > >I've been forcing myself to learn Java, and I was wondering if > >anyone's used Jython. For anyone in the Chicago, IL area, the Chicago Python Users Group, ChiPy, is going to have a speaker on Jython this Thursday, January 13th. For more information, check out the group site at: http://www.chipy.org Everyone is welcome, benginner to advanced. We love all kinds of input. You'd be surprised what you can learn when you get the chance to actually TALK to someone else ;-) -- David Rock [EMAIL PROTECTED] pgpZSSUvRuLbK.pgp Description: PGP signature ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python with MySQL ?
* Danny Yoo <[EMAIL PROTECTED]> [2005-01-11 10:55]: > > On Tue, 11 Jan 2005, Mark Kels wrote: > > > How can I send SQL querys to a MySQL database with a python-CGI program ? > > Hi Mark, > > You'll want to grab a "Python DB API" module for MySQL. The best one I've You might want to check out sqlobject, too http://sqlobject.org/ It gives you a relatively simple way to "objectify" SQL statements. -- David Rock [EMAIL PROTECTED] pgpRBRwPdqdc0.pgp Description: PGP signature ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A somewhat easier way to parse XML
* Max Noel <[EMAIL PROTECTED]> [2005-01-19 00:17]: > Hi everyone, > > I've just spent the last few hours learning how to use the DOM XML > API (to be more precise, the one that's in PyXML), instead of revising > for > my exams :p. My conclusion so far: it sucks (and so does SAX because I > can't see a way to use it for OOP or "recursive" XML trees). > I'm certain it can be used to do extremely powerful stuff, but as > far as usability is concerned, it's ridiculously verbose and naming is > inconsistent. I've had a look at Java DOM as well, and it's apparently > the same. I'm kind of in the same boat as you are and I have come to the conclusion that XML is intended to answer specific questions with discreet answers, not walk the DOM to create a dictionary. I _think_ the idea behind this is that it would be redundant. You already have a "dictionary" of sorts in the XML itself, why create a new one? For me, it seems that the way you are supposed to interact with an XML DOM is to already know what you are looking for, and in theory, you _should_ know ;-) Still, I can't help wishing I had a simple way to create a dict from a DOM. From a Python perspective, that seems more "Pythonic" to me as well. I guess it's just a different way of looking at it. -- David Rock [EMAIL PROTECTED] pgpq4Ua00eRSO.pgp Description: PGP signature ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A somewhat easier way to parse XML
* Max Noel <[EMAIL PROTECTED]> [2005-01-19 11:48]: > > On Jan 19, 2005, at 03:58, David Rock wrote: > > >For me, it seems that the way you are supposed to interact with an XML > >DOM is to already know what you are looking for, and in theory, you > >_should_ know ;-) > > Indeed. The problem is, even if I know what I'm looking for, the > problem remains that given the following document, > > > baz > > > If I want to get "baz", the command is (assuming a DOM object has > been created): > > doc.documentElement.getElementsByTagName("bar")[0].childNodes[0].nodeVal > ue > > Quoting from memory there, it may not be entirely correct. However, > the command has more characters than the document itself. Somehow I > feel it'd be a bit more elegant to use: > > doc["bar"] > > (or depending on the implementation, doc["foo"]["bar"]) > > Don't you think? Absolutely. That is exactly what I was hoping for, too. ElementTree comes close, but even that can be a bit unwieldy because of the multi-dimentional array you end up with. Still, if you know the data, doc[0][0] is a lot easier than doc.documentElement...nodeValue -- David Rock [EMAIL PROTECTED] pgp6q0sQrJqbe.pgp Description: PGP signature ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] newbie OSX module path question
* Mike Hall <[EMAIL PROTECTED]> [2005-02-14 18:22]: > Hm, so if I import glob, and then execute this line: > > print glob.glob('/Local_HD/Users/mike/Documents/pythonModules/*.py') > > I simply get brackets returned: > > [] > > > ...not sure what this means. Thanks again. It means it didn't find anything that matches that pattern, which suggests that the directory does not contain *.py files. That might be a problem. ;-) -- David Rock [EMAIL PROTECTED] pgpmTRknYUp8c.pgp Description: PGP signature ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reading from stdin
* Nick Lunt <[EMAIL PROTECTED]> [2005-03-01 22:23]: > On Tue, 2005-03-01 at 14:14 -0800, Sean Perry wrote: > > > > > unless you want the output for some other reason, a more idiomatic way > > is: > > > > for line in sys.stdin.readlines(): > > # handle the line > > > > I tend to use xreadlines() which does not read the entire input at once. > > For stdin this make sense, you have no idea how much data will be > > piped in. > > Thanks Sean, I agree with you on both accounts there. For another approach to this, I like to use the fileinput module. In the case of the original example of mimicing grep, it allows you to easily handle both a list of files passed to the command or use it as a pipe. The default action if there are no files given is to use stdin. http://www.python.org/doc/2.4/lib/module-fileinput.html -- David Rock [EMAIL PROTECTED] pgpi6ZajDHCbx.pgp Description: PGP signature ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] csv module not raising exception properly
I am trying to catch an exception from the csv module but it doesn't seem to be generating a proper exception because I don't seem to be able to catch it. Here is what I am doing: for inputline in fileinput.input(args): try: input = csv.reader([inputline], escapechar='\\') except: print "ERROR", inputline This is the traceback: Traceback (most recent call last): File "/usr/openv/local/bin/bpdbreport_test.py", line 539, in ? for line in input: _csv.Error: newline inside string Shouldn't I be able to catch this? The reason I'm doing it this way is because I have discovered a ctrl-M in the data I am parsing and the csv module bombs out on it. I needed to check each line individually. I thought I could do a try block around the csv.reader line and deal with the rare exception. Does anyone know why this try block doesn't catch the exception? The version of Python I am using is 2.3.3 Thanks. -- David Rock [EMAIL PROTECTED] pgprCjzYhfyU7.pgp Description: PGP signature ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] csv module not raising exception properly
* Kent Johnson <[EMAIL PROTECTED]> [2005-04-07 15:28]: > David Rock wrote: > >I am trying to catch an exception from the csv module but it doesn't > >seem to be generating a proper exception because I don't seem to be able > >to catch it. Here is what I am doing: > > > > > >for inputline in fileinput.input(args): > > try: > > input = csv.reader([inputline], escapechar='\\') > > except: > > print "ERROR", inputline > > > > > >This is the traceback: > >Traceback (most recent call last): > > File "/usr/openv/local/bin/bpdbreport_test.py", line 539, in ? > >for line in input: > >_csv.Error: newline inside string > > I'm suspicious of this - the traceback doesn't match the code you show. Is > your program called bpdbreport_test.py? What is happening at line 539 of > bpdbreport_test.py? Line 539 is the csv.reader line. I just boiled it down to the place where things don't make sense. I use try/except blocks all the time and I even tested this one by putting a "raise" statement inside the block and it picked it up, so it's not a scope issue or anything weird like that. I think the csv module doesn't raise an exception properly. Can someone verify that it works for them? I am going to continue testing with an extremely watered down version to see if it _ever_ works right. -- David Rock [EMAIL PROTECTED] pgpanrCj7ro4M.pgp Description: PGP signature ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] csv module not raising exception properly [SOLVED]
* David Rock <[EMAIL PROTECTED]> [2005-04-07 15:00]: > * Kent Johnson <[EMAIL PROTECTED]> [2005-04-07 15:28]: > > David Rock wrote: > > >I am trying to catch an exception from the csv module but it doesn't > > >seem to be generating a proper exception because I don't seem to be able > > >to catch it. Here is what I am doing: > > > > > > > > >for inputline in fileinput.input(args): > > > try: > > > input = csv.reader([inputline], escapechar='\\') > > > except: > > > print "ERROR", inputline > > > > > > > > >This is the traceback: > > >Traceback (most recent call last): > > > File "/usr/openv/local/bin/bpdbreport_test.py", line 539, in ? > > >for line in input: > > >_csv.Error: newline inside string > > > > I'm suspicious of this - the traceback doesn't match the code you show. Is > > your program called bpdbreport_test.py? What is happening at line 539 of > > bpdbreport_test.py? > > Line 539 is the csv.reader line. I just boiled it down to the place > where things don't make sense. I use try/except blocks all the time and > I even tested this one by putting a "raise" statement inside the block > and it picked it up, so it's not a scope issue or anything weird like > that. I think the csv module doesn't raise an exception properly. Can > someone verify that it works for them? > > I am going to continue testing with an extremely watered down version to > see if it _ever_ works right. Turns out the REAL problem is when you try and USE the reader object, NOT when you create it. The documantation was not clear on which operation would actually generate an error. The traceback actually alludes to this, in hindsight (Thanks Kent). The input = csv.reader() is fine. When you try to iterate over the object, THAT'S when it dies. -- David Rock [EMAIL PROTECTED] pgpu0OQPiEInu.pgp Description: PGP signature ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] getopt matching incorrect options
* Jay Loden <[EMAIL PROTECTED]> [2005-07-11 22:30]: > I have an app that takes a command line argument of -l or --list. It uses > the > getopt module to parse the arguments, and I just noticed that for some > reason, getopt is matching "--lis" or "--li" etc to "--list". (Code pasted in > below) > > Is this normal behavior, and if so, is there any way to avoid this? I just > want it to match "--list" to "--list", not "--l" and "--li" and "--lis" etc. This is normal. From getopt http://docs.python.org/lib/module-getopt.html Long options on the command line can be recognized so long as they provide a prefix of the option name that matches exactly one of the accepted options. For example, if long_options is ['foo', 'frob'], the option --fo will match as --foo, but --f will not match uniquely, so GetoptError will be raised. -- David Rock [EMAIL PROTECTED] pgpzJhOCWT42I.pgp Description: PGP signature ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Removing a file from a tar
* Adam A. Zajac <[EMAIL PROTECTED]> [2007-06-27 11:26]: > I was reading over the documentation for the tarfile module and it > occurred to me that there didn't seem to be a way to remove an > individual file from the tar. > > For example, suppose I did this: > > import tarfile > tar = tarfile.open("sample.tar", "w") > tar.add("unwanted") > tar.add("wanted") > tar.close() > > At this point, how could I come back and remove "unwanted" from the tar? Wel, it looks like tar's --remove-files is not supported yet, you would probably have to reopen the tarfile, write it to a new one file-by-file, excluding the ones you don't want. Messy :-( -- David Rock [EMAIL PROTECTED] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with plugins
* Ark <[EMAIL PROTECTED]> [2007-07-03 11:50]: > Hi! > First, my english may be bad, so I apoligize. > This is the first time i mail the list and it's about something i've been > investigating, but i haven't found enough information. > I want to learn how to do extensible aplications using plugins. I've found > some how tos an tutorials, but they're not deep enough for my needs, and i > need your help with documentation about the topic, or with everything you > consider helpful. I think we need some more information explaining what you are trying to accomplish. Can you supply an example of an "extensible application" and also a longer description of what you mean when you say "plugin." Perhaps some links to what you have looked at so far would also help to clarify? -- David Rock [EMAIL PROTECTED] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] odd
* elis aeris <[EMAIL PROTECTED]> [2007-07-19 08:51]: > I ran this > > > for x in range(5,10): >print x > > and OP was > > 5 > 6 > 7 > 8 > 9 > > why is that? shouldn't it print > > 5 > 6 > 7 > 8 > 9 > 10? That is the expected behaviour, per the documentation: http://docs.python.org/lib/built-in-funcs.html#l2h-58 -- David Rock [EMAIL PROTECTED] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Running Python on Gentoo
* Greg Lindstrom <[EMAIL PROTECTED]> [2007-07-26 13:44]: > Hello, > I am running python 2.4.2 on Gentoo Unix and am having problems running > programs. I have a script, hello.py as such: > > #! /usr/bin/python > print 'hello, world' > > that I save and add executable permission. Then at the prompt I type in.. > > $ ./hello.py > -bash: ./hello.py: /usr/bin/python: bad interpreter: Permission denied > > If I type > $ python hello.py > I get "hello, world" as expected. > > I was hoping that the "shabang" would have the script execute. Am I > missing something? Can you help me? BTW, when I type /usr/bin/python > at the prompt I get the python interpreter, so at least that's working. Are you using any hardened gentoo kernels or anything like that, or is it a "normal" gentoo build? I don't think this is a python problem, but rather a permissions problem at a level OTHER than the filesystem. I found this in the gentoo forums: http://forums.gentoo.org/viewtopic-t-549470-highlight-interpreter+permission+denied.html Are you using any "trusted path execution" in the kernel? This would potentially be something that could happen with ANY lniux system, not just gentoo. FWIW, I am having the same problem (even though I never actually tried on this system before) :-) -- David Rock [EMAIL PROTECTED] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Running Python on Gentoo
Just to follow up on what _my_ environment looks like (and the probable cause in my case, anyway) Security Options -> GRsecurity -> Executable Protections -> Trusted Path Execution (TPE) CONFIG_GRKERNSEC_TPE: If you say Y here, you will be able to choose a gid to add to the supplementary groups of users you want to mark as "untrusted." These users will not be able to execute any files that are not in root-owned directories writable only by root. If the sysctl option is enabled, a sysctl option with name "tpe" is created. Now I just need to find how to turn that off. I did want it more secure :-) -- David Rock [EMAIL PROTECTED] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] input/output redirection
* Lane, Frank L <[EMAIL PROTECTED]> [2005-09-08 09:49]: > Hi List, > > I wanted to take the stdout of a process and redirect it to stdin of a > python script, then after playing with the input in the script I want to > send it back to stdout (all of this to be done while the original > process runs happily along). I can't seem to figure out the correct > syntax if this is possible. > > e.g. > > C:\> runner.exe | script.py > C:\> runner.exe > script.py # this overwrites your script!:-) I use fileinput for most of my stdin text processing. It also give me the flexibility of using it as a pipe OR assigning a wordlist of files to the script instead. http://www.python.org/doc/2.4.1/lib/module-fileinput.html import fileinput for line in fileinput.input(): process(line) -- David Rock [EMAIL PROTECTED] pgp3RtUbUyLUC.pgp Description: PGP signature ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (no subject)
* jon freddy <[EMAIL PROTECTED]> [2005-09-13 13:37]: > I am new to Python, about 1 day. And I downloaded from > python.org Pythong2.4, it has the command line and > junk. But what actuall program compiles the source of > python into a program? Any of the programs included in > the package? And also, is Python capable of writing an > OS? Hi, Jon. Python is an interpreted language, your script is "compiled" at runtime by the main python executable, similar to perl. Your script maintains its textfile identity. So the simple form of running a script is: python myscript It _is_ possible to create a standalone binary, though. py2exe is a common application to build an executable with. Python is theoretically capable of being used to write an OS, but that is an exercise that is probably left to theory. There are a lot of good OS'es out there that would undoubtedly perform much better than a PythonOS ever could. That doesn't mean it wouldn't be cool, though. :-) -- David Rock [EMAIL PROTECTED] pgpbDnlqYILFN.pgp Description: PGP signature ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] problems with the shebang line and linux
* Adam <[EMAIL PROTECTED]> [2006-02-16 14:23]: > On 16/02/06, Brian van den Broek <[EMAIL PROTECTED]> wrote: > > It seems to me that that ^M is your problem although I'm not quite sure > where it came from there seems to be an extra character on the end of the > copied one. Here's a little test I did: > > #! /bin/py > print "What the hell!!" > > [EMAIL PROTECTED]:~$ ./test.py > -bash: ./test.py: /bin/py: bad interpreter: No such file or directory > and there doesn't seem to be any weird thing on the end even though that > file doesn't exist. I would verify that /bin/py is the actual location of your python interperter. That's a really weird location. > > I even retyped the testerlybar.py file, but I end up with the same > > results as when the small script was copied and pasted. > > > > Likewise, I got the same results after saving the two files to my Home > > directory on the hail mary thought that perhaps the fact I'd save the > > originals on a FAT32 mounted drive might be making things goofy. > > > > I'm stumped. Any steps I can take to work out what's going on? I have verified that ^M at the end _will_ break it. I also verified that having a space doesn't matter, either. Both work: #!/usr/bin/python #! /usr/bin/python When you retyped it, what editor did you use? When you cat the file: cat testerlybar.py What does the output look like? If you have xxd installed (you probably do): xxd testerlybar.py What does the output look like? This will help us see EXACTLY what's in the file. It will look something like this: [EMAIL PROTECTED] ~ $ xxd foo.py 000: 2321 202f 7573 722f 6269 6e2f 7079 7468 #! /usr/bin/pyth 010: 6f6e 0a70 7269 6e74 2022 4865 6c6c 6f22 on.print "Hello" 020: 0a . Bottom line, the error means bash can not find the application you told it to use, so something is wrong with the path you have in the file. -- David Rock [EMAIL PROTECTED] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] file?
* kakada <[EMAIL PROTECTED]> [2006-04-04 09:32]: > Hi all, > > How can we know that one specific file is already exist in filesystem? > for instance, I want to read zipfile by issuing code: > > import zipfile > ziparchive = zipfile.ZipFile(inputfilename, "r") > > if the inputfilename doesn't exist then an error would be occurred. > I want to catch up this special case first. The key here is to actually "catch" the exception. Python is very good at assuming something will work, and then deal only with the exceptions: import zipfile try: ziparchive = zipfile.ZipFile(inputfilename, "r") except: print "error accessing file" You could get fancy and deal with various exceptions or read traceback info, too. Using the try block is generally considered a more Pythonic way of handling the problem. :-) -- David Rock [EMAIL PROTECTED] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] for loops
* josip <[EMAIL PROTECTED]> [2006-04-11 09:13]: > I have problem with this question. > Can someone show me the code and than explain it? > > >>Write a Python program to print out the following shape. You are > expected to use two for loops (these must be nested) to solve this problem. > > output: > * * * * * > * * > * * > * * * * * That looks a lot like homework. If you have a specific question about a _part_ of code _you_ have written, we'll be glad to help out explaining those specifics. We generally try to stay away from doing the work for you :-) -- David Rock [EMAIL PROTECTED] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] School Boy Error
* John CORRY <[EMAIL PROTECTED]> [2006-04-15 23:48]: > Thanks Brian for the help on the last one. I couldn't see the wood for > the trees. I have a tougher one for you. > > I am reading in a CSV file. Each line represents a line that I want to > upload into my database. I am trying to upload the first line in the > file to get myself started. The code is below:- You may want to check out the csv module to aid in any odd data input, too. http://docs.python.org/lib/module-csv.html -- David Rock [EMAIL PROTECTED] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Beginner question(s)
* Ismael Garrido <[EMAIL PROTECTED]> [2006-06-18 19:34]: > Alan Gauld wrote: > >> Also, does anyone know of a PDA that would run python? > >> > > > > There was a project called pippy, but I haven't heard anything of it > > recently so I don't know if its still around or if it runs on modern > > PDAs - I think it was PalmOS anyhow... > > > > > > Pippy is quite dead. No development done recently. It supposedly runs > fine, but runs only Python 1.5. Last I used it, it worked fine, but it was limited. -- David Rock [EMAIL PROTECTED] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] <> and chomp
* William Allison <[EMAIL PROTECTED]> [2006-09-14 12:14]: > Hi, > I'm new to programming and started with Perl but have been reading a lot > of good things about Python. Thought I would switch before I have too > much time invested in Perl. > Anyway, my question is, is there something in Python similar to the > diamond operator and chomp from Perl? I'm trying to read in from a file > line by line and get rid of the '\n' at the end of each line. fileinput() is similar to <> http://docs.python.org/lib/module-fileinput.html rstrip() is similar to chomp http://docs.python.org/lib/string-methods.html#l2h-201 These aren't exact matches, but they are close. -- David Rock [EMAIL PROTECTED] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] getting 'pwd' for XP ?
* Dave S <[EMAIL PROTECTED]> [2006-09-28 16:10]: > I currently running XP (like a fish out of water :) and I need to know the > dir > that the python script is executed from. a linux 'pwd' How can I achieve > this - I have looked in sys & os & os.path but found nothing suitable os.getcwd() http://docs.python.org/lib/os-file-dir.html -- David Rock [EMAIL PROTECTED] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Equivalent to perl -e
* Chris Lasher <[EMAIL PROTECTED]> [2006-10-15 22:07]: > Haha! I'll relay that message! Thanks Kent and Glenn! > Here is one I actually use in real life. I needed something to figure out what the previous year, month, etc for rolling up old log files. The best thing I could think of for date calculation was datetime. This is embedded inside a shell script. python -c ' import time import datetime dtup_now = time.localtime() y,m,d = dtup_now[:3] d_today = datetime.datetime(y,m,d) d_delta = datetime.timedelta(d_today.day) last_month = d_today - d_delta d_delta = datetime.timedelta(last_month.day) two_month = last_month - datetime.timedelta(last_month.day) d_delta = datetime.timedelta(two_month.day) del_month = two_month - datetime.timedelta(two_month.day) print "%d %02d %d%02d" % (last_month.year, last_month.month, del_month.year, del_month.month)' What you will notice is it gets complicated in a hurry if you try to do loops or anything fancy because of formatting constraints. Not that it can't be done, but it would hurt to try. :-) -- David Rock [EMAIL PROTECTED] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Equivalent to perl -e
* Alan Gauld <[EMAIL PROTECTED]> [2006-10-16 17:32]: > > Why? > Why not just put it in a Python script? > I'm missing something I think. I don't think you are missing anything. It was something that just sort of happened one day. I was trying to do something fairly simple in a shell script and didn't have a good way to get the date info I wanted, so I started playing around with python -e. It really SHOULD just be a python script that calls shell stuff, not the other way 'round :-) Still, in the spirit of the OP, I thought it would be appropriate to share. -- David Rock [EMAIL PROTECTED] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] getopt module..
* Asrarahmed Kadri <[EMAIL PROTECTED]> [2006-10-22 20:19]: > Can somebody explain getopt function using a simple example.. > > Thanks.. This really does have a good example of usage http://docs.python.org/lib/module-getopt.html Essentially, you define options and arguments and what you expect to see from them, then the for o, a in opts: section is used to replace default values with information from the commandline. -- David Rock [EMAIL PROTECTED] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Has anyone tried matplotlib...??
* Matt Richardson <[EMAIL PROTECTED]> [2006-10-22 16:56]: > I just used it a couple of weeks ago to produce a histogram of > randomly generated numbers. Read the documentation, it's well written > and has good examples. I met the current maintainer at the chipy (Chicago Python user group) http://www.chipy.org meeting a few months ago. He's a great guy and he did some pretty impressive things with it. It also appears to interact well with ipython, an extremely powerful python interpreter shell (much better than the built-in shell) http://ipython.scipy.org/ -- David Rock [EMAIL PROTECTED] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] 'elp!!!!!!!1Totally Clueless Newbie In Distress
* Karl Wittgenstein <[EMAIL PROTECTED]> [2007-01-20 13:10]: > Ok,got the script working almost fine now...The only problem is that the > program window closes before we can get a glimpse of the answer...I use SPE > under WinXP, and have seen this problem in every script i try...This is the > script,as redone by a Smart Caring Dude on this list: It sounds like you need to run it from a command window. Running it the way you are isn't meant to leave a window up after the script is finished. Do Start->Run->cmd on XP to get a command window. python should already be in your path, so typing "python" at the propmt should result in it running the interpreter. If that works, exit the interpreter and type "python scriptname" That should run your script, and you will see the results in the command window because it won't close after the script is done. -- David Rock [EMAIL PROTECTED] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] largest palindrome number
* surya k [2011-08-27 20:51]: > > here, as the loop goes on, i*j can never become smaller in any case. > which is why I think it, as long as "PNum" gets a new number, its > bigger palindrome than the previous.. so, at the end of the loop. > we'll get largest palindrome number.. > > On 8/25/11, Hugo Arts wrote: > > > > When you get a new palindrome, you should make sure it's bigger than > > the one you already have before you replace the old one. 88 is the > > last palindrome you find, but it is not the the biggest. You cannot > > assume the biggest one will be found last. > > As implied by Hugo, What you need to to do is store your largest current palindrome and as you find a new one, replace the largest current only if the one you just found is actually larger. Once you go through the entire block, the value in your largest current value will actually be the largest palindrome. -- David Rock da...@graniteweb.com pgpqe98kqh5z1.pgp Description: PGP signature ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] PYTHONPATH (Mac OS X)
* Stayvoid [2011-12-30 16:11]: > >You don't have any option. > >You either type in the full path or you get the user to tell you > >in some way - either with a prompt or via an input argument. > > OK, now I get it. > > How can I tell this to the end-user? > Should I write a README file or what? > > I've tried to run lengthcounter_lutz from the file's folder and this worked > out. > cd /Users/Username/Python_modules/ > python /Users/Username/Python_modules/lengthcounter_lutz.py > ('Lines:', 12, 'Chars:', 285) > > > But I can't understand what's wrong with the second one: > def countLines(name): > file = open(name.__file__) > return len(file.readlines()) > > def countChars(name): > return len(open(name.__file__).read()) > > def test(name): > return "Lines:", countLines(name), "Chars:", countChars(name) > > if __name__ == '__main__': > import lengthcounter > print test(lengthcounter) > > >>> import lengthcounter > >>> lengthcounter.test(lengthcounter) > ('Lines:', 5, 'Chars:', 885) > Looking at page 1119 in the learning Python book, I might venture a guess as to where the difference lies. You are calling test as: test(lengthcounter), but that is not the name of a file (the name of a file should be in quotes). lengthcounter in this case is a variable, not a filename. The behavior in this case is probably undetermined. I suggest doing a manual check on the file named lengthcounter.pyc, and I'll bet you will find something closer to 5 lines and 885 characters. pyc files are the bytecode version of your file that gets generated automatically and is the code that is actually executed. Somehow, calling the method test inside the interpreter is different from running it on the commandline and you are picking up the pyc file. In either case, this format is iffy at best: if __name__ == '__main__': import lengthcounter print test(lengthcounter) should really be: if __name__ == '__main__': import lengthcounter print lengthcounter.test(lengthcounter) to avoid ambiguous behavior. -- David Rock da...@graniteweb.com pgpc2h7KXfB8z.pgp Description: PGP signature ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Which computer operating system is best for Python developers?
* Tamar Osher [2012-02-22 19:00]: > > Hi. I am still having trouble installing and using Python on my (new) > Windows 7 computer, but I plan to contact Microsoft forums and see if > they can help me, since this is a Windows problem and not a Python > problem. > > My question: For the future, what type of computer is best for Python > developers? Do all Python developers use some type of Unix computer? > I appreciate your feedback and look forward to hearing from you. > Thanks for your time. As always, the answer is "it depends." If you plan on doing Win32 python programming, it doesn't make sense to use anything other than a Windows system. It is usually easier if you can develop on a system that is similar to where your programs will run, but it is by no means a requirement. Your biggest challenge if developing on unlike systems, will be using methods that might be OS-specific (os.fork() comes to mind). As long as you keep things neutral, you shouldn't have huge issues. -- David Rock da...@graniteweb.com pgpOARLwWTZLn.pgp Description: PGP signature ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] creating dict of dict : similar to perl hash of hash
* Abhishek Pratap [2012-03-06 09:50]: > Hi Guys > > I am looking for a way to build dictionaries of dict in python. > > For example in perl I could do > > my $hash_ref = {}; > $hash->{$a}->{$b}->{$c} = "value"; > if (exists $hash->{$a}->{$b}->{$c} ){ print "found value"} > > Can I do something similar with dictionaries in Python. Absolutely. Python is very good at using nested dicts. dict = {} dict['a'] ={} dict['a']['b'] = {} dict['a']['b']['c']= "value" This is a bit brute force, but it illustrates that the intermediary keys need to exist. ie, if you try to assign directly, it won't work: Type "help", "copyright", "credits" or "license" for more information. >>> dict ={} >>> dict['a']['b']['c'] = 'value' Traceback (most recent call last): File "", line 1, in KeyError: 'a' Since the key 'a' doesn't exist, it throws an exception. Python is also more flexible than perl in nesting data because it doesn't have to be the same data type. You can nest variables, lists, dicts, etc all at the same level: dict = {} dict['mylist'] = [1,2,3] dict['mystring'] = 'string' dict['mynum'] = 4 dict['anotherdict'] = {} dict['anotherdict']['anotherstring'] = 'string2' -- David Rock da...@graniteweb.com pgp8ik0yrru5G.pgp Description: PGP signature ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] creating dict of dict : similar to perl hash of hash
* Thomas Maier [2012-03-07 00:38]: > Hi David, > Mixed data types in nested data structure are possible in Perl as well: > %hash = (); > $hash{'mylist'} = [1,2,3]; > $hash{'mystring'} = 'string'; > $hash{'mynum'} = 4; > $hash{'anotherhash'} = {}; > $hash{'anotherhash'}{'anotherstring'} = 'string2'; > > Thomas Hah. Fair enough :-) -- David Rock da...@graniteweb.com pgpszglXkVXly.pgp Description: PGP signature ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Simple text file processing using fileinput module. "Grabbing successive lines" failure
* Flynn, Stephen (L & P - IT) [2012-07-02 15:03]: > Tutors, > > Can someone explain to me how I am supposed to make use of readline() > to grab the next line of a text file please? It may be that I should > be using some other module, but chose fileinput as I was hoping to > make the little routine as generic as possible; able to spot short > lines in tab separated, comma separated, pipe separated, ^~~^ > separated and anything else which my clients feel like sending me. There are a couple issues that you need to resolve. For starters, there is no guarantee that the successive line is actually part of the preceding line. It could very well be that the original line is simply truncated, in which case trying to append the following line would be incorrect. What I typically do in a case like this is use a flag variable and pull the offending line(s). So, you need to first determine the best course of action for resolving the inconsistency (eg, how do you verify the following line belongs with the preceding)? Try checking the line, if it's less than 13 then flag and store in a buffer and continue. The following line _should_ also error, in which case, you can try to resolve the two lines, or fail out if the criteria isn't met. Essentially, your problem isn't with using fileinput, it's with how you handle each line that comes in. -- David Rock da...@graniteweb.com pgpsm5eZpm6mp.pgp Description: PGP signature ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Seeking help with reading and writing files in Python
* Aristotle [2012-06-26 14:28]: > > The sequence of events that I am using now is to open a program that > will gather gallons used from user, call a module to make calculations, > use the info from the module to write info to a file named > FinalProjectBill.txt. > > After that is done, I open another program that will read the info > written to FinalProjectBill.txt > > I guess my confusion about the instructions is, if I should read from > one file FinalProjectBill.txt first how does data get written to that > file to begin with? Based on this part, you have already answered your own question. Specifically, you get your input file, FinalProjectBill.txt, by collecting data from the user, doing some calculations, and outputting to the file. I'm not sure I see the problem. :-( -- David Rock da...@graniteweb.com pgpgnpfBiWpdl.pgp Description: PGP signature ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python and boot sequences
* Dave Wilder [2012-06-28 12:54]: > > Can a Python script be written that has the ability to stop a Linux > device in the middle of a boot when a certain sequence occurs and then > perform an action? > > For example, when I boot my switch (w/ Linux OS 2.7.3), I want to stop > the boot when I see a series of asterisks. When I see this, I need to > hit the <9> sequence. Then, I need to select a menu > option (e.g. 1 to run a test or Q to quit and continue w/ the boot). > Another example would be when doing a PXE boot, selecting the image to > load when prompted during the reboot. Probably not. The issue is that you are dealing with the bootstrap process of a system. Typically, this is not a place where any semblance of external user interaction exists. The examples you show represent compiled-in options that are more likely part of the initial ramdisk, BIOS-level code for a specific device, or something similar. The PXE boot menu example is usually something that's being presented by an external server (via cobbler, or a similar product). There isn't an OS at that point that would likely be able to supply a python environment to use. I think we would need to better understand exactly what you are trying to build, but you are probably looking for something that would be a much lower level than python. -- David Rock da...@graniteweb.com pgp7NxdORAGka.pgp Description: PGP signature ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] confusion about imports
* Chris Hare [2012-07-09 13:33]: > import functions > import os > import db > > when everything was all in one file, that worked just fine. Now, with it all > split up, once I changed > > r = DbPath() > > to > > r = functions.DbPath() > > things seems to work now. I hope this is it!!! > Yes, that's it. As mentioned elsewhere, you have to reference the module name in order to let python know _which_ one you want. For example, you could have the same DbPath() method in two different modules: module1 and module2, so you need to be able to differentiate. module1.DbPath() is not the same thing as module2.DbPath() Your functions.DbPath() is the way to go. -- David Rock da...@graniteweb.com pgpstgBsNVZmH.pgp Description: PGP signature ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] starting to learn
* blindmaildrop [2012-07-11 16:46]: > Hello! > > I am just starting to learn python, having signed up for a class on it in > University. The last time I programmed anything was in the long long long > ago of BASIC and (well since I spent time doing other things) I missed the > development boat. > > So starting from scratch, how-to? Coming here is a good start. Welcome! Start here for beginning ideas: http://wiki.python.org/moin/BeginnersGuide You will find a number of good jumping-off points under the "Learning Python" section. Come back as you hit things. :-) -- David Rock da...@graniteweb.com pgpXxeijIY9Gq.pgp Description: PGP signature ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Confusion regarding the 'from' statement
* Mazhar Hussain [2012-08-14 23:24]: > the module object with the del statement. However what happens if I > try to import a name using 'from' that references a name in the > imported module that itself is not imported. Consider the following > example,here there are two modules mod1.py and mod2.py, > > #mod1.py > from mod2 import test > test('mod1.py') > > #mod2.py > def countLines(name): > print len(open(name).readlines()) > > def countChars(name): > print len(open(name).read()) > > def test(name): > print 'loading...' > countLines(name) > countChars(name) > print '-'*10 Loosely speaking, it does import the other methods. In order to successfully import test(), it has to resolve countLines() and countChars(). They won't be directly accessible, as they don't exist in the namespace, but test() knows about them. You are reading too much into the comment that the module is "deleted". -- David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What are all those letters after terminal commands?
* Cecilia Chavana-Bryant [2012-08-23 14:18]: > mkdir -p i/like/icecream. I am guessing that the -p stands for directory > path? I have seen other such letters sometimes with or without the ' - ' > before them (I think) in commands so my question is, what are these letters > for? what are they called? and could someone please point me to where I can They are called commandline options. Most programs allow you to use options to change the behavior of the program "on the fly." In this particular case, mkdir creates a directory, while mkdir -p means "make the directory and any parent directories that do not already exist. For example: If i/like/icecream does not exist, we try to create it with mkdir: mkdir i/like/icecream The result will be an error if i or i/like does not exist yet: mkdir: i/like: No such file or directory So we use -p, to also create the parent directories: mkdir -p i/like/icecream To learn about options that are available for a given command, try using the "man" command like so: man mkdir It will give you a list of options, what they do, and how to use them. In general, there are two things you can use on a commandline, options and arguments. Options are the switches that change the program's behavior and arguments are the inputs to the program (filenames, etc). -- David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to split/partition a string on keywords?
* Jared Nielsen [2012-08-23 12:05]: > Hi all, > I'm new to programming and Python. > I want to write a script that takes a string input and breaks the string at > keywords then outputs the pieces on separate lines. > But split() doesn't retain the separator and partition() retains the white > space and returns a 3-tuple which I'll have to figure out how to rejoin nor > does it partition on subsequent instances of the separator. While it's true that split() doesn't retain the separator, you still know what the separator is, right? Why not do something like: text = raw_input("Enter text: ") sep = 'and' parts = text.split(sep) for i in parts[:-1]: print i print sep print [-1] You might also want to consider stripping whitespace in the individual list items, too. -- David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to split/partition a string on keywords?
* David Rock [2012-08-23 15:03]: > * Jared Nielsen [2012-08-23 12:05]: > > Hi all, > > I'm new to programming and Python. > > I want to write a script that takes a string input and breaks the string at > > keywords then outputs the pieces on separate lines. > > > But split() doesn't retain the separator and partition() retains the white > > space and returns a 3-tuple which I'll have to figure out how to rejoin nor > > does it partition on subsequent instances of the separator. > > While it's true that split() doesn't retain the separator, you still > know what the separator is, right? Why not do something like: > > text = raw_input("Enter text: ") > sep = 'and' > parts = text.split(sep) > for i in parts[:-1]: > print i > print sep > print [-1] Oops, print [-1] should have been print parts[-1] Hopefully you get the idea, though. -- David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to split/partition a string on keywords?
* eryksun [2012-08-23 17:02]: > On Thu, Aug 23, 2012 at 3:05 PM, Jared Nielsen > wrote: > > Hi all, > > I'm new to programming and Python. > > I want to write a script that takes a string input and breaks the string at > > keywords then outputs the pieces on separate lines. > > This is just for printing? You can use replace(): > > >>> text = "Ham and cheese omelette with hasbrowns and coffee." > >>> print text.replace(" and ", "\nand\n") > Ham > and > cheese omelette with hasbrowns > and > coffee. I like that :-) If you aren't just printing, and want to use partition you will need to do some recursion (I assume that's the expected use case for partition). def repart(text): parts = text.partition('and') if parts[0] == text: return (parts[0],) else: return parts[:-1] + repart(parts[-1]) if __name__ == '__main__': text = "Ham and cheese omelette with hasbrowns and coffee." parts = repart(text) for part in parts: print part.strip() # Clean up whitespace when printing. -- David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reading lines from a list of files
* Alex Kleider [2015-05-12 02:33]: > On 2015-05-11 23:48, Peter Otten wrote: > > Alex Kleider wrote: > > > >> Is there a better (more 'Pythonic') way to do the following? > >> > >> for f_name in f_names: > >> with open(f_name, 'r') as f: > >> for line in f: > > > > There's the fileinput module > > > > <https://docs.python.org/dev/library/fileinput.html#fileinput.input> > > > > but personally I prefer the way you show above. > > Then I'll stick with what you prefer and what I know. > It seems silly to import yet another module for the sole > purpose of saving one line of code although the reason > for my inquiry was more to diminish levels of indentation > than number of lines. > Thanks, > Alex Personally, *I* prefer fileinput as my go-to file reader. Don't knock fileinput for "saving one line." It does a lot more than that. It allows your script to manage the filelist as an input, automatically handles stdin so your script can easily be both a filter in a pipeline and a file reader, plus a host of other useful methods for info about the file you are reading. Part of what you really need to define is the context of your question of "better." What is your use case? From where is your list of files coming? Is it truly just "read and forget"? Your needs will dictate what option is "best." It may be what you've already done yourself, it may be fileinput, or it may be something completely different. -- David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Pep 8, about indentation
* Alex Kleider [2015-08-07 21:50]: > > Here is what I've got in my ~/.vimrc file: > set autoindent > set shiftwidth=4 > set expandtab > set textwidth=72 > set scrolljump=2 > set scrolloff=2 > > I'll add > set tabstop=4 You might want to add softtabstop as well. set softtabstop=4 It's very handy for allowing the delete key to go back TAB number of spaces (ie, deletes those 4 spaces you just inserted). -- David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Pep 8, about indentation
* Alex Kleider [2015-08-10 11:26]: > On 2015-08-10 08:33, David Rock wrote: > > > You might want to add softtabstop as well. > > set softtabstop=4 > > > > It's very handy for allowing the delete key to go back TAB number of > > spaces (ie, deletes those 4 spaces you just inserted). > > I got it working but the key needs to be the 'backspace' key, not the > 'delete' key. > Either way, very handy (replacing the need to use CTRL-D.) Yeah, BS is more accurate (although BS says Delete on my keyboard). Gotta love consistency :-) -- David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to grep a word and make a dictionary from multiple lines.
* Fosiul Alam [2016-01-04 22:29]: > Hi Expert, > I am learning python to do some system admin code, i am still in the > process of learning but I need a help on bellow code in urgent, i will be > really greatfull for any help > > Basically i wanted like this :- > > grep a line which has 1:0:0:129 , and get the LUN number(i.e > 360060165656565634348a739e511) for this path > > so the Dictionalry will be : > > dict = {'360060165656565634348a739e511': '1:0:0:129', > '3600601323h42h2k323asdf33511': 1:0:2:98}; > > > How can i do this ? based on your multipath output, one thing you have to take into account is that the LUN value comes before the SCSI value. You are going to have to walk the file and for each mpath line, create a dict, then add your SCSI values to that entry. You will have to find a way to break out of your logic when the next mpath is seen. You will also want to think about what to do with all your LUNs. You have four per mpath, not one. Do you want to capture only one, or do you need all of them? -- David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to grep a word and make a dictionary from multiple lines.
* Fosiul Alam [2016-01-05 09:46]: > Hi > so the logic will be like bellow :- > > a)Start to read the file, > b)start a line which start with "3600601" > c) Iterate through the line till i see another line which starts with > "3600601" > d) read the last line before 3600601 > e)cut all the path and create a dictionary which will have one key (LUN ID > 3600601 ) and multiple values (PATH > *0:0:0:129,**1:0:0:129,*0:0:2:129,1:0:2:129) > > f) then look up each dictinary by Values(*0:0:0:129) * to get the required > LUN ID > > does the logic sound right ? > > mpathdz (360060165656565634348a739e511) dm-134 DGC,VRAID > size=200G features='0' hwhandler='1 alua' wp=rw > |*-+- policy='round-robin 0' prio=130 status=active > *|* |- 0:0:0:129 sddz 128:16 active ready running > *|* `- 1:0:0:129 sdwd 69:656 active ready running > *`-+- policy='round-robin 0' prio=10 status=enabled > |- 0:0:2:129 sdnd 70:496 active ready running > `- 1:0:2:129 sdafg 68:864 active ready running > mpathcu (3600601323h42h2k323asdf33511) dm-103 DGC,VRAID > size=200G features='0' hwhandler='1 alua' wp=rw > |*-+- policy='round-robin 0' prio=130 status=active > *|* |- 1:0:2:98 sdaeb 66:880 active ready running > *|* `- 0:0:2:98 sdly 69:256 active ready running > *`-+- policy='round-robin 0' prio=10 status=enabled > |- 0:0:0:98 sdcu 70:32active ready running > `- 1:0:0:98 sduy 67:672 active ready running > mpathbp (36003434343eere8b69e411) dm-36 DGC,RAID 5 > size=100G features='0' hwhandler='1 alua' wp=rw > |*-+- policy='round-robin 0' prio=130 status=active > *|* |- 0:0:0:68 sdbq 68:64active ready running > *|* `- 1:0:0:68 sdtu 65:704 active ready running > *`-+- policy='round-robin 0' prio=10 status=enabled > |- 0:0:2:68 sdku 67:288 active ready running > `- 1:0:2:68 sdacx 8:912active ready running If that's what you need, then that would probably work (more or less). A few issues to make sure you address: 1. not all multipath entries start with "3600601". mpathbp, for example, is "3600343". You would probably be better off looking for "mpath" 2. looking up by value would work, but maybe you should do it the other direction. Your SCSI values will be unique, so use that as the key a "simpler" logic is probably: a) read file b) store the LUN value from your mpath line c) iterate over lines and find SCSI key, then apply the LUN as the value for the key d) when you hit a new mpath line, simply update your LUN value and keep going Then you can look up your LUN by SCSI key directly. -- David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] PLEASE I NEED HELP URGENTLY
* precious akams via Tutor [2016-01-09 19:54]: > PLEASE I NEED A LITTLE HELP . > I can figure out what Iam missing in this project > > Create a class called BankAccount > .Create a constructor that takes in an integer and assigns this to a > `balance` property. > .Create a method called `deposit` that takes in cash deposit amount and > updates the balance accordingly. > .Create a method called `withdraw` that takes in cash withdrawal amount and > updates the balance accordingly. if amount is greater than balance return > `"invalid transaction"` > .Create a subclass MinimumBalanceAccount of the BankAccount class > > THIS IS MY SOLUTION > > class BankAccount: > def_init_(self, initial_amount): > self.balance=initial_amount > > def deposit (self, amount): > self.balance+=amount > > def withdraw (self, amount): > if self.balance>=amount: > return ('invalid transaction') > > class MinimumBalanceAccount(BankAccount): > def _init_(self): > BankAccount_init_(self) > > THIS IS THE ERROR MESSAGE I GOT > > Internal Error: runTests aborted: TestOutcomeEvent(handled=False, test=, > result=, outcome='error', exc_info=(, TypeError('this constructor takes no > arguments',), ), reason=None, expected=False, shortLabel=None, > longLabel=None) is not JSON serializable This doesn't appear to be all of your code. What's the code you are running that actually generates the traceback? -- David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Recommendations for best tool to write/run Python :p:
* Alan Gauld [2016-03-03 11:02]: > On 03/03/16 09:31, Thomas C. Hicks wrote: > > On 03/03/2016 02:26 AM, Lisa Hasler Waters wrote: > >> Could you please recommend the best Python tools for writing and running > >> our code for the long term? Also, we are hoping to find free tools! > >> > > Most people on this list are a lot smarter than me so there are probably > > good reasons for it but I have used Ipython (now Jupyter) for teaching > > my kids programming in middle and high school. > > IPython is great as an interactive environment but the OP > specifically mentioned writing longer programs and editing > files which is not what IPython does best. I suspect that's > why it didn't get a mention earlier. Very likely, but it's definitely worth mentioning as a runtime environment. It's a big step above the basic built-in CLI -- David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Changing the interpreter prompt symbol from ">>>" to ???
* boB Stepp [2016-03-12 00:46]: > > So let's see if this copies and pastes into a plain text Gmail and is > visible to "many environments": > > Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:54:25) [MSC v.1900 > 64 bit (AMD64)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > Active code page: 65001 > ► print("Can everyone read the prompt?") > Can everyone read the prompt? > ► > > It looks good to me in Gmail. Any issues? Angry users of pure ASCII > terminals? ~(:>) I'm using mutt in a screen session on raspbian. Looks fine to me. I have put a lot of effort into "properly" displaying "weird" things, though. -- David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Study Tips
* Alan Gauld via Tutor [2016-05-30 22:11]: > On 30/05/16 06:45, Steve Lett wrote: > > write code., lots of it. > > Don't just settle for the examples/exercises in your book. > Use them as a start but extend them. Add extra features. > Change the output format or the sort order. > Combine examples to make bigger programs. > > Writing code means making mistakes and, in finding the solution, > you learn far more than from just reading code. And a corollary to this: have a purpose for why you are writing it. Learning code for the sake of learning it will get old quickly. You will get a lot further if you are trying to solve a problem that you care about. Think of something you would like to automate, or calculate, or process. Do you have data you would like to analyze? As you learn different elements and apply them to a practical use that does something for you, it will be more satisfying and more likely to stick in your brain. -- David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] OT: Recommendations for a Linux distribution to dual-boot with Win7-64 bit
Here’s my take on a lot of this (it’s similar to what’s been said already, so this is more of a general philosophy of distros). There are basically three types of distros (you can subdivide 100 ways, but these are the primary categories) 1. slower-moving, very stable, binary installs 2. fast-moving, stable-ish, binary installs 3. fast-moving, stable-ish, source installs In a relative sense, linux stability is good regardless. I only point out “very stable” because they are typically bulletproof on purpose, at the expense of some flexibility. #1 examples: Debian stable (codename jessie) Red Hat Enterprise Linux (RHEL) CentOS (a free RHEL repackaging) The primary issue with these slow-moving binary distros is they are stable by not introducing new things quickly, so the versions of software available in their software repositories are sometimes ancient. That’s not to say you can’t install something newer, but it won’t be “standard.” If you are looking for latest and greatest, these might not be for you, but they are good for what they do. I support RHEL servers as my day job, but use debian at home. Since debian recently changed it’s stable branch, it does contain many “reasonably new” versions of most software compared to RHEL, but you won’t see fast adoption of new stuff moving forward (besides security updates). #2 examples: debian testing (codename stretch) Fedora (this is where things get tested before they go into RHEL) Ubuntu (based on debian) Pros with #2: "latest and greatest” available in the official repositories Cons: "latest and greatest” available in the official repositories It’s a double-edged sword. The closer you get to the bleeding edge, the higher the risk of something being “not quite right” but you are much more likely to find newer versions of software. It’s also worth noting; don’t let the “testing” in debian testing scare you, it’s still a very stable distro. #3 examples: gentoo linux from scratch (LFS) These are interesting in that all code is built from source, rather than installed as binary packages. In the case of gentoo, that’s not really a problem, though. The package management tools take care of the work for you, it just means it takes longer to install a given package if your system is slower at compiling. LFS is not one I would recommend unless you really want to learn how to build a linux system _literally_ from scratch. I have also run gentoo at home for years, with very few issues, but it’s an example of getting closer to the bleeding edge. Another class of linux distribution you may want to consider is anything with a “LiveCD.” These are full distributions designed to run off a bootable CD/DVD/UBS stick. There are LiveCD versions for several of the distributions out there and they may give you a better feel for what user experience you want before taking the plunge. They don’t install to your hard drive at all (although some have an option to if you wish later) and give you an easy look at how they work. I know you didn’t want to run linux in a VM, but I highly suggest that you _do_ for a while first. Again, that is an easy way to try out several distros and decide what you like _before_ committing to a dual-boot. It’s a lot easier to handle the dual-boot once you know which one you want to try. Going back later and switching to a different distro gets sticky. Based on what you’ve listed as requirements, debian is probably a solid choice (either stable; or testing if stable doesn’t have what you need). Since this is a Python mailing list, the current pythons available in stable are 2.7.9 and 3.4.2, which should give you a good indicator if that will suit your needs (i.e., if they are “new enough” for you). testing is 2.7.11 and 3.5.1. It’s also worth noting that debian does allow you to run stable, and cherry-pick packages from testing; that’s a little advanced (but something to keep in mind). — David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] OT: Recommendations for a Linux distribution to dual-boot with Win7-64 bit
> On Jun 28, 2016, at 12:49, boB Stepp wrote: > > I forgot one concern last night: > > 11) My current graphics adapter is made by NVIDIA. Their drivers are > proprietary. Is this going to be a deal breaker for Linux? Typically, no. At a minimum, you will still have native support for basic GUI display. There are also nvidia-supplied drivers available that can be used, but they are typically needed only for advanced 3D acceleration (if at all). My 15-year old laptop had an Nvidia Geforce 2 Go card and it was fine. > 12) And what about wireless networking? My ASUS motherboard has > builtin wireless, but the software used to manage its settings may be > (I cannot remember for certain.) Windows-only. Will this be an issue? Again, not likely a problem. Most hardware nowadays is reasonably well supported, although some advanced features may not be. The easiest thing to do is google for your distro name and the brand of device and see if there are any issues. If you follow my earlier advice on trying a liveCD of your chosen distro first, that will give you a really good idea if your hardware will work. — David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] OT: Recommendations for a Linux distribution to dual-boot with Win7-64 bit
> On Jun 28, 2016, at 18:16, boB Stepp wrote: > > On Mon, Jun 27, 2016 at 10:48 PM, Steven D'Aprano wrote: >> >> >> What about running Win7 in a virtual machine? > > What type of performance hit will I take when running CPU intensive > processes? I don't yet have any real experiences with running virtual > machines. Ultimately, not likely to be all that much. The bigger constraint with running VMs is often available ram. >> >> Otherwise, I like: >> >> Linux Mint. Good software repositories, more conservative than Ubuntu, >> not as stick-in-the-mud as Debian. Based on Debian/Ubuntu so the quality >> is good, mostly aimed at non-hard core Linux geeks. > > Alan obviously likes this distro. And my teacher wife at the > beginning of this summer break switched several of her class PCs to > Mint. Be nice to be writing software for the same environment, so > this might be a positive here. That’s as good a reason as any. :-) As I’m sure you have gathered by now, picking a distro is a lot like picking a brand of car. *Linux* underneath is largely similar across all the distros, what you are picking is the wrapper around it. It’s more about the package manager used, and the philosophy of the maintainers than anything. The only logical option is throw a dart and just try one. If you don’t like how they do things, throw another dart until you find what you like. This is the blessing and the curse of linux; endless variety. Regarding the package management, there are basically two models: RPM-based and dpkg-based (yes, there are others, but these are the two big players). RPM-based (often referred to as yum) is anything similar to Red Hat (fedora, CentOS, etc), dpkg-based (sometimes referred to as apt) is anything based on debian (ubuntu, mint, etc). How they work is fundamentally different, but any distro that uses the same package management will largely “feel” like any other. If you value Alan’s opinion (and arguably, your wife’s is more important), try out Mint. You may or may not like it, but you won’t know until you try. I still say a dry run in a VM to get a feel for it would do wonders for you regardless. — David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] OT: Recommendations for a Linux distribution to dual-boot with Win7-64 bit
> On Jun 29, 2016, at 11:20, boB Stepp wrote: > > My Christmas present of a Corsair mechanical gaming keyboard was not > _seen_ during the boot up sequence until *after* Windows started up. > So I could not get into my BIOS area! I had not noticed this earlier Which keyboard do you have? Most Corsairs have a “BIOS switch” for exactly this issue. — David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] OT: Recommendations for a Linux distribution to dual-boot with Win7-64 bit
> On Jun 29, 2016, at 12:32, boB Stepp wrote: > > On Wed, Jun 29, 2016 at 12:02 PM, David Rock wrote: >> >>> On Jun 29, 2016, at 11:20, boB Stepp wrote: >>> >>> My Christmas present of a Corsair mechanical gaming keyboard was not >>> _seen_ during the boot up sequence until *after* Windows started up. >>> So I could not get into my BIOS area! I had not noticed this earlier >> >> Which keyboard do you have? Most Corsairs have a “BIOS switch” for exactly >> this issue. > > K95 RGB. I will have to look around for setting you mention. It should be a physical switch on the keyboard itself — David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] OT: Recommendations for a Linux distribution to dual-boot with Win7-64 bit
> On Jun 29, 2016, at 17:16, boB Stepp wrote: > OK, I'm into a live Mint Linux session off my USB flash drive. The Cool. > I typed both "python" and "python3" in the terminal window to see what > is here: Python 2.7.6 and Python 3.4.3 [Does this mean we are *on* > topic now? ~(:>))]. Question: Is Python 3 used by any of Mint's OS > functions? Or does it only use Python 2? I don’t know off-hand, but unless you plan on doing work with Mint itself, I doubt it matters much beyond the academia of knowing for knowledge’s sake. Are you concerned about a version conflict with something you plan to do on the system? We are definitely getting back on topic if you want to talk about different versions of python and whether it’s better to just work with what’s there or install something different. > No Git is pre-installed, but it immediately tells me the command to > type to get it! Cool!! If I may suggest… GitKraken is pretty nice. https://www.gitkraken.com I’m not a fan of Git, but it makes it tolerable even for a stodgy SysAdmin like myself ;-) > Now when the new hard drive arrives tomorrow we'll see if I can get a > good dual-boot of Windows 7 and Mint Cinnamon going! Having the second disk will make this a breeze. You are avoiding the biggest complication of resizing partitions on the same disk. The one suggestion I would make about the install: when it asks if you want to use LVM, say yes. It adds a layer of flexibility with you disk layout that you will be sad you don’t have later. > Thanks for all of the help even though this has been off-topic for this list! > > Meanwhile, more playing around with Mint!! have fun! — David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] OT: Recommendations for a Linux distribution to dual-boot with Win7-64 bit
> On Jun 29, 2016, at 20:16, boB Stepp wrote: > > > The interesting part is since IDLE needs tkinter, it installed that > dependency as well. As far as I can tell after typing "help(tkinter)" > in the Python interpreter, it looks like *all* of tkinter got > installed. Is this in fact true? Most likely, yes. Welcome to package management. This is what we were talking about earlier; the package management tools are really good and do wonderful things like find all the needed dependencies for a package that you install. In some cases, that can be many-many packages depending on the complexity. All you need to worry about is the thing you want, and let the system do the rest. :-) — David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Regex/Raw String confusion
> On Aug 3, 2016, at 20:54, Jim Byrnes wrote: > > Is the second example a special case? > > phoneNumRegex = re.compile(r'(\(\d\d\d\)) (\d\d\d-\d\d\d\d)') > mo = phoneNumRegex.search('My phone number is: (415) 555-4242.') > print(mo.group(1)) > print() > print(mo.group(2)) > > I ask because it produces the same results with or without the ' r '. No, it’s not a special case. The backslashes in this case are a way to simplify what could otherwise be very unwieldy. There are several of these character groups (called special sequences in the documentation). For example, \s means any whitespace character, \w means any alphanumeric or underscore, \d means any digit, etc. You can look them up in the docs: https://docs.python.org/2/library/re.html — David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Downloading Slack Files
> On Aug 16, 2016, at 15:25, Malcolm Boone wrote: > > if __name__ == '__main__': >while 1: >files_list_url = 'https://slack.com/api/files.list' >date = str(calendar.timegm((datetime.now() + timedelta(-30)) >.utctimetuple())) >data = {"token": _token, "ts_to": date} >response = requests.post(files_list_url, data = data) >if len(response.json()["files"]) == 0: >break >for f in response.json()["files"]: >print ("Downloading file" + f["name"] + "...") >timestamp = str(calendar.timegm(datetime.now().utctimetuple())) >urllib.urlretrieve = "https://"; + _domain + ". > slack.com/api/files.list" + timestamp >requests.post(urllib.urlretrieve, data = { >"token": _token, >"file": f["id"], >"set_active": "true", >"_attempts": "1"}) >print ("DONE!") > > > The other issue, is that the script never ends (probably a simple solution, > but again I'm pretty new to this). It keeps printing the list of file names > over and over until I manually close out of Python. I’m not sure about the downloading part, but the reason it never stops is because this test is never true: >if len(response.json()["files"]) == 0: >break Since you are downloading and not removing anything, there’s always going to be files so you will never break out of the while loop. I think you need to get the list of files first, outside of the loop, then loop over that list to download. — David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] syntax error help
> On Mar 30, 2016, at 13:05, Awais Mamoon wrote: > > Hi my code should be working however keeps coming up with invalid syntax but > I know there isn’t one. Please help me its been 2 hours > When you run your code, what is the actual error you get (copy and paste the entire thing, please)? Where does it say the syntax error is? — David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Basic telnet question
> On Sep 24, 2016, at 04:21, Phil wrote: > > The problem is that the client is not responding, certainly not as expected. > There aren't any Python errors either, however, the console is blocked until > the client is disabled. If I then attempt a connection with the disabled > client a Python connection refused error is displayed, as I would expect. > > I have read the telnetlib document and searched for examples but I seem to be > stuck on a very basic problem. > > By the way, I'm using Python 3.5 under Linux. when you say "the client is not responding, certainly not as expected”, what, exactly, is the output you get? read_all is a bit touchy, and it’s a blocking operation. the blocking part is likely why the console is blocked. read_all doesn’t know it should give things back to you just because you don’t see any new data; it’s still trying to read everything until it times out. either add a short timeout value to your telnetlib.Telnet(), or try a different read method; for example, read_very_eager you could also try using telnetlib.set_debuglevel() to try and get more details about what’s actually happening. — David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Basic telnet question
> On Sep 24, 2016, at 15:49, Phil wrote: > > On 25/09/16 01:01, David Rock wrote: >> >> when you say "the client is not responding, certainly not as expected”, >> what, exactly, is the output you get? >> > > In my dazed state I think I responded to David personally instead of the > list, my apologies. :-) > Thank you for your reply David. > > This is what I expect: > > Trying 127.0.0.1... > Connected to localhost. > Escape character is '^]'. > > But, as I say, the console is blocked and nothing is returned. > > I'll try the debug method that you suggested. So you are expecting to read until the header stanza is complete, then send a command and presumably get the results of the command. The problem is read_all() doesn’t work the way you think it does. See what happens with your current code if you send ctrl+], it will probably print as expected, but also close the connection. I don’t think read_all is the right function for the task you are trying to perform. You are putting it inside a print statement print(tn.read_all()) but that’s never going to print anything or return control because read_all will never finish (and never return to the print call). read_all() is a blocking operation that’s going to sit there and keep trying to read data until it’s told to stop (EOF), or until the connection times out. What you probably mean to do is use read_until(). You know what you are expecting, so try to catch it with something like: header = tn.read_until("character is '^]’.”, timeout=5) print(header) tn.write("f" + "\n”) etc read_until looks for a specific string and returns when it finds it, giving control back to you. — David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Basic telnet question solved
> On Sep 24, 2016, at 18:59, Phil wrote: > > On 25/09/16 07:17, David Rock wrote: >> header = tn.read_until("character is '^]’.”, timeout=5) >> print(header) > > Thank you David, read_until() led me to a result. It seems that the telnetlib > doesn't emulate the console telnet command exactly, so I didn't get the > connection response that I had expected. However, if I send a command to the > client and use read_until() then I do get the result from the command that I > expected. > > Thanks again, I was on the verge of giving this idea away. Glad it worked for you :-) — David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] formatting xml (again)
* richard kappler [2016-12-27 14:44]: > > I have tried to feed this raw into our other app (Splunk) and the app reads > each line (gedit numbered line) as an event. I want everything in between > each stx and etx to be one event. > > I have tried: > > # > with open("original.log", 'r') as f1: > with open("new.log", 'a') as f2: > for line in f1: > line2 = line.replace("\n", "") > f2.write(line2) > ## > > Now this obviously doesn't work because, as stated above, each tag and > datum in the example above from lines 2 to 7 is on a different line, so > python is doing exactly as I tell it, it's stripping the \n and then > printing the line, but not concatenating everything between stx and etx on > one line, which is what I want it to do. > > What I'm trying to do is collapse the 'expanded lines' between stx and etx > to one line, but I just can't wrap my head around how to do it. Or to put, > and do, it another way, how do I read each line from the original file, but > write it to another file so that everything from stx to etx, including stx > and etx, are on one line in the file? Concatinate all your lines into a single output variable first, then write that to your log Pseudocode (ie, this won't run), but this should give you the idea (defining the parts to loop will be the challenge you will have to define for yourself). with open("original.log", 'r') as f1: with open("new.log", 'a') as f2: output = "" for line in f1: if between [x02] and [x03]: output =+ line.strip() else: f2.write(output) output = "" Basically, you need to loop over everything between your markers and put them in a single entry, then send that one entry all at once instead of piecemeal. I can come up with something a little more complete if you still need more help. -- David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] formatting xml (again)
* richard kappler [2016-12-27 15:39]: > I was actually working somewhat in that direction while I waited. I had in > mind to use something along the lines of: > > > stx = '\x02' > etx = '\x03' > line1 = "" > > with open('original.log', 'r') as f1: >with open('new.log', 'w') as f2: > for line in f1: > if stx in line: > line1 = line1 + line > if not stx in line: > if not etx in line: > line1 = line1 + line > if etx in line: > line1 = line1 + line + '\n' > f2.write(line1) > line1 = "" > > > but that didn't work. It neither broke each line on etx (multiple events > with stx and etx on one line) nor did it concatenate the multi-line events. A big part of the challenge sounds like it's inconsistent data formatting. You are going to have to identify some way to reliably check for the beginning/end of your data for it to work. Do you know if you will always have \x02 at the start of a section of input, for example? The way I usually do log parsing in that case is use the stx as a flag to start doing other things (ie, if I find stx, stuff lines until I see the next stx, then dump and continue). If you have intermediary data that is not between your stx and etx (comment lines, other data that you don't want), then it gets a lot harder. If you don't have at least a marginally consistent input, your only real option is probably going to be scanning by character and looking for the \x02 and \x03 to get a glob of data, then parse that glob with some kind of xml parser, since the data between those two is likely safe-ish. -- David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] formatting xml (again)
* richard kappler [2016-12-27 16:05]: > The input is consistent in that it all has stx at the beginning of each > 'event.' I'm leaning towards regex. When you say: > > " find stx, stuff lines until I see the next stx, then dump and continue" > > Might I trouble you for an example of how you do that? I can find stx, I > can find etx using something along the lines of : > > a = [m.start() for m in re.finditer(r"", line)] > > but then I get a little lost, mostly because I have some lines that have > "data data [\x03][\x02] data" and then to the next line. More succinctly, > the stx aren't always at the beginning of the line, etx not always at the > end. No problem, I can find them, but then I'm guessing I would have to > write to a buffer starting with stx, keep writing to the buffer until I get > to etx, write the buffer to file (or send it over the socket, either way is > fine) then continue on. The fact that 'events' span multiple lines is > challenging me. Well, that shows that in the context of line-based data, it is not consistent. That's the main issue. If you knew that every event started on a new line, then you could fairly easily: if '\x02' in line: output = line.strip() while '\x02' not in line: output = output + line.strip() etc. Unfortunately, we don't have that kind of line-based consistency. You are either going to have to treat it more like a binary stream of data, triggering on stx and etx on a character-by-character basis, or you are going to have to test for both stx and etx on each line and do different things based on the combination you find. Some possible options for a single line appear to be: [\x02] [\x02] data [\x02] data [\x03] [\x02] data [\x03][\x02] [\x03] data [\x03] data [\x03][\x02] data [\x03][\x02] data etc That's assuming something really ugly like this couldn't happen on a single line (but somehow I think it probably can): data [\x03][\x02] data [\x03][\x02] I think you are stuck reading as a character stream, rather than a line-based text file due to the unstable nature of the input. Another possibility (I suppose) would be to read per line and split on the \x02 yourself (I'm assuming that's actually a single hex character). That would artificially create "record" data that you could manipulate and combine partial segments into complete xml records to parse. Might be faster, might not, probably would get complicated pretty quickly but could be an option. Without seeing actual data, it's tough to speculate what the best approach would be. -- David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] formatting xml (again)
* Alan Gauld via Tutor [2016-12-28 00:40]: > On 27/12/16 19:44, richard kappler wrote: > > Using python 2.7 - I have a large log file we recorded of streamed xml data > > that I now need to feed into another app for stress testing. The problem is > > the data comes in 2 formats. > > > > 1. each 'event' is a full set of xml data with opening and closing tags + > > x02 and x03 (stx and etx) > > > > 2. some events have all the xml data on one 'line' in the log, others are > > in typical nested xml format with lots of white space and multiple 'lines' > > in the log for each event, the first line of th e 'event' starting with an > > stx and the last line of the 'event' ending in an etx. > > It sounds as if an xml parser should work for both. After all > xml doesn't care about layout and whitespace etc. > > Which xml parser are you using - I assume you are not trying > to parse it manually using regex or string methjods - that's > rarely a good idea for xml. Yeah, since everything appears to be .., the "event" flags of [\x02] [\x03] may not even matter if you use an actual parser. -- David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (no subject)
> On Feb 7, 2017, at 15:09, တာန္ခတ္သန္ wrote: > > > # RockPaperScissors > > import random > print ("Hello.. Welcome from Rock, Paper, Scissors Game!!\n" > +"Game instruction:\n" > +"You will be playing with the computer.\n" > +"You need to choose one of your choice: Rock, Paper or Scissors.\n" > +"Enter 'e' to exit the game.\n") > > game_command = {"r":"Rock","p":"Paper","s":"Scissors","e":"Exit"} > > > score = 0 > player = 0 > try: >while player == 'r' and player == 'p' and player == 's': > There are two major things that you need to address first. 1. You never ask for user input before starting your while loop 2. Your while loop is testing for r, p, and s to all be equal to each other and set, which is not what you want to test. Basically, your while loop is immediately false as soon as you run your script. You need to rework your logic to test the player’s value. — David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Q about .join() Thanks!
> On Feb 13, 2017, at 12:34, SIJIA CHEN wrote: > > I find out that the outcome for using .join() on a dictionary is totally > different than it using on list or string. for example, > >>>> seq4 = {'hello':1,'good':2,'boy':3,'doiido':4} >>>> print ':'.join(seq4) > boy:good:doiido:hello > So my question is why the outcome doesn't show sequentially as the same > sequence of the original seq4? What pattern do those "keys" of the > dictionary in the outcome show ? Dictionaries (in particular, their keys) are unordered. You can not rely on them to be in a particular sequence. The reason for this, from a practical perspective, is you are expected to ask for the specific key; you should not care about the ordering. Lists, on the other hand, have a specific order by design so will always be in the order they were created. What are you trying to do with join() on a dictionary in the first place? Is there a specific outcome you are trying to get? It’s unlikely that using join on a dictionary is what you actually want. — David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] printing items form list
> On Mar 3, 2017, at 12:52, Peter Otten <__pete...@web.de> wrote: > > Antonio Zagheni via Tutor wrote: > >> suitcase = ["book, ", "towel, ", "shirt, ", "pants"] > > Hm, looks like you opened Rafael's suitcase while he wasn't looking, and > sneaked in some commas and spaces ;) > > That's cheating... yeah, just a little. :-) You can use join for this: suitcase = ["book", "towel", "shirt", "pants"] output = ', '.join(suitcase) print ("You have a %s in your luggage.") %output — David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] printing items form list
> On Mar 3, 2017, at 13:42, dirkjso...@gmail.com wrote: > > On 03/03/2017 12:19 PM, Alan Gauld via Tutor wrote: >> >> That's one reason why join() is a better solution, it >> handles all of that for you. It's also faster, although >> in a small application you'd never notice the difference. >> > The ','.join(suitcase) is obviously best of all, but if one doesn't know that > method, the below suggestion can be fixed with: > > suitcase = ['book', 'towel', 'shirt', 'pants'] > > for i in suitcase: >st = st + i + ', ' > > print('You have a s% in your luggage.' % st) There are three issues with that statement. 1. not knowing a method is not an excuse. It’s worth knowing join because it has a lot of flexibility (and it _is_ known because of this discussion) 2. Your code as written doesn’t work because st is not defined before you use it >>> suitcase = ['book', 'towel', 'shirt', 'pants'] >>> for i in suitcase: ... st = st + i + ', ' ... Traceback (most recent call last): File "", line 2, in NameError: name 'st' is not defined 3. Your [fixed] code (added st = ‘') and join do NOT do the same thing (note the extra comma and space at the end of yours) join: You have a book, towel, shirt, pants in your luggage. yours: You have a book, towel, shirt, pants, in your luggage. String concatenation with a loop is notorious for adding extra stuff at the end. To get it right, you have to take into account what to do at the end of the list, which adds code complexity. — David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to control putty window
* Ufuk Eskici [2012-12-20 16:25]: > Hello, > > I run this command and opens putty: > > import os > import subprocess > command = '"c:\Program Files\Putty\putty.exe" -ssh > ufukeskici@10.10.10.10-pw test > subprocess.Popen(command) > > But then I want to input new commands to this Putty new window. How can I > do it? Once you start putty, it is a separate application that python doesn't really know anything about. How many commands are you trying to send? If it's only one or two, you might be able to set up a putty profile with a couple auto-commands on connect, but that's not the same thing. If it's a long string of commands, you might be better to pscp a shell script to the target with one command, and then call that script with the putty profile. I would research automating putty first, then see if there are any options within python to accomplish the same things. -- David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Binary/Decimal convertor
* Ghadir Ghasemi [2013-01-11 21:51]: > Hi, I made a program called binary/denary convertor. Can anyone tell > me about how I could stop the user entering a binary number with more > than 8 numbers or 8 bit by repeating the question over and over until > they do enter a correct binary number( 8-bit or less) Here is the > code. I started off by entering 'len' function. > > def add_binary_numbers(num1, num2): > return num1 + num2 > > num1 = int(input('please enter the first 8 bit binary number: '),2) > if len(num1) > 8: > print("please enter an 8 bit binary number") > return int(num1,2) > num2 = int(input('please enter the second 8 bit binary number: '),2) > result = add_binary_numbers(num1, num2) > print('the result is', bin(result)[2:]) It looks like the first thing you need to do is figure out how to use a loop (eg, while loop, for loop). I would recommend thinking about some pseudocode to determine your program's flow and then try to build something to accomplish that. -- David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] First Python Test
* Alan Gauld [2013-02-02 17:49]: > On 02/02/13 12:57, Shall, Sydney wrote: > > Dear Aurelien, > > Would you please explain how one installs GNU Emacs on a MAC using OS X > > v10.6. > > Last time I looked it was already installed. Just type emacs at a > Terminal prompt. Verified on 10.6.8 -- David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] First Python Test
* Shall, Sydney [2013-02-03 16:47]: > > On 03/02/2013 13:13, Jonatán Guadamuz wrote: > > El 03/02/2013, a las 06:53 a.m., "Shall, Sydney" > > escribió: > > > >> Dear Alan, > >> I installed Cocoa emacs successfully. > >> But it does not run on OS X 10.6.8. > >> The notes with it say that it was built for 10.4. > >> Where may I look for an update, please? > >> With many thanks for your help. > >> Sydney > > Maybe you can look here > > > > aquamacs.org The first hit I get googling for "cocoa emacs" returns: http://emacsformacosx.com/ Perhaps that will work for you. I've tested that it works on my system, at least ("works" = it ran). -- David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionaries and multiple keys/values
* Robert Sjoblom [2013-03-26 05:36]: > > brittle. However, even if I was happy with that, I can't figure out > what to do in the situation where: > data[i+3] = 'Canadian, Pub Food' #should be two items, is currently a string. > My problem is that I'm... stupid. I can split the entry into a list > with two items, but even so I don't know how to add the key: value > pair to the dictionary so that the value is a list, which I then later > can append things to. If your data is a list, then it will be a list in the dict. You could just make it so that particular key always contains a list of characteristics, even if it's a list of only one. >>> data = 'Canadian, Pub Food'.split(',') >>> data ['Canadian', ' Pub Food'] >>> data = 'French'.split(',') >>> data ['French'] Then just put the list as the value. d['characteristics'] = data >>> data = 'Canadian, Pub Food'.split(',') >>> d['characteristics'] = data >>> d['characteristics'] ['Canadian', ' Pub Food'] -- David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Text Editors and Linux (was Re: exit message)
* Steven D'Aprano [2013-05-08 22:13]: > On 08/05/13 00:26, Prasad, Ramit wrote: > > Steven D'Aprano wrote: > > > >> * a decent console app that supports multiple tabs; > > > > Any reason to prefer tabs to virtual terminals (i.e. screen)? > > > Yes. I can see tabs, and click them with a mouse, they can have a > meaningful title, and I can use spacial memory to associate them with > tasks. "Tests = second last tab" is more natural for me to remember > than "Tests = virtual terminal 7", and clicking with the mouse is much > faster for me than remembering, and typing, "Ctrl-A 7". Well, not to start a flame war, but that is all subjective. I find NOT using a mouse to be much faster, and screen can be set up pretty much the same way you describe (specific screens for a task, labels, etc). So it's really more about personal taste than anything. If you _like_ what you are using, that's fine. I wouldn't like that setup. All options are valid options. Try them all and find what you like. -- David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Text Editors and Linux (was Re: exit message)
* Steven D'Aprano [2013-05-09 10:29]: > On 09/05/13 02:57, David Rock wrote: > > > > Well, not to start a flame war, but that is all subjective. > > Did I say otherwise? I was very careful to say "more natural FOR ME, > faster FOR ME". Not at all, but it was suggested that console apps were not able to do the same thing as tabbed apps, which isn't the case. I also didn't say you were wrong, I just don't want an option to be overlooked because of a personal bias. I have no argument against tabbed environments being more natural, because they are. There is a steep learning curve for many console apps, but they can be rewarding if used properly. > > So it's really more about personal taste than anything. If you _like_ > > what you are using, that's fine. I wouldn't like that setup. > > I'm sure that many people wouldn't. > > On the other hand, I work with, and watch, a lot of techies who live > in screen. They swear that they're more efficient, but watching them > hunt for the right virtual terminal doesn't look very efficient to me. > I often see them flip through three or four different VTs until they > reach the one they were looking for. Then they aren't using it correctly. My screen sessions are labeled, and show me exactly what window I'm in, just as well as a tabbed window does. I don't have to remember anything any more than you do. Someone using a tool inefficiently does not mean that tool is inefficient. > It is especially amusing when they end up shutting down the wrong > server because they've gone to the wrong vt and haven't realised it. That's not an honor reserved for users of screen. I see the same thing from other folks using all manner of environments, including tabbed ones. -- David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Text Editors and Linux (was Re: exit message)
* Alan Gauld [2013-05-09 07:47]: > On 09/05/13 05:01, Prasad, Ramit wrote: > > > What I like about screen is the way sessions stay open when > > disconnected, but I find tabbed terminals easier to scroll for > > history. If there is a tabbed terminal that will allow split screens > > then all the neat features I know about in screen would > > exist...although I rarely use that feature at the moment. > > Can't you use screen within a tabbed terminal? > > Just a thought... > Actually, no (at least not for scrolling). If you scroll in a window that has screen running, you won't scroll the content of the screen session, which is what you actually want to see. It will just show what's in the buffer from before starting the screen session. You would still need to use the scrollback buffer in screen (ctrl-a ESC), which again, works well, but is not necessarily intuitive. > Or use emacs... :-) There's always one. You aren't helping the case for console apps with that one at all. :-) -- David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Text Editors and Linux (was Re: exit message)
* Prasad, Ramit [2013-05-09 04:01]: > Steven D'Aprano wrote: > > On the other hand, I work with, and watch, a lot of techies who live > > in screen. They swear that they're more efficient, but watching them > > hunt for the right virtual terminal doesn't look very efficient to > > me. I often see them flip through three or four different VTs until > > they reach the one they were looking for. It is especially amusing > > when they end up shutting down the wrong server because they've gone > > to the wrong vt and haven't realised it. > > > > ctrl+a, > > will list all screen titles and let you navigate using arrow keys or > typing in the number. Of course, that assumes you correctly title > your virtual terminal sessions. > > I was mostly curious because they seem roughly equivalent and mostly > dependant on the terminal I am using. I was wondering if maybe there > was a trick or two that I was missing. I'll defend Steven on this one. Yes, that works, but it's far from efficient. What I use in my .screenrc is: hardstatus alwayslastline "%w" Which effectively puts titled tabs on the last row of the screen. Admittedly, if you have a lot of sessions open, you are limited by space a bit doing this, in which case the ctrl+a " may be necessary, but you have bigger issues if you have that many open at one time. :-) > What I like about screen is the way sessions stay open when > disconnected, but I find tabbed terminals easier to scroll for > history. If there is a tabbed terminal that will allow split screens > then all the neat features I know about in screen would > exist...although I rarely use that feature at the moment. Yes, the disconnect/reconnect is nice (I use it a lot). It's not exactly relevant to merits of console interfaces vs GUI, though. That's more of a "this is a cool baked-in capability for working with lousy network connections", which you can also do with things like VNC for a remote GUI. -- David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Text Editors and Linux (was Re: exit message)
* Alan Gauld [2013-05-09 16:50]: > On 09/05/13 15:42, David Rock wrote: > > >> Or use emacs... :-) > > > > There's always one. You aren't helping the case for console apps with > > that one at all. :-) > > But then emacs can also be considered an IDE in its own right so its > maybe a special case. Yeah, emacs is definitely a special case. There aren't many examples out there of a single application that can do so many things. :-) -- David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How convert an int to a string
* Jim Byrnes [2013-06-22 16:01]: > I need to convert a series of digits like 060713 to a string so I can > make it look like a date 06-07-13. > > >>> a = 060713 > >>> a[:2] > Traceback (most recent call last): >File "", line 1, in > TypeError: 'int' object has no attribute '__getitem__' > >>> b = str(a) > >>> b[:2] > '25' > >>> b > '25035' > >>> > > I was confused at first but then realized that the 0 makes it octal. I > thought str() would do it but it didn't. Reading about str() it talks of > string representation. So how can I convert it to a true string I can > slice and build my date look a like? Is there a requirement to store them as numbers in the first place? Why not just store them as a string? a = '060713' -- David Rock da...@graniteweb.com signature.asc Description: Digital signature ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Parse text with python
* Danilo Chilene [2013-10-17 17:55]: > Hi, > > The part that always change is the , it can be 1 digit or 4 digits. > Example: 1. > The part that never changes is the 1700. I think the point is we have a hard time believing that 1700 will never change. What do you plan to do when it does down the line? It's generally a bad idea to focus on something that is obviously a data field as an item to key off of. That said, another approach you could take is to use split(). Split each line, check to see if 1700 is in it, then just grab the next field. Inherent dangers: INUSE field may be empty, so you will grab the wrong value 1700 might be somewhere other than where you expect it etc -- David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help (Splitting a word into letters)
* y j [2014-03-18 16:41]: > how can i split a word into letters in python 2.7.6? Strings can already be accessed as arrays: >>> s='foobar' >>> print s[2] o >>> print s[4] a >>> print s[7] Traceback (most recent call last): File "", line 1, in IndexError: string index out of range >>> Can you be a little clearer what you need? Are you looking to store them in variables, an array, print them? If printing them, are you looking to output one per line, or spaced out? -- David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help Noob Question
* Chris “Kwpolska” Warrick [2014-03-28 16:27]: > > Create a folder on the desktop, or even in the home directory. A much > nicer place than the drive root — and a much modern way to store it > (drive root sounds DOS-y) I'll have to disagree with this statement. Dropping all your files in you Desktop directory puts all the files ON the Desktop, which quickly becomes a mess. Regardless of whether it's a new directory at the base, or a new directory under your User directory, you should at least have a dedicated directory to put the files. I'm not discussing the merits of one place over the other, just that simple organization is a good thing. Put it wherever you want, but at least keep it organized. Dropping everything in Desktop is not organized. -- David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] while loop
* Scott Dunning [2014-03-30 18:37]: > Without out a break or placing that 10 in there I can’t think of a way > to have the while loop stop once it reaches (n). Any hints? As discussed already, you can't use fixed values (ie, you don't know that 10 is always going to be there). > def print_n(s, n): > > while n <= 10: > > print s > > n = n + 1 > > So, instead of while n <= 10: Think about: while something <= n: and changing something and retesting. -- David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Question about O(N**2)
The the "Logical Error" question, this was brought up: The big problem is this: fullPath += [line.decode('utf-8', 'ignore').strip()] which is an O(N**2) algorithm. Do you know that terminology? Very briefly: O(1) means approximately constant time: tripling the size of the input makes no difference to the processing time. O(N) means linear time: tripling the input triples the processing time. O(N**2) means quadratic time: tripling the input increases the processing time not by a factor of three, but a factor of three squared, or nine. With small files, and fast computers, you won't notice. But with huge files and a slow computer, that could be painful. Instead, a better approach is: fullPath.append(line.decode('utf-8', 'ignore').strip()) which avoids the O(N**2) performance trap. I have two questions: 1. How do you know that fullPath += [line.decode('utf-8', 'ignore').strip()] is an O(N**2)? 2. How do you know that fullPath.append(line.decode('utf-8', 'ignore').strip()) is not? -- David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] printing all text that begins with "25"
* Bo Morris [2014-10-02 11:41]: > Hello all, hope everyone is doing well. > > When I run the linux command "hamachi list" i get something along the lines > of the following output > >087-888-279 Pandora25.x.x.xxx alias: not > set >096-779-867 AM1LaptopBD-PC25.x.x.xxx alias: not set >097-552-220 OWS-Desktop 125.0.0.0 alias: not set >099-213-641 DESKTOP 25.0.0.0 alias: not set > > I am trying to write a python script that will run the above command and > only print out the IP's that begin with 25. How do I strip out all other > text except for the IP's that begin with "25?" There are a few assumptions that need to be made, for starters. Is the format always the same (ie, is the IP address always in column 3 separated by whitespace)? Looking at the line with "OWS-Desktop 1", the answer is no. That complicates things a bit. If it was true, you could use the string split method to get column 3. Maybe the fields are separated by a tab? A regex may be possible, but you will have similar issues to using split. I'm also assuming it's possible for there to be IP addresses that do not start with 25. Are you looking to isolate those? It's not necessary to write out to a file first. You can get the output from commands and work on it directly. Another approach would be to change the command you are running. I've never heard of hamachi list before; does it have any commandline options to display only IP addresses? -- David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A question about using stdin/out/err vs named files
* Peter Otten <__pete...@web.de> [2014-10-19 10:05]: > George R Goffe wrote: > > > When you run a python program, it appears that stdin, stdout, and stderr > > are opened automatically. > > > > I've been trying to find out how you tell if there's data in stdin (like > > when you pipe data to a python program) rather than in a named input file. > > It seems like most/all the Unix/Linux commands are able to figure this > > out. Do you know how Python programs do this or might do this? > > There is also the fileinput module. I use fileinput all the time. "This iterates over the lines of all files listed in sys.argv[1:], defaulting to sys.stdin if the list is empty. If a filename is '-', it is also replaced by sys.stdin. To specify an alternative list of filenames, pass it as the first argument to input(). A single file name is also allowed." It gives a fairly clean way to just "do the Right Thing" whether you are feeding files, or reading from stdin. -- David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] While until the end of a list
> On Mar 13, 2017, at 10:54, Toni Fuente via Tutor wrote: > > Hi, > > I've got this script that goes through an httpd conf file, and gets the > related bits of it for a site, and writes a new config with values that > I am interested. The problem is that it finds the first chunk and > returns it, but I need to go to the end of all chunks list, because > there are also some chunks related to the same site that I need to > collect (virtualhost *:80 and virtualhost:443). I was > > I was thinking in a while loop in the find_chunk function that will go through > all chunks and return the chunks that site is on, but I don't know how to > construct it. You just need to make a list or a dict to store the information for each site, and add the results to it. If you use a list, it would be list.append(), for example. I don’t really follow what you expect the output to be, though. What do you want the results of running the script to look like? — David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Problem on parsing data
> On Mar 13, 2017, at 16:19, jarod_v6--- via Tutor wrote: > > > What can I do for parse better that file and Have only the comma outside the > string ? > I recommend using the cvs module rather than try to write your own. https://docs.python.org/2/library/csv.html — David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] CSV file Reading in python
> On Mar 20, 2017, at 14:37, Edzard de Vries wrote: > > I have a CSV which I want to be able to read in Python. I don't know the > exact syntax and I get error messages. Where can I find the syntax to do this. > I juiste starter learning Python. Edzard, Please post your code and the errors you are getting so we can see what issue you are having. — David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python - help with something most essential
> On Jun 5, 2017, at 09:36, Schtvveer Schvrveve wrote: > > > And I was rejected. I just wish to understand what I could have done for > this to be better? > > I am a Python beginner, so I'm sure there are things I don't know, but I > was a bit surprised at the abruptness of the rejection and I'm worried I'm > doing something profoundly wrong. The main thing that jumps out to me is the memory issue they asked you to address was not addressed. In your readFile, you have with open(filename) as f: content = f.readlines() Which reads the entire file into memory. They specifically did not want you to do that. The implication is they were looking for a solution where you read the file maybe one line (or even one word) at a time and look for anagrams in smaller groups. — David ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Fahrenheit to Celsius Conversion another problem and Programming Paradigm
> On Jun 14, 2017, at 09:20, William Gan wrote: > > However, today I modified only the print instruction a little to try to print > out ℃ (in the second print clause). When I subsequently ran the script all > the outputs were executed from the if clause, even when I input other letters > (Please see below. I have removed the code to print degree C). > > > if unit == 'C' or 'c': > >f = temp * 9 / 5 + 32 > >print(str(temp) + ' C is equivalent to ' + '%.2f' % f + ' F.') > > elif unit == 'F' or 'f': > >c = (temp - 32) * 5 / 9 > >print(str(temp) + ' F is equivalent to ' + "%.2f" % c + ' C.') The problem is your if statement is flawed. if unit == 'C' or 'c’: This is not doing what you think it is. You are expecting: if unit == ‘C’ or unit == ‘c’ When doing an ‘or’ statement, each part of the logic on each side of the ‘or’ is evaluated, so if unit == ‘C’ is true, or if ‘c’ is true is what’s actually being checked. a bare character, ‘c’ will always evaluate to True, so the if is always true. What you actually want (checking if unit is ‘C’ or ‘c’) can be done a few ways. The most common are: if unit == ‘C’ or unit ==‘c’: or if unit in [‘C’, ‘c’]: > ISSUE 2: > > The second issue relates to the last statement above “I have looked at it > many times today and could not see the error”. > > > > I was hoping that someone, perhaps one with pedagogical experience and > knowledge, could advise the following: > > 1. Is it possible that I may not have the right aptitude or mental > paradigm to do computer programming? Unlikely. Programming is not about aptitude, it’s more about spending time understanding the rules. The above is a prime example of getting to understand the rules. Logic rules are notoriously specific; they check exactly what you tell them to check, which is not always what you think you are asking. It just takes time. > > 2. Nevertheless, I intend to keep learning and practicing, but wonder > if there is an effective way to get a breakthrough into the programming > paradigm? If so, kindly advise how and direct me to a suitable resource to do > it. Really, just keep trying things. When you run into something like this, the most effective way to troubleshoot is narrow it down to the essential issue. In this case, “why is the if statement always evaluating to true?” Look at the parts and re-read what each does (eg, reread how the ‘or’ operator works). You are doing fine. :-) — David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Fahrenheit to Celsius Conversion another problem and Programming Paradigm
> On Jun 15, 2017, at 13:16, William Gan wrote: > > Hi David, > > Very much thanks for taking time to help. > > Your explanation has helped me understand that syntax issue better. I have > resolved that error. > > Your counsel on the second issue has given me encouragement. Thank you. I’m glad it helped. For completeness, in case you didn’t notice, your elif statement has the same issue. elif unit == 'F' or 'f’: c = (temp - 32) * 5 / 9 print(str(temp) + ' F is equivalent to ' + "%.2f" % c + ' C.’ — David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Why use main() ?
This is not a question about using if __name__ == '__main__':. I know what the difference is between running the script or importing it and using the value of __name__ to determine behavior. This is a question about the benefits of using a main() function vs not. ie, if __name__ == '__main__': #code goes here vs def main(): #code goes here if __name__ == '__main__': main() I personally find using main() cumbersome, but many examples I come across use main(). Is there some fundamental benefit to using main() that I'm missing? -- David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Why use main() ?
* Alan Gauld via Tutor [2017-07-05 20:36]: > On 05/07/17 16:37, David Rock wrote: > > > This is a question about the benefits of using a main() function vs not. > > > Others have answered for the pros, but I confess that I don't > always use a main(), but only if all I'm doing is, say, > instantiating a class and running a method. For anything > more complex I'd write a main() (or test() or demo() ) to > go inside the >if name==main > clause. Thank you everyone for the input. -- David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor