Re: [Tutor] (no subject)- finding/deleting files
> On 08/19/2012 03:29 PM, Selby Rowley Cannon wrote: >> OK, I have some code, and it uses glob.glob('*.py') to find all the >> python files in the current directory. >> Just thought i'd ask, would: >> >> glob.glob('C:\*.py') (Windows), or >> >> glob.glob('/*.py') (*nix) >> >> find all the python files on the system? Thanks > > See http://docs.python.org/library/glob.html Selby, Also there is no rule that says that all python files must end in .py. Those that don't of course will not be 'found.' ;-( I just happened to knock out a little script that might be easily adapted to what you want to do. I'll attach it in case you want to make use of it. alex > > I don't see anywhere it implies that more than one directory would be > scanned. In any case, it's pretty quick to just try it in the > interpreter. I tried using python 2.7 on Linux, and it does not descend > recursively into subdirectories. > > Perhaps you want os.walk, which lets you loop over an entire tree of > files/directories. > > BTW, you forgot to double the backslash in your Windows example. Either > double the backslash, or make it a raw string, or use forward slashes. > > > -- > > DaveA > > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > #!/usr/bin/env python import os.path import os import sys def visitfunc(arg, dirname, names): for name in names: name_path = os.path.join(dirname, name) if name[:2] == '._': if os.path.isfile(name_path): print "OK: %s"%(name_path, ) #os.remove(name_path) # Delete the hash ('#') mark on the above line to "activate" this program. # If you don't do that, the program is harmless; it simply tells you which # files it would have deleted had you uncommented that line. args = sys.argv[1:] for argument in args: print "AK: dir specified: '%s'"%(argument, ) arg_path = os.path.abspath(argument) print "AK: path used: '%s'"%(arg_path, ) print "Unless the 'os.remove..' line is commented out," print "the following files will be deleted." os.path.walk(arg_path, visitfunc, arg_path) ___ 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?
This question seemed a good excercise so I banged out a little script (which worked) but latter I saw posts showing code that by using string method 'partition' provided a more elegant solution. I was previously unaware of this method. My "bible" has been David M. Beazley's Python Essential Reference (3rdEd) in which this method is not mentioned (that I can see.) Should I switch "bibles?" (I often find myself wanting to hack in "off line environments" so something as old fashion as a book would be nice:-) Here's my script for what it's worth: #!/usr/bin/env python import sys usage = """test0 separator Requires one parameter, the text to be used to separate the input which will be requested by the program.""" if len(sys.argv) != 2: print usage separator = sys.argv[1] def separate(string, separator): ret = [] i = string.find(separator) l = len(separator) while i > 0: ret.append(string[:i]) ret.append(separator) string = string[i+l:] i = string.find(separator) ret.append(string) return ret def repart(string, separator): """Does the same as separator but using string method 'partition'""" parts = string.partition(separator) if parts[0] == string: return (parts[0], ) else: return parts[:-1] + repart(parts[-1], separator) input_str = raw_input("Enter text to split on '%s': "%(separator, )) separated_array = separate(input_str, separator) for s in separated_array: print s parted_array = repart(input_str, separator) for s in parted_array: print s > 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. > I'm not sure how to break the string, though. > I looked through the docs and found split() and partition(), which come > close. > 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. > > Here's the script in its basic form: > > #!/usr/bin/python > > text = raw_input("Enter text: ") > print "You entered ", text > > objects = text.partition(' and') > print objects > > for object in objects:# Second Example > >print object > > For example, if I run this with the input: > "Ham and cheese omelette with hasbrowns and coffee." > I get: > Ham > and > cheese omelette with hashbrowns and coffee. > > Any help is greatly appreciated. > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > ___ 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?
> On 23/08/12 23:08, aklei...@sonic.net wrote: > >> (I often find myself wanting to hack in "off line environments" so >> something as old fashion as a book would be nice:-) > > Depends how off line you are. > If you still have the python interpreter then just using dir() and > help() should be all you need. > > I couldn't recall how partition worked so I just typed > help(''.partition) at the >>> prompt. > > Most documentation you need is available that way, and if in doubt try > it out at the prompt! > > But if you mean offline as in only paper and pencil then a book is the > best bet and Beazley is good. I use him and Python in a Nutshell for my > paper-only moments. Thank you for the tips. I will definitely KEEP Beazley- we've developed a very warm and cuddley relationship! (the Book, I mean:-) I raised the issue out of concern that the 'partition' method wasn't there and consequent worries that there may be other cool things I'm missing. Ahh, Ha! as I type this I suddenly realize what you are getting at: >>> s = "my string" >>> s.dir() Big "Thank You" alex > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > ___ 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?
> On Thu, Aug 23, 2012 at 9:08 PM, wrote: >> > s.dir() >> > > Surely you mean dir(s). Maybe you're thinking of the __dir__ special > method you can add to a class to override the default behavior. > Yes, dir(s) is what I gave the interpreter. I should have used cut and paste (but tend not to for short bits.) > You can also dir(str), or call help(str) to page through all of the doc > strings. > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python working with Bash....arrrggggh!
> As I code Python, I find myself falling back on Bash to handle basic OS > tasks. How do you gurus deal with Python --> Bash conflicts? > > For example, if I wish to test if a file exists, I might do > > test = Popen('[ -f file-i-want-to-test-for ]') > > But the moment I invoke Bash for a test, I must deal with the fact that > Bash returns a zero for true and a non-zero for false. But in Python, > zero is false and non-zero is true. So if the file exists, the variable > 'test' will be zero since that is what was returned by Bash. But if I > want to test the variable for the existence of the file, I have to test > the opposite: 'if not test:' because Python sees the zero as False. > > Does it become second nature to work with these conflicts? Or do you > find it more expedient bypass the OS shell and work almost exclusively > with Python? try >>> import os.path >>> os.path.exists(path) or >>> os.path.isfile(file_name) http://docs.python.org/library/os.path.html > > > Ray > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] reason(s) for trailing comma in dict declarations
Part of a previous post: """ Here's the style I'd use: combos = { 0: 'id', 2: 'country', 3: 'type', 5: 'lat', 6: 'lon', 12: 'name', } Put each entry on its own line, indented by two spaces, and leave a trailing comma on the last entry. The latter is especially important in sequences of strings to prevent them from being "silently"<=>"concatenated" if you were to add an entry and forget the comma. """ When I first saw this I thought it would lead to a syntax error so tried it out.. Then played with it to try to recreate the '"silently"<=>"concatenated"' problem but couldn't. I like this syntax because it avoids the syntax error if the comma is omitted when adding an entry but I don't understand the (potential) concatenation problem. Could you explain please? alex ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reason(s) for trailing comma in dict declarations
Thanks for the clarification. Now it is clear. ak > On Sat, Aug 25, 2012 at 11:53 AM, wrote: >> >> Put each entry on its own line, indented by two spaces, and leave a >> trailing comma on the last entry. The latter is especially important >> in sequences of strings to prevent them from being >> "silently"<=>"concatenated" if you were to add an entry and forget the >> comma. >> """ >> >> When I first saw this I thought it would lead to a syntax error so tried >> it out.. >> Then played with it to try to recreate the '"silently"<=>"concatenated"' >> problem but couldn't. I like this syntax because it avoids the syntax >> error if the comma is omitted when adding an entry but I don't >> understand >> the (potential) concatenation problem. >> >> Could you explain please? > > Sure, I said the problem is with "sequences", not mappings. The syntax > for a dictionary will catch the mistake. But try it with a list. > > x = [ > "string1", > "string2", > "string3" # no comma > ] > > Later you decide to add "string4" but forget to add the comma: > > x = [ > "string1", > "string2", > "string3" # no comma > "string4" > ] > > Result: > > ['string1', 'string2', 'string3string4'] > > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] running more than one python program at the same time
> On 08/28/2012 03:30 PM, Benjamin Fishbein wrote: >> Hello, >> I wrote a program that I want to have running 24/7. But the problem is >> that I also want to write and run other programs. I'm using Idle and it >> won't let me run more than one script at a time. Do you know if there's >> a way to do this? Or do I need to buy a second computer? >> Thanks, >> Ben > Can you make each script executable and run them without idle? > > > Ray > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > The following works with Linux and might with OSX as well. add "#!/usr/bin/env python" as the first line of your script. Then from the terminal change its permissions: $ chmod 755 /paht/to/my/script/script.py After that you can start your program with: $ /path/to/my/script/script.py If you add "&" to the end of the line it'll go into the background and you'll get your terminal back. I am less confident that the following will work on your Mac but there is probably something equivalent. If you wanted it to run when ever the computer is on, see if there is a file called "/etc/rc.local" If there is, edit it (you'll need root privileges to do so) and add as a last line: "/path/to/my/script/script.py" The words between the slashes will of course have to be modified to suit your situation. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Print List
> On 12/09/12 16:36, Ashley Fowler wrote: > >> def printList(lists): >> print("First Name\tLast Name\tCredits\tGPA") >> for i in lists: >> print (i) >> >> >> Any Suggestions or Corrections? > > The input parameter is called 'lists' which implies that the input is > more than one list. Try to make your input parameter names as accurate > as possible. In this case you might think 'list' would be good, but its > no, because list is a Python builtin word. So we would be better to > choose something like aList or theList. > > Your function could have been generic in that it printed any kind of > list but by printing a header line you have made it specific to a list > of students. So you could call the input studentList. > > In general, in Python, generic functions are favoured. One way to have a > header and be generic would be to pass the header in as a parameter too: > > def printList(theList, theHeader=""): > print(theHeader) > for item in theList: >print item > > > And then you would call it with: > > printList(myStudentList, "First Name\tLast Name\tCredits\tGPA") > > Or > > printList(myPetList, "Name, Breed, Age") > > Or > > printList(myBlankList) # uses the default empty header > > or whatever... > > -- > Alan G To make it even more generic I would suggest replacing """ print(theHeader) """ with """ if theHeader: print(theHeader) """ to avoid a blank line if you don't need/want a header line. ak > def printList(theList, theHeader=""): > print(theHeader) > for item in theList: >print item > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] index of elements in numpy array
> On 13 September 2012 21:16, Bala subramanian > wrote: > >> Friends, >> I have a 2D matrix (a numpy array) and i am looping over each row in >> the matrix. I would like to know how i can find the index of each >> element in a while looping a row. Is there any function in numpy. >> > > Your question could mean several things. Could you post a small piece of > example code and clarify what it is you're unable to do? > > Here's an example that loops over all elements of a 2D Matrix: > import numpy M = numpy.array([[1, 1], [2, 3], [5, 8]]) M > array([[1, 1], >[2, 3], >[5, 8]]) numrows, numcols = M.shape for i in range(numrows): > ... for j in range(numcols): > ... print M[i, j] > ... > 1 > 1 > 2 > 3 > 5 > 8 > > Oscar I think what he wants is to replace your print statement with """ if : print "Indeces are %d and %d."%(i, j, ) """ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Cube root
> On Sat, Sep 15, 2012 at 5:36 PM, Dave Angel wrote: >> On 09/15/2012 05:28 PM, Amanda Colley wrote: >>> Ok, I have to get input from a user ('enter a number') and then get >>> the >>> cube root of that number. I am having trouble with the code to get the >>> cube root. If anyone can help me solve this I would greatly appreciate >>> it. >>> ('enter a number') >>> n=number >>> ??? cube root?? >>> >>> >> >> The operator to raise a number to a particular power is **, and it's not >> constrained to integer powers. So 5*2 is 25. See what's next? >> > This is a great place to ask questions. But don't forget google (or bing) > > try googling python cube root > > see how you do and come back with your code! > -- > Joel Goldstick Why does: """ >>> import math >>> 9**(1/3.0) 2.080083823051904 >>> 9.0**(1.0/3.0) 2.080083823051904 >>> """ not seem to work? > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Cube root
> On Sat, Sep 15, 2012 at 5:36 PM, Dave Angel wrote: >> On 09/15/2012 05:28 PM, Amanda Colley wrote: >>> Ok, I have to get input from a user ('enter a number') and then get >>> the >>> cube root of that number. I am having trouble with the code to get the >>> cube root. If anyone can help me solve this I would greatly appreciate >>> it. >>> ('enter a number') >>> n=number >>> ??? cube root?? >>> >>> >> >> The operator to raise a number to a particular power is **, and it's not >> constrained to integer powers. So 5*2 is 25. See what's next? >> > This is a great place to ask questions. But don't forget google (or bing) > > try googling python cube root > > see how you do and come back with your code! > -- > Joel Goldstick OOPS!! Should have been: >>> 27.0**(1.0/3.0) 3.0 >>> Which works better than expected! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] All possible 16 character alphanumeric strings?
> Hello again python tutor list. > I have what I see as a somewhat complicated problem which I have no idea > where to begin. I'm hoping you fine folks can help me. > > I'm trying to generate a list of every possible 16 character string > containing only 2-7 and a-z lowercase. I've seen some examples using regex > to define which characters I want to use but not a way to generate the > complete list of all possibilities. I'm not looking for a handout- just a > point in the right direction. > > Any information would be awesome, thanks. > > Right now I've got something like: > > import random ''.join(random.choice('234567abcdefghijklmnopqrstuvwxyz') for i in range(16)) > > Which only prints 1 number, obviously. > > or possibly something like this: > > > def genKey(): > hash = hashlib.md5(RANDOM_NUMBER).digest().encode("base32") > alnum_hash = re.sub(r'[^a-z2-7]', "", hash) > return alnum_hash[:16] > > > Keeping in mind that although I understand this code, I did not write it, > I > got it from stackoverflow. > > Again any help would be great. Feel free to ask if you must know exactly > what I'm trying to do. > > I'm running Ubuntu 12.04 and python 2.7 > > Scott This seems to work: #!/usr/bin/env python # file : every.py print 'Running "every.py"' possible = "234567abcdefghijklmnopqrstuvwxyz" word_length = 16 word_list = [] def add_word(word): if len(word)==word_length: word_list.append(word) print word # There may come a time you won't want this line. else: for c in possible: new_word = word + c add_word(new_word) add_word("") # print word_list ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] All possible 16 character alphanumeric strings?
#!/usr/bin/env python # file : every.py print 'Running "every.py"' possible = "234567abcdefghijklmnopqrstuvwxyz" word_length = 16 word_list = [] def add_word(word): if len(word)==word_length: word_list.append(word) print word # There may come a time you won't want this line. else: for c in possible: new_word = word + c add_word(new_word) add_word("") # print word_list > That solution is really nice, thanks, I doubt I would've come up with > something as nice. What I'll do is have that write to a file then use > regex > to strip out any characters like whitespace or commas from the list and > that should give me a good solid list, no? > > I'm using this to write a program I'm calling TORdialer with the goal of > attempting to basically ping all possible TOR hidden service pages with > the > goal of having an absolutely complete list of all TOR hidden services on > the net right now. Unfortunately it will probably be a lot of fucked up CP > sites and drug related marketplaces. I'm mostly interested in the sites > that aren't publicized (ie- government related sites, etc). > Thanks for your help and I'll try to keep everyone posted. > There won't be any whitespace or commas in any of the derived output. For your purposes, you might want to make this into a generator although that would be getting too sophisticated for me to help you. Since in its present form the algorithm is a recursive one, I'm guessing it'll run out of memory long before it comes to completion although I haven't let it run for more than a few seconds, just enough to see that it seemed to be doing what I wanted. >From what I know about computer science, I believe that most if not all recursive algorithms can be re-written to be non recursive. If you could do that, you could then make a generator and presumably make use of it without overwhelming resources. I look forward to hearing what those with more expertise might have to say about that. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] All possible 16 character alphanumeric strings?
> possible = "234567abcdefghijklmnopqrstuvwxyz" > word_length = 16 > print 'Running "every.py"' > word_list = [] > def add_word(word): > if len(word)==word_length: > word_list.append(word) > print word > else: > for c in possible: > new_word = word + c > add_word(new_word) > > > The only problem with this code is that it actually takes a word as its > input and just checks that it is == word length. If not it just appends > the > string possible to the variable word that was called in the function > add_word. > > I need to be able to generate every possible combination of the characters > in the variable possible, ideally coming up with a string that resembles > the TOR hidden network strings that look like this: > "kpvz7ki2v5agwt35.onion" > > > Scott Actually it doesn't even do that. It only prints "running 'every.py'"! You forgot the line that does all the work: """ add_word("") """ I'm attaching the whole file so you don't miss the important bit. Run it and see what happens, but be ready to CNTL-C (I'm assuming you are running Linux, I think it'll be the same on Mac, all bets are off regarding M$ Windoz:-) Alex #!/usr/bin/env python # file : every.py print 'Running "every.py"' possible = "234567abcdefghijklmnopqrstuvwxyz" word_length = 16 word_list = [] def add_word(word): if len(word)==word_length: word_list.append(word) print word # There may come a time you won't want this line. else: for c in possible: new_word = word + c add_word(new_word) add_word("") # print word_list ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] All possible 16 character alphanumeric strings?
>> Hello again python tutor list. >> I have what I see as a somewhat complicated problem which I have no idea >> where to begin. I'm hoping you fine folks can help me. >> >> I'm trying to generate a list of every possible 16 character string >> containing only 2-7 and a-z lowercase. I've seen some examples using >> regex >> to define which characters I want to use but not a way to generate the >> complete list of all possibilities. I'm not looking for a handout- just >> a >> point in the right direction. >> >> Any information would be awesome, thanks. >> >> Right now I've got something like: >> >> import random > ''.join(random.choice('234567abcdefghijklmnopqrstuvwxyz') for i in > range(16)) >> >> Which only prints 1 number, obviously. >> >> or possibly something like this: >> >> >> def genKey(): >> hash = hashlib.md5(RANDOM_NUMBER).digest().encode("base32") >> alnum_hash = re.sub(r'[^a-z2-7]', "", hash) >> return alnum_hash[:16] >> >> >> Keeping in mind that although I understand this code, I did not write >> it, >> I >> got it from stackoverflow. >> >> Again any help would be great. Feel free to ask if you must know exactly >> what I'm trying to do. >> >> I'm running Ubuntu 12.04 and python 2.7 >> >> Scott > > This seems to work: > #!/usr/bin/env python > > # file : every.py > print 'Running "every.py"' > > possible = "234567abcdefghijklmnopqrstuvwxyz" > word_length = 16 > > word_list = [] > def add_word(word): > if len(word)==word_length: > word_list.append(word) > print word # There may come a time you won't want this line. > else: > for c in possible: > new_word = word + c > add_word(new_word) > > add_word("") > > # print word_list > Addendum: As others have pointed out, you might run out of patience, time, memory, or what ever ...long before completion. one solution would be to make "word_length" &/or "possible" shorter. It was fun trying to knock this one out. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] All possible 16 character alphanumeric strings?
> On 09/15/2012 10:03 PM, Scurvy Scott wrote: >>> >>> That list would fill all the PC's on the planet a few billions times. >>> The number of items in the list has 25 digits in it. print 32**16 >>> >> > > I can't see any reason why it changes anything. The world doesn't have > enough disk space to store *every* address. If you need to calculate > all of them, you don't have enough time. > > You need to rethink whatever your real problem is. For example, if you > were really trying to crack a safe with 32 numbers on the dial and 16 > settings to open it, perhaps you should forget all of it and get some > nitro. Or a stethoscope. Or bribe somebody who knows the combination. > If you have to try all of the combinations systematically, you'll never > get there. We can probably all agree that there aren't enough resources (time, memory, etc) to solve the problem, but that doesn't make the problem uninteresting. What interests me, and I acknowledge that this is more a question for a computer science forum than a python one, is: can this be done in a non recursive way so the limiting factor will be time, not memory? I couldn't think of a way. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] All possible 16 character alphanumeric strings?
> Akleider, you didn't include attribution for the person you are quoting, > which is a bit rude and also means I can't be sure who it was. From > context, I *think* it is the original poster Scott: > > On 16/09/12 13:06, aklei...@sonic.net wrote: >>> I'm using this to write a program I'm calling TORdialer with the goal >>> of >>> attempting to basically ping all possible TOR hidden service pages with >>> the goal of having an absolutely complete list of all TOR hidden >>> services >>> on the net right now. > > Did you really think that when a group of really smart security and > network > experts sit down to design a protocol for hiding services from discovery, > that it would actually be vulnerable to a programming beginner who just > lists out all the possible sites and pings them? And the TOR designers > didn't think of that? > > I'm sorry if this comes across as condescending, but it's kinda cute that > you thought this was viable. TOR is designed to be resistant to discovery > from people with the full resources of the United States and Chinese > governments. Believe me, they already considered the "brute force attack" > where you list out every possible address. > > If every person in the world runs their own TOR hidden network, then the > chances of you pinging *even one* by accident is about 1 in > 172703688516375. > If your TORdialer program could ping a million addresses per second, you > would need to run it non-stop for over five years just to find *one* > address. > > "An absolutely complete list"... oh my stars and garters. > > (Remember those maths classes on permutations and combinations that you > probably thought were totally pointless? *This* is why they're important.) > > > > -- > Steven I do sincerely apologize for anything that was rude. Please believe me, it was not my intent to be so. I also apologize for in any way contributing to anything that might be considered nefarious. I did not appreciate that the goal of the exercise was less than honourable. My interest in this had only to do with how one might come up with all possible x length strings consisting only of a predefined set of characters. Why one might want to do this, was of no interest to me at the time; in fact I didn't understand what the goal was and I appreciate your explaining that to me. Might I also take this opportunity to thank you and all the other contributers on this mailing list for the friendly helpful place I have found this list to be. Sincerely, Alex Kleider ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] "ImportError: _strptime not supported"
The following code was recently suggested as an example of how the datetime module could be used to solve a problem. Not having access to Python at work, I found http://pythontutor.com/visualize.html thinking it would allow me to "play with Python" when I have a free moment. from datetime import datetime start_date = datetime(year=2012, month=11, day=3) print(start_date) datestring = '10/11/2012' experiment_date = datetime.strftime(datestring, '%d/%m/%Y') print(experiment_date) if experiment_date > start_date: print("Experiment_date comes after start_date.") else: print("Expriment_date does not come after start_date.") Does not complete because of: "ImportError: _strptime not supported" At first I thought perhaps strptime was a Python3 feature but both v2.7 and v3.2 result in the same ImportError. Is the problem with http://pythontutor.com/visualize.html ? Also, the leading underscore in the error message puzzles me. According to http://docs.python.org/library/datetime.html """classmethod datetime.strptime(date_string, format)""" strptime should work. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Through a glass, darkly: the datetime module
> On 10/06/2012 07:19 PM, Richard D. Moores wrote: >> On Fri, Oct 5, 2012 at 7:15 AM, Walter Prins wrote: >> >>> Does this hint help? >>> >> import datetime >> mydate = datetime.date(2012,10,5) >> mydate = mydate + datetime.timedelta(days=30) >> print mydate >>> 2012-11-04 >> Yes! Thanks to all for their rapid responses. >> >> But now I'm thinking it would be handy to not only know that, say, 500 >> days from today is 2014-02-18, but to know what day if the week that >> is. I suppose the calendar module is to be used for this, but I >> haven't been able to get it to work for me. So what day of the week IS >> 2014-02-18? >> >> The docs say >> calendar.weekday(year, month, day) >> Returns the day of the week (0 is Monday) for year (1970â...), month >> (1â12), day (1â31). >> > import calendar > calendar.weekday(2014, 2, 18) >> 1 >> >> That "1" means Tuesday, right? But how can I use calendar to print out >> that word, "TUESDAY"? >> >> Thanks >> > > To turn an integer (0-6, or whatever) into a string, just use a tuple of > the same size: > > tran = ("MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", > "SATURDAY", "SUNDAY") > i = 1 > print tran[i] > > (prints "TUESDAY") > > Note that I'm not sure of the actual mapping of the integers coming out > of the weekday function, so you might have to rearrange the strings above. I'm also not sure but I seem to remember that it is ("SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY") which I think is extremely clever because it gets around the problem created by the fact that some people (misguided in my view) begin the week with Sunday instead of ending with it. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] if/else option for making a choice
> On Mon, Feb 18, 2013 at 10:22 AM, Niclas Rautenhaus > wrote: > >> Hello folks, >> >> ** ** >> >> I would be very pleased if someone is able to help me. >> >> I wrote a small programm, to calculate the grand total for a car. >> >> A basic price can be entered. Given that basic price, a tax peercentage >> is >> calculated and added tot he grand total. >> >> >> But unfortunately I am stuck with giving the user the choice to select >> an >> additional option! >> The extra items have got set values, but at the moment they all get >> summarized, but i want to choose. >> >> ** >> > > > greetings Niclas, and welcome to Python! while i'll let the others comment > on your code specifically, i can give some overall suggestions/guidance. > > you're trying to create an overall price calculator correct? while it's > straightforward providing a base price, the complexity in your app (and > real life) is the set of options that customers can choose from. > > in your situation, i think it would be more "Pythonic" to maintain the > extras as a vector of options and prices. you then loop through those, > prompting the user to enter Yes or No, and add either the cost or zero, > respectively. that will help keep your code less complex as well. you > would > just be maintaining a running total until the user is done with all their > selections. > > good luck! > -- wesley I'd be interested in knowing exactly what you mean by the term "vector" in the above discussion. When I saw the problem I thought dict would serve as in options = { "leather" : 1600, "alloy_wheels" : 1200, # and so on } Comments? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] subprocess module: when to _NOT_ use shell=True
I've not found anywhere a clear explanation of when not to set shell=True. If the command line must be interpreted by the shell then clearly this must be set. So the question that comes up is why not set it always? In an effort to investigate, I came up with the following script that indicates that the shell looks at only the first string in the array if the first parameter is an array rather than a string. Switching between cmd being a string vs an array and shell being set or not set gives 4 possibilities. Any comments? #!/usr/bin/env python # file : test.py (Python 2.7, NOT Python 3) # Running on Linux platform (Ubuntu.) print 'Running "tes.py"' import subprocess cmd = ["ls", "-l"] # cmd = "ls -l" p = subprocess.Popen(cmd, # shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (s_out, s_err) = p.communicate() print "Std_out returns:\n%s\nStd_err returns:\n%s\n"%\ (s_out, s_err, ) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] subprocess module: when to _NOT_ use shell=True
Thank you "Eryksun" and "EikeWek" for your responses. It is this sort of thing that begins to pull one out of the newbie into the intermediate category. I'm grateful. alex > I've not found anywhere a clear explanation of when not to set shell=True. > If the command line must be interpreted by the shell then clearly this > must be set. So the question that comes up is why not set it always? > In an effort to investigate, I came up with the following script that > indicates that the shell looks at only the first string in the array if > the first parameter is an array rather than a string. Switching between > cmd being a string vs an array and shell being set or not set gives 4 > possibilities. > Any comments? > > #!/usr/bin/env python > > # file : test.py (Python 2.7, NOT Python 3) > # Running on Linux platform (Ubuntu.) > print 'Running "tes.py"' > > import subprocess > > cmd = ["ls", "-l"] > # cmd = "ls -l" > p = subprocess.Popen(cmd, > # shell=True, > stdout=subprocess.PIPE, > stderr=subprocess.PIPE) > (s_out, s_err) = p.communicate() > print "Std_out returns:\n%s\nStd_err returns:\n%s\n"%\ > (s_out, s_err, ) > > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor