[Tutor] Detecting my own IP address?
G'day, I'm currently blundering through a script that will let me configure and then connect to PPTP VPNs from a Linux box. Just a text-based front-end to pptp-client, really. Adding in new VPN configurations was simple. Connecting is a little harder. From the command-line I would normally type: "sudo pon $TUNNEL", where TUNNEL is the name of the connection. This is followed by "sudo route add -net 192.168.1.0 netmask 255.255.255.0 dev ppp0" (as an example), once the tunnel was established. What I would really like the script to be able to do is detect when the tunnel connects, grab the IP address, and then create an appropriate route. At present, the only thing I can think of is to redirect the output of 'ifconfig' into a temporary file, then read it back in and use Python and regular expressions to try and extract the IP info from that. I could *probably* make that work... but I wouldn't feel very proud about it. Does anyone have any clues? I do prefer to figure things out for myself *cough*google*cough*, but in this case I'm not really sure where to start looking. Any help would be appreciated. Regards, ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Detecting my own IP address?
Thank you for your suggestions everyone. I do wish to parse ifconfig, as I'm specifically after the address of ppp0. At this stage, I'm only writing the script for my own machine, so the downside to parsing ifconfig does not yet apply. I'm a little curious, however. When you say 'varies depending on the operarating system', are you talking about Windows vs. Linux, or, say, Debian vs. Gentoo? Cheers, ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] "Print" behaviour inside a loop?
Hullo, Firstly, thanks to everyone who helped me find my own IP address. That was a big help. That bit is working now, and working very nicely. I am now stuck on something purely aesthetic - printing a few dots across the screen to provide a bit of feedback while the VPN tunnel is being established. def vpn_connect(choice): import time ip_addr = "" tries = 0 retries = 10 print "Connecting to %s" % (choice), os.system("pon %s" % (choice)) while ip_addr == "" and tries < retries: print "...", # This is the line causing problems time.sleep(0.5) ip_addr = get_addr() if ip_addr != '': #create the route! pass else: tries += 1 sys.exit() It works. The problem is, nothing is displayed on screen until after the connection occurs - at which point we see: "Connecting to Prodigi ... ... ... ... ... ... ... " If I remove the comma at the end of the marked line, the ellipses print every .5 seconds as desired, except they print down the screen of course! After googling around a little, I found a post that seemed to say Python won't draw the results of 'print' statements until it hits a newline. I tried using sys.stout.write('...'), but had the same problem there, too. I've also found a few progress bar classes around the web, but I not exactly want a progress bar. I just want to print '...' every few seconds until connected. Any hints? I looked up the python reference manual, but couldn't find any way to force print statements to draw. Should I be looking into threads, perhaps? Regards, ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] "Print" behaviour inside a loop?
>Just use sys.stdout.writelines(' ... ') > >Example: > >>> import sys > >>> sys.stdout.writelines ('... '); sys.stdout.writelines ('... ') > ... ... >>> > > Thank you for the suggestion Lee, but I'm afraid that doesn't work either. Same problems as described before. Max Noel hit the nail right on the head, though. I got it working with while ip_addr == "": sys.stdout.writelines("...") sys.stdout.flush() time.sleep(0.5) ip_addr = get_addr() if ip_addr != '': ... Script works like a charm now! Still rife with bugs and problems that would make it more or less useless for anyone except me - but a perfectly good, pptp config program already exists. I just made my own for education reasons. Anyone curious can view the whole thing here: http://members.optusnet.com.au/~sger/pytp I'd welcome any constructive criticism. Also, I'm storing a lot of passwords in plain text files. I hope I got all the permissions stuff right, but again, if anyone happens to spot any obvious flaws please do share. Regards, -- "Come back to the workshop and dance cosmological models with me?" - Peer, "Permutation City", by Greg Egan. Simon Gerber [EMAIL PROTECTED] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how do i pause a script ?
>Hey all, >how do i pause a script. like >print 'something' >pause a half second >print 'something else' > > Hi, I think you're looking for 'sleep' in the time module. >>> import time >>> print "something" >>> time.sleep(1) >>> print "something else" That should do what you're describing. Incidentally, 'sleep' takes a float, not an int. So you can use time.sleep(1.5) to pause for one and a half seconds, and so forth. Hope that helps! If anyone knows a better way, feel free to correct me. I've only just started to learn Python myself. -- "Come back to the workshop and dance cosmological models with me?" - Peer, "Permutation City", by Greg Egan. Simon Gerber [EMAIL PROTECTED] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] PyGTK, classes and return values?
Greetings, all. I've been stumbling my way through the PyGTK tutorial, with mixed success. So far I have been able to achieve everything I have set out to achieve, with one rather major exception. I have a class called 'AddAccountWindow' that creates a window asking for hostname, username, password, account-type. That sorta thing. When the user fills out the data and hits 'okay', it creates a class (self.account) with the required parameters. So far, so good. But now, I have no idea how to get that class *out* of AddAccountWindow. I can't seem to find any way to return it. Nor can I successfully pass anything in by reference, change it into the required class, and pass it out again. Any help would be much appreciated. Regards, -- "Come back to the workshop and dance cosmological models with me?" - Peer, "Permutation City", by Greg Egan. Simon Gerber [EMAIL PROTECTED] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Replacement for 'Find' Module
You could probably do something like this... (Note: This example is for Linux - but you can adapt it fairly easily to Windows.) # E.g. Find every .inf file on a CD-ROM. path = '/cdrom' # 'E:\\' or whatever for Windows inf_list = [] for root, dirs, files in os.walk(path): for current_file in files: if '.inf' in current_file: inf_list.append(os.path.join(root, current_file)) I, too, would be interested in knowing if anyone has a better way to do this :) You would probably combine the 'glob' module with os.walk to grab what you wanted, and build the list of files that way. Lemme know what you figure out. Cheers, On 15/08/05, Don Parris <[EMAIL PROTECTED]> wrote: > On my Windows XP box running Python 2.4, I attempted to use the 'find' > module per the example in Programming Python (Ch. 2) - i.e.: > >>>import find > >>>find.find('*') > > However, Python didn't find the find module. The docs say it's now > deprecated, but don't point to what tool should be used to replace > find. My Googling efforts haven't been fruitful so far. Could > someone please point me in the right direction? > > Don > -- > DC Parris GNU Evangelist > http://matheteuo.org/ > [EMAIL PROTECTED] > "Hey man, whatever pickles your list!" > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How can I make this run right?
I'd do it like this... And there's probably an even quicker way, if you really sat down and thought about it. n = int(raw_input("Number: ")) x = n-1 while x > 1: n *=x x -=1 print n The reason why it isn't working is because of " while x > 1: x -= 1 " When your program hits this point it stays in the while loop, subtracting 1 from x each time, but not multiplying anything anymore, until it hits break. So your program does this. Number: 4 n = 5 x = 4 t = 20 x = 3 x = 2 x = 1 BREAK. Cheers! On 15/08/05, Nathan Pinno <[EMAIL PROTECTED]> wrote: > > The following code is supposed to take in a number, and print number!: > n = int(raw_input("Number: ")) > x = n-1 > while 1: > t = n*x > while x > 1: > x -= 1 > else: > break > print t > > Why isn't it working, and how can I make it print out the correct output? > > Thanks in advance, > Nathan > --- > Early to bed, > Early to rise, > Makes a man healthy, wealthy, and wise. > --Benjamin Franklin > --- > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] OT - Newbie Anxiety
> But that was the PAST. This is FINALLY the FUTURE. And while I am a bit > disappointed those flying cars that were promised aren't here yet, we of the > future now have the luxury of white space with no downside. Whaddaya mean, no flying cars? http://www.moller.com/skycar/ Aside from that, thanks for the interested read. Cheers! -- Simon Gerber - Prodigi Solutions http://www.prodigi.com.au ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] FWD: How do I fix this error so that my exchange rates program will work?
Sorry - Forgot to reply to the list as well. -- Forwarded message -- Hi Nathan, Let's take a look at the debugger message: > Traceback (most recent call last): > File "D:\Python24\exchange.py", line 84, in -toplevel- > save_rates(rates) > File "D:\Python24\exchange.py", line 9, in save_rates > store.write(rate + '\n') > TypeError: unsupported operand type(s) for +: 'float' and 'str' Well, looks like you're trying to add a number to a string. Sorry mate, can't be done! Luckily, there's an easy fix. Change the number into a string, just for the purpose of writing to the file. Python has a very quick way of doing this. Replace this: > store.write(rate + '\n') With this: store.write(`rate` + \n') Note that these are not your regular sungle quotes. You'll find them above the tab key, under escape, on most standard keyboards. Good luck! -- Seen in the release notes for ACPI-support 0.34: 'The "I do not wish to discuss it" release * Add workaround for prodding fans back into life on resume * Add sick evil code for doing sick evil things to sick evil screensavers' -- Seen in the release notes for ACPI-support 0.34: 'The "I do not wish to discuss it" release * Add workaround for prodding fans back into life on resume * Add sick evil code for doing sick evil things to sick evil screensavers' ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Guess my number game
Hi William, Just a word of warning, you should get used to using 'raw_input()' rather than 'input()' in your progams. Why? Because input() attempts to run whatever you type in as a Python program. If you want to know why that's a problem, try running your progam. When it asks you to "Enter the number: " type in this: open('test.txt', 'w') Your program will crash. But look in the directory where you ran it, and you'll see a blank 'test.txt' document! Obviously, it's just as easy to delete files, and cause other malicious damage. Obviously, this isn't much of a problem if you're just writing a small game as a learning excercise. But it's a good habit to practice secure coding whenever possible. raw_input saves anything typed in as a string. Which is good, because you don't want people to be able to execute arbitrary code using your program. But it's bad, because you can't do mathematics with a string. So you need to use 'type casting', which you might not know about yet, to turn the string into a number. Try this instead: number = int(raw_input("Enter the number: ")) Your program will still look the same, but it'll be a lot safer. -- Seen in the release notes for ACPI-support 0.34: 'The "I do not wish to discuss it" release * Add workaround for prodding fans back into life on resume * Add sick evil code for doing sick evil things to sick evil screensavers' ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How do I fix this IndexError?
Hi Nathan, > Traceback (most recent call last): > File "D:\Python24\exchange.py", line 28, in -toplevel- > exch = pickle.load(store) > File "D:\Python24\lib\pickle.py", line 1390, in load > return Unpickler(file).load() > File "D:\Python24\lib\pickle.py", line 872, in load > dispatch[key](self) > File "D:\Python24\lib\pickle.py", line 1207, in load_appends > mark = self.marker() > File "D:\Python24\lib\pickle.py", line 888, in marker > while stack[k] is not mark: k = k-1 > IndexError: list index out of range As you can see from the traceback, the error is occuring entirely in the pickle module. Which probably means your pickle file is corrupted. Or that you're trying to load your old exch.txt file which wasn't in pickle format. Simply delete 'exch.txt' and try again. Although you'll notice your program still doesn't work, because it tries to load 'exch.txt' even if there isn't an exch.txt. You should consider rewriting your program so that it checks to see if an 'exch.txt' file exists. If it does, it unpickles it. If not, it uses your default 'rates' variables. Speaking of rates, you have two typos in your code which you also need to fix. > exch = pickle.load(store) Should be rates = pick.load(store) And similarly, > pickle.dump(exch, store) pickle.dump(rates, store) Otherwise you're not saving or loading anyhing! Cheers, -- Seen in the release notes for ACPI-support 0.34: 'The "I do not wish to discuss it" release * Add workaround for prodding fans back into life on resume * Add sick evil code for doing sick evil things to sick evil screensavers' ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How do I fix this IndexError?
Hi Nathan, I've attached a crude hack that fixes the problem. It should give you an idea of how to proceed. I've put comments next to the things I've changed. Bear in mind I'm hardly more than a beginner myself, so there are definitely better ways to do this. But it's somewhere to start, anyway. Cheers! [code] import pickle, os #LOAD THE OS MODULE def menu(): print "1. Change Canadian currency into American." print "2. Change American currency into Canadian." print "3. Change Canadian currency into Euros." print "4. Change Euros into Canadian currency." print "5. Update exchange rates." print "9. Save and Exit" def exchange_update(): print "1. Update Canadian to US rate." print "2. Update US to Canadian rate." print "3. Update Canadian to Euro rate." print "4. Update Euro to Canadian update." print "5. Main menu" def menu_choice(): return int(raw_input("Which option? ")) print "The Currency Exchange Program" print "By Nathan Pinno" if os.path.exists('exch.txt'): # Check to see if 'exch.txt' exists store = open('exch.txt', 'rb') # Only open the file if it exists rates = pickle.load(store)# Save as 'rates', not 'exch' store.close() else: # If there's no exch.txt file, use these default rates. rates = {'can_us' : 0.80276, 'us_can' : 1.245702, 'can_euro' : 1.488707, 'euro_can' : 0.671724} while 1: menu() menu_option = menu_choice() if menu_option == 1: can = float(raw_input("Canadian $")) print "US $",can*rates['can_us'] elif menu_option == 2: us = float(raw_input("US $")) print "CAN $",us*rates['us_can'] elif menu_option == 3: can = float(raw_input("CAN $")) print "Euros",can*rates['can_euro'] elif menu_option == 4: euro = float(raw_input("Euros")) print "CAN $",euro*rates['euro_can'] elif menu_option == 5: while 1: exchange_update() sub = menu_choice() if sub == 1: new_can = float(raw_input("New CAN-US Exchange rate: ")) rates['can_us'] = new_can print "Exchange rate successfully updated!" elif sub == 2: new_us = float(raw_input("New US-CAN Exchange rate: ")) rates['us_can'] = new_us print "Exchange rate successfully updated!" elif sub == 3: new_cxr = float(raw_input("New CAN-Euro Exchange rate: ")) rates['can_euro'] = new_cxr print "Exchange rate successfully updated!" elif sub == 4: new_euro = float(raw_input("New Euro-CAN Exchange rate: ")) rates['euro_can'] = new_euro print "Exchange rate successfully updated!" elif sub == 5: break elif menu_option == 9: store = open("exch.txt", 'wb') #save pickle.dump(rates, store) # Save 'rates' variable, not 'exch'. store.close() break print "Goodbye." -- Seen in the release notes for ACPI-support 0.34: 'The "I do not wish to discuss it" release * Add workaround for prodding fans back into life on resume * Add sick evil code for doing sick evil things to sick evil screensavers' ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] new to linux and I cannot find some python things
> Hi all, > > I'm a week or so into having switched from WinXP to linux (ubuntu > breezy). There is a lot to learn about the differences in the OS'es > and that's just fine. Excellent! Another Ubuntu Breezy user here. If there's anything Ubuntu I can help you with, drop me an e-mail and I'll do what I can to help. > But, a couple of things have been in my way with Python. Most notably, > I don't know how one browses the documentation. On Windows, I just > fired up the .chm (I think cmh--at any rate, the compiled help file.) Yeah, chm. Incidentally, there's a chm reader for Linux. Very primative, but it works in a pinch. Look for 'xchm' in the Universe repository. > I have installed the docs on the linux side and they can be found by > python: > > >>> help() > > help> NONE Nah, that's part of core Python. Nothing to do with the 'python-doc' package you installed. > I assume there is some linux facility for documentation browsing that > beats importing modules and accessing docstrings. I'd work it out > eventually, but a timesaving pointer would be appreciated. Firefox! file:///usr/share/doc/python2.4/html/index.html The python-doc package is just an offline version of http://www.python.org/doc/2.4.2/ You can also probably find a copy of the book 'Dive into Python' here: file:///usr/share/doc/diveintopython/html/index.html I know Hoary installed it by default. Not sure about Breezy, since I just did a dist-upgrade from Hoary. As a rule, with Ubuntu (and most other Linux distros), the documentation goes under /usr/share/doc/. But you can always check to see exactly what a package has put where. From the command-line, just type 'dpkg -L python-doc'. Hope that helps, -- Seen in the release notes for ACPI-support 0.34: 'The "I do not wish to discuss it" release * Add workaround for prodding fans back into life on resume * Add sick evil code for doing sick evil things to sick evil screensavers' ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Finding bottom level directories, and command-line arguments
G'day Tutors, I watch many different TV shows on my PC, as many of us do. But I am sick and tired of forgetting which episode I was up to. So, in a prodigious effort to avoid ever using, say, a pen, I am working on a script to take over some of my brain's memory handling. When complete, I will simply be able to type, for example, 'play family_guy' from the command line and it will automatically launch the next unwatched episode. So I was wondering if anyone has an efficient, Pythonesque way of creating a dictionary of all bottom level directories in a given path. At the moment I'm doing this \/ to find all directories in a given directory. But I really want to dig down and find all bottom level directories. --- def build_dir_index(): for item in os.listdir(vid_path): if os.path.isdir(item): # Ask user what to do with this directory... I know about os.walk and os.path.walk, but I'm not sure how to use them effectively to get a list of all bottom level directories. Otherwise, I've also considered using the above listdir/isdir recursively to build up lists of subdirectories, and tag all directories that return an empty list as bottom-level. But I just get the feeling there's a simple, elegant way of doing this that I'm missing. Second question - anyone have some good pointers/links about how to parse command line arguments effectively? I.e. perhaps build a dictionary of all options and their values, so I can deal with them appropriately? Cheers, -- Seen in the release notes for ACPI-support 0.34: 'The "I do not wish to discuss it" release * Add workaround for prodding fans back into life on resume * Add sick evil code for doing sick evil things to sick evil screensavers' ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Finding bottom level directories, and command-line arguments
Hi Danny, Thanks for the advice. > It might be interesting to write a function that takes an arbitrary > directory, and returns 'True' if that directory is a bottom-level > directory. Can you write this function? I've got this: --- def isBottomDir(path): for item in os.listdir(path): if os.path.isdir(os.path.join(path,item)): return False return True --- Is that an acceptable way of doing this? I've been reading http://thedailywtf.com for a month or so now - and though I've yet to see a Python example cross their pages, I'm rather terrified of becoming the first :) To iterate through the directories, the following works for me: --- for root, dirs, files in os.walk('~\Test'): if test_dir.isBottomDir(root) == True: print root --- Is it worthwhile trying to write my own recursive function for this? Or can I safely leave this task to to os.walk without inviting ridicule from the programming community. > There's a module that does this called 'optparse': > > http://www.python.org/doc/lib/module-optparse.html > > Try reusing that first, because it's been fairly well exercised and tuned > to what people expect from an option parser. Excellent. That looks like what I was looking for. Thanks! -- Seen in the release notes for ACPI-support 0.34: 'The "I do not wish to discuss it" release * Add workaround for prodding fans back into life on resume * Add sick evil code for doing sick evil things to sick evil screensavers' ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Finding bottom level directories, and command-line arguments
Hi Danny, > That web site (http://thedailywtf.com) is amusing in its way, but my > problem with it is that so many of the people there enjoy mocking others > in a mean-spirited and immature way. Programming well is a hard thing. > The adolescent posturing I see there isn't admirable to me. It's also very > sad to see that, for any given bad code, there's a lot more really bad > responses. So my feelings are mixed about it, in the same sort of way > that I have misgivings toward Slashdot. *grin* Yes... Slashdot. *shudder*. I've had two of my articles Slashdotted, and both times it left quite a bruise. If it happens again, I have resolved to simply not read the comments. Like Othello said, there are some things we are better off not knowing :) > It's perfectly ok to take advantage of os.walk(); I like this code. Excellent. But based on Kent's comment, I have discovered that -- for root, dirs, files in os.walk(prog_variables['vid_path']): if dirs == []: print root -- does the same thing. Cheers, -- Seen in the release notes for ACPI-support 0.34: 'The "I do not wish to discuss it" release * Add workaround for prodding fans back into life on resume * Add sick evil code for doing sick evil things to sick evil screensavers' ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] [OT] Shells
> It looks promising, although without good command line editing and the > ability to create active GUIs it will be limited. But then, you can't do GUIs > in > bash either... There's always Zenity. Which of course isn't a built in part of the Bash shell. But it does allow you to create simple GUI dialogues to use with shell scripts. And most distro's include it as part of the default installation. -- Seen in the release notes for ACPI-support 0.34: 'The "I do not wish to discuss it" release * Add workaround for prodding fans back into life on resume * Add sick evil code for doing sick evil things to sick evil screensavers' ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor