[Tutor] help
i am only a novice and just started programming.. i am having trouble running a .py file in the command prompt.. if anyone of you could help? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help
On Mon, Mar 29, 2010 at 7:30 AM, Oshan Modi modi.os...@gmail.com wrote: i am only a novice and just started programming.. i am having trouble running a .py file in the command prompt.. if anyone of you could help? How are you trying to run it ?? -- Vishwajeet Singh +91-9657702154 | dextrou...@gmail.com | http://singhvishwajeet.com | http://bootstraptoday.com Twitter: http://twitter.com/vishwajeets | LinkedIn: http://www.linkedin.com/in/singhvishwajeet ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help
Oshan Modi wrote: i am only a novice and just started programming.. i am having trouble running a .py file in the command prompt.. if anyone of you could help? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor If you are using Windows and just installed Python and then tried to execute your script with python script_name.py and it tells you it cannot find the program to execute then it is likely your environment settings as the Python installer never seems to set up your path properly. Go to My Computer - Advanced Settings - Environment Settings - Double-Click on path - Add your python path eg. c:\python26 at the end - Restart and it should work. -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help
On Mon, 29 Mar 2010 01:00:45 pm Oshan Modi wrote: i am only a novice and just started programming.. i am having trouble running a .py file in the command prompt.. if anyone of you could help? Are you running Linux or Mac? At the command prompt, run: python myfile.py and report any errors. You can also run: which python and see what it says. -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help
Forwarding to the list. Martijn wrote: On Tue, Mar 30, 2010 at 12:15 PM, Christian Witts cwi...@compuscan.co.za mailto:cwi...@compuscan.co.za wrote: Oshan Modi wrote: i am only a novice and just started programming.. i am having trouble running a .py file in the command prompt.. if anyone of you could help? ___ Tutor maillist - Tutor@python.org mailto:Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor If you are using Windows and just installed Python and then tried to execute your script with python script_name.py and it tells you it cannot find the program to execute then it is likely your environment settings as the Python installer never seems to set up your path properly. Go to My Computer - Advanced Settings - Environment Settings - Double-Click on path - Add your python path eg. c:\python26 at the end I think it should be capitalized, but I'm not sure, so: For Python 2.6: C:\Python26 For Python 3.1: C:\Python31 If you didn't install it on the C: drive, change C: to the drive letter you installed it on. Also, check if there's a semicolon ( ; ) at the end of the path before you add the python path, if there isn't, add it first. Now you can continue :) Martijn - Restart and it should work. -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org mailto:Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Windows is case insensitive when it comes to paths and executables names so it shouldn't matter. The semi-colon I forgot to mention though. :) -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help
Oshan Modi wrote: I have Windows 7 and am using python 2.6.. I added python.exe's address in the path option under enviromental variables.. i can run python in command prompt.. its just that i dont know to make it execute a file directly rather than typing the whole program again and again.. On Tue, Mar 30, 2010 at 4:55 PM, Christian Witts cwi...@compuscan.co.za mailto:cwi...@compuscan.co.za wrote: Forwarding to the list. Martijn wrote: On Tue, Mar 30, 2010 at 12:15 PM, Christian Witts cwi...@compuscan.co.za mailto:cwi...@compuscan.co.za mailto:cwi...@compuscan.co.za mailto:cwi...@compuscan.co.za wrote: Oshan Modi wrote: i am only a novice and just started programming.. i am having trouble running a .py file in the command prompt.. if anyone of you could help? ___ Tutor maillist - Tutor@python.org mailto:Tutor@python.org mailto:Tutor@python.org mailto:Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor If you are using Windows and just installed Python and then tried to execute your script with python script_name.py and it tells you it cannot find the program to execute then it is likely your environment settings as the Python installer never seems to set up your path properly. Go to My Computer - Advanced Settings - Environment Settings - Double-Click on path - Add your python path eg. c:\python26 at the end I think it should be capitalized, but I'm not sure, so: For Python 2.6: C:\Python26 For Python 3.1: C:\Python31 If you didn't install it on the C: drive, change C: to the drive letter you installed it on. Also, check if there's a semicolon ( ; ) at the end of the path before you add the python path, if there isn't, add it first. Now you can continue :) Martijn - Restart and it should work. -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org mailto:Tutor@python.org mailto:Tutor@python.org mailto:Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Windows is case insensitive when it comes to paths and executables names so it shouldn't matter. The semi-colon I forgot to mention though. :) -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org mailto:Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Is this perhaps what you want to do ? http://www.python.org/doc/faq/windows/#how-do-i-make-python-scripts-executable -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help
Simple; just write python program.py in your command line :) On Tue, Mar 30, 2010 at 2:08 PM, Christian Witts cwi...@compuscan.co.zawrote: Oshan Modi wrote: I have Windows 7 and am using python 2.6.. I added python.exe's address in the path option under enviromental variables.. i can run python in command prompt.. its just that i dont know to make it execute a file directly rather than typing the whole program again and again.. On Tue, Mar 30, 2010 at 4:55 PM, Christian Witts cwi...@compuscan.co.zamailto: cwi...@compuscan.co.za wrote: Forwarding to the list. Martijn wrote: On Tue, Mar 30, 2010 at 12:15 PM, Christian Witts cwi...@compuscan.co.za mailto:cwi...@compuscan.co.za mailto:cwi...@compuscan.co.za mailto:cwi...@compuscan.co.za wrote: Oshan Modi wrote: i am only a novice and just started programming.. i am having trouble running a .py file in the command prompt.. if anyone of you could help? ___ Tutor maillist - Tutor@python.org mailto:Tutor@python.org mailto:Tutor@python.org mailto:Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor If you are using Windows and just installed Python and then tried to execute your script with python script_name.py and it tells you it cannot find the program to execute then it is likely your environment settings as the Python installer never seems to set up your path properly. Go to My Computer - Advanced Settings - Environment Settings - Double-Click on path - Add your python path eg. c:\python26 at the end I think it should be capitalized, but I'm not sure, so: For Python 2.6: C:\Python26 For Python 3.1: C:\Python31 If you didn't install it on the C: drive, change C: to the drive letter you installed it on. Also, check if there's a semicolon ( ; ) at the end of the path before you add the python path, if there isn't, add it first. Now you can continue :) Martijn - Restart and it should work. -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org mailto:Tutor@python.org mailto:Tutor@python.org mailto:Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Windows is case insensitive when it comes to paths and executables names so it shouldn't matter. The semi-colon I forgot to mention though. :) -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org mailto:Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Is this perhaps what you want to do ? http://www.python.org/doc/faq/windows/#how-do-i-make-python-scripts-executable -- Kind Regards, Christian Witts ___ 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] USB Access
Hi, I was wondering if anyone could point me to Python modules or example code for accessing USB connected devices. I would like to get as close to the hardware as possible with Python. I would like to be able to monitor as well as control USB connected devices. I've looked at the missile launcher code by Pedram Amini at dvlabs.tippingpoint.com, but am looking to see what else has been done in this area. thanks, Marc Sent from my Verizon Wireless BlackBerry ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Script Feedback
As a self-taught Python user I am still looking for insight on the most pythonic and programmatically-friendly way of accomplishing a given task. In this case, I have written a script that will perform a “clean bzip2″ of a directory (or directories). Mac OS X (via AFP and netatalk, in my case) tends leaves a bunch of ugly files/directories hanging around and I would rather not include them in my compressed tar file. In writing the script, though, I ran into some questions and I am not sure what the recommended approach would be. The script works, as it is, but I feel its a little hacked together and also a little limited in its application. There is something to be said for programs that just work (this does) but I want to take it a little further as an educational endeavor and would like it to appear robust, future-thinking, and pythonic. My initial questions are: 1. Is there a better way to implement a --quiet flag? 2. I am not very clear on the use of Exceptions (or even if I am using it in a good way here) — is what I have done the right approach? 3. Finally, in general: any feedback on how to improve this? (I am thinking, just now, that the script is only suitable for a command line usage, and couldn’t be imported by another script, for example.) Any feedback is greatly appreciated. Writing a script like this is a good learning tool (for me, at least). I have posted this email online if you want to see the script with pretty code formatting: http://blog.damontimm.com/python-script-clean-bzip/ Thanks for any insight you may provide. Damon Script follows #! /usr/bin/env python '''Script to perform a clean bzip2 on a directory (or directories). Removes extraneous files that are created by Apple/AFP/netatalk before compressing. ''' import os import tarfile from optparse import OptionParser IGNORE_DIRS = ( '.AppleDouble', ) IGNORE_FILES = ('.DS_Store', ) class DestinationTarFileExists(Exception): '''If the destination tar.bz2 file already exists.''' def ignore_walk(directory): '''Ignore defined files and directories when doing the walk.''' for dirpath, dirnames, filenames in os.walk(directory): dirnames[:] = [ dn for dn in dirnames if dn not in IGNORE_DIRS ] filenames[:] = [ fn for fn in filenames if fn not in IGNORE_FILES ] yield dirpath, dirnames, filenames def tar_bzip2_directories(directories): for directory in directories: file_name = '-'.join(directory.split(' ')) tar_name = file_name.replace('/','').lower() + .tar.bz2 if os.path.exists(tar_name): raise DestinationTarFileExists() if not options.quiet: print 'Compressing files into: ' + tar_name tar = tarfile.open(tar_name, 'w:bz2') for dirpath, dirnames, filenames in ignore_walk(directory): for file in filenames: if not options.quiet: print os.path.join(dirpath, file) tar.add(os.path.join(dirpath, file)) tar.close() if __name__ == __main__: parser = OptionParser(usage=%prog [options: -q ] [directory]) parser.add_option(-q, --quiet, action=store_true, dest=quiet) options, args = parser.parse_args() directories = [] for arg in args: if os.path.isdir(arg): directories.append(arg) else: print Ingoring: %s (it's not a directory). % arg try: tar_bzip2_directories(directories) except DestinationTarFileExists: print A tar file already exists this this directory name. print Move or rename it and try again. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] USB Access
On Tue, Mar 30, 2010 at 9:01 AM, Marc m...@marcd.org wrote: Hi, I was wondering if anyone could point me to Python modules or example code for accessing USB connected devices. I would like to get as close to the hardware as possible with Python. I would like to be able to monitor as well as control USB connected devices. I've looked at the missile launcher code by Pedram Amini at dvlabs.tippingpoint.com, but am looking to see what else has been done in this area. I've used pyserial, I believe, to directly access the usb. Here's the important connection bits of my code: import serial class pyDuin: ser = serial.Serial() def __init__(self, port=/dev/ttyUSB0, baud=115200, timeout=0): self.ser.baudrate = baud self.ser.port = port self.ser.timeout = timeout def ready(self): self.ser.write(%c % 41) def open(self): self.ser.open() if not self.ser.isOpen(): print Error, not able to open serial connection on %s % \ (self.ser.port, ) - I was using it to connect to my arduino. If you'd like the rest of the source, let me know. HTH, Wayne ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] How do I find information about a Python object.
Hi, I've downloaded IDLE python for windows. I've also downloaded Eclipse with the python addition. I have simple programs that will run on both IDLE and Eclipse. How do I get more information about a object/variable, such as proc in the example below. For example, if I execute the following: proc = subprocess.Popen(['C:\\Progra~1\\putty\\plink','Catt'], shell=False) I can remote log into our Linux machine named 'Catt'. How do I find a list of attributes for the object/variable proc? I've tried subprocess.__doc__ and subprocess.Popen.__doc__. Random Googling shows that there are things like process identification numbers available - such as proc.pid. How do I find the other options? Thanks, Mike ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How do I find information about a Python object.
You might want to check out the below chapter from Dive Into Python: http://diveintopython.org/power_of_introspection/index.html ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Remote access from Windows PC to a Linux box
Hi, I'm trying to connect to a Linux box from my Windows machine and execute a series of commands - (ls, pwd, cat 'somefile', etc...). I'm using Putty to do the ssh and have set up with Putty's Pagent agent to allow me to enter a passphrase once per session to handle security keys between the two boxes (so, no passwords needed for my remote scripts). I have code that will give me a remote prompt on the Linux machine where I can manually enter commands. This works great, but I want a script to always execute the same series of commands without having to do so manually. I also have code that will execute a single command like cat a file and write the ouput to a new file. However, when I try to use the communicate object in subprocess, my window hangs. Here is my working code: # module name data_collect.y # import subprocess def simp_tst0(s_name): # Opens a remote connection to s_name and gives a prompt. # Works great for executing linux commands. # Does not exit gracefully when you type exit. The python # prompt hangs when it gets to the r.communicate command # cmmnd_0=C:\\Progra~1\\putty\\plink %s % s_name r = subprocess.Popen(%s % cmmnd_0,shell=False) (r_stdout, r_stderr) = r.communicate(dir) #status=r.poll() #Locks up if you try to poll here print r_stdout return r def cat_remote(s_name, file2cat): # This simple test file opens a remote connection to s_name, does a cat on # file file2cat and writes the cat to an output file (out2.txt). cmmnd_2=C:\\Progra~1\\putty\\plink %s cat %s % (s_name, file2cat) q = subprocess.Popen(%s % cmmnd_2, stdout=open('out2.txt','w')) def simp_tst3(s_name): # Runs the initial subprocess.Popen command - creates proc. # Hangs when you try to use proc.communicate proc = subprocess.Popen(['C:\\Progra~1\\putty\\plink','Sula'], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, ) #Either of the next two commands cause window to hang #proc.stdin.write(dir) #(stdout_value, stderr_value) = proc.communicate(input=dir)[0] return proc Thanks, Mike ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Script Feedback
On Wed, 31 Mar 2010 01:27:43 am Damon Timm wrote: [...] My initial questions are: 1. Is there a better way to implement a --quiet flag? I usually create a function print_ or pr, something like this: def print_(obj, verbosity=1): if verbosity 0: print obj and then have a variable verbosity which defaults to 1 and is set to 0 if the user passes the --quiet flag. Then in my code, I write: print_(this is a message, verbosity) 2. I am not very clear on the use of Exceptions (or even if I am using it in a good way here) — is what I have done the right approach? Hmmm... perhaps. Usually, you want to catch an exception in order to try an alternative approach, e.g.: try: result = somefunction(x) except ValueError: # Fall back on some other approach. result = something else Occasionally, you want to catch an exception just to ignore it. It's generally *not* a good idea to catch an exception just to print an error message and then exit, as you do. Just let the exception propagate, and Python will print a rich and detailed traceback together with your error message. However, a reasonable exception (pun intended) for that rule is to hide the traceback from the users, who probably can't do anything about it, and would only get confused by the details. So you want to have your functions and classes raise exceptions, and the application layer (the user interface) catch them. So I would do something like this (untested). In your function code: ... if os.path.exists(tar_name): msg = A tar file already exists this this directory name. \ Move or rename it and try again. raise DestinationTarFileExists(msg) Then your application layer looks something like: if __name__ == '__main__': try: ... except KeyboardInterrupt: sys.exit(1) except DestinationTarFileExists, e: print e.message sys.exit(2) # Any other exception is unexpected, so we allow Python # to print the full traceback as normal. 3. Finally, in general: any feedback on how to improve this? (I am thinking, just now, that the script is only suitable for a command line usage, and couldn’t be imported by another script, for example.) Separate the underlying functionality from the application-level code. These functions should NEVER print anything: they do all communication through call-backs, or by returning a value, or raising an exception. E.g.: def tar_bzip2_directories(directories, callback=None): for directory in directories: file_name = '-'.join(directory.split(' ')) tar_name = file_name.replace('/','').lower() + .tar.bz2 if os.path.exists(tar_name): raise DestinationTarFileExists(errmsg) if callback is not None: callback(directory, filename, tarname) ... Create a main function that runs your application: def main(argv=None, callback=None): if argv is None: argv = sys.argv process_command_line_options(argv) if callback is None: def callback(dirname, filename, tarname): print Processing ... tar_bzip2_directories(...) if __name__ == '__main__': try: main() except ... # as above Now anyone can import the module and call individual functions, or even call main, or they can run it as a script. Hope this helps, -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Need some help on How to Think Like a Computer Scientist: Learning with Python exercise
Hello All, I am competely new in Python programming. When i reading Chapter 4 in How to Think Like a Computer Scientist: Learning with Python , I am stuck in the exercise 4. Here is the question: Enter the following expressions into the Python shell: 1. True or False 2. True and False 3. not(False) and True 4. True or 7 5. False or 7 6. True and 0 7. False or 8 8. happy and sad 9. happy or sad 10. and sad 11. happy and Analyze these results. What observations can you make about values of different types and logical operators? Can you write these observations in the form of simple rules about and and or expressions? I have no problem with 1-4, but compelely wrong with the rest. Like question 5, i throught the answer is True, but when i type it in IDLE, I got 7 instead, question 8 happy' and 'sad', my answer is True, but the answer is 'happy'. Can you please tell me why i am wrong. I really appreciate any assistance you can give. Thanks___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help
On 3/28/2010 10:00 PM, Oshan Modi wrote: i am only a novice and just started programming.. i am having trouble running a .py file in the command prompt.. if anyone of you could help? Please learn how to ask questions. In a situation like this we'd like to know what operating system you are using, which version of Python, what you are typing at the command prompt, and what happens. Otherwise we must guess, as several of us have already done. This wastes all our time. Please post answers to: operating system version of Python what you type at the command prompt what happens -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help (Oshan Modi) with command prompt
You didn't say what operating system, but in general terms, the python application has to know how to find your python module, say 'foo.py'. This means that the directory where foo.py is located must be on the system path or PYTHONPATH. One simple way to do this is to navigate at the command prompt to the directory that contains your module, and then execute python foo.py. In this way python uses the current directory as the current working directory (cwd); python starts looking in this directory for your module. Another way is to examine what's on your system path. At the command prompt, launch python and then enter these two commands: import sys for i in sys.path: print i You'll get a list something like this. This list is where python is looking for foo.py. If not in one of these directories, python probably won't find your module (in general). C:\Python25\Lib\idlelib C:\Python25\lib\site-packages\ets-3.2.0-py2.5.egg C:\Python25\lib\site-packages\etsdevtools-3.0.2-py2.5-win32.egg C:\Python25\lib\site-packages\etsprojecttools-0.5.0-py2.5.egg C:\Python25\lib\site-packages\mayavi-3.2.0-py2.5-win32.egg C:\Python25\lib\site-packages\scimath-3.0.3-py2.5-win32.egg C:\Python25\lib\site-packages\setupdocs-1.0.2-py2.5.egg C:\Python25\lib\site-packages\traits-3.1.0-py2.5-win32.egg C:\WINNT\system32\python25.zip C:\Python25\DLLs C:\Python25\lib C:\Python25\lib\plat-win C:\Python25\lib\lib-tk C:\Python25 C:\Python25\lib\site-packages C:\Python25\lib\site-packages\itk\module\Python C:\Python25\lib\site-packages\PIL C:\Python25\lib\site-packages C:\Python25\lib\site-packages\gtk-2.0 C:\Python25\lib\site-packages\win32 C:\Python25\lib\site-packages\win32\lib C:\Python25\lib\site-packages\Pythonwin Hunt ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Remote access from Windows PC to a Linux box
You can have a look @ paramiko library. http://www.lag.net/paramiko/ On 30-Mar-2010, at 9:59 PM, Mike Baker wrote: Hi, I'm trying to connect to a Linux box from my Windows machine and execute a series of commands - (ls, pwd, cat 'somefile', etc...). I'm using Putty to do the ssh and have set up with Putty's Pagent agent to allow me to enter a passphrase once per session to handle security keys between the two boxes (so, no passwords needed for my remote scripts). I have code that will give me a remote prompt on the Linux machine where I can manually enter commands. This works great, but I want a script to always execute the same series of commands without having to do so manually. I also have code that will execute a single command like cat a file and write the ouput to a new file. However, when I try to use the communicate object in subprocess, my window hangs. Here is my working code: # module name data_collect.y # import subprocess def simp_tst0(s_name): # Opens a remote connection to s_name and gives a prompt. # Works great for executing linux commands. # Does not exit gracefully when you type exit. The python # prompt hangs when it gets to the r.communicate command # cmmnd_0=C:\\Progra~1\\putty\\plink %s % s_name r = subprocess.Popen(%s % cmmnd_0,shell=False) (r_stdout, r_stderr) = r.communicate(dir) #status=r.poll() #Locks up if you try to poll here print r_stdout return r def cat_remote(s_name, file2cat): # This simple test file opens a remote connection to s_name, does a cat on # file file2cat and writes the cat to an output file (out2.txt). cmmnd_2=C:\\Progra~1\\putty\\plink %s cat %s % (s_name, file2cat) q = subprocess.Popen(%s % cmmnd_2, stdout=open('out2.txt','w')) def simp_tst3(s_name): # Runs the initial subprocess.Popen command - creates proc. # Hangs when you try to use proc.communicate proc = subprocess.Popen(['C:\\Progra~1\\putty\\plink','Sula'], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, ) #Either of the next two commands cause window to hang #proc.stdin.write(dir) #(stdout_value, stderr_value) = proc.communicate(input=dir)[0] return proc Thanks, Mike ___ 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] Script Feedback
On Tue, 30 Mar 2010 10:27:43 -0400 Damon Timm damont...@gmail.com wrote: As a self-taught Python user I am still looking for insight on the most pythonic and programmatically-friendly way of accomplishing a given task. In this case, I have written a script that will perform a “clean bzip2″ of a directory (or directories). Mac OS X (via AFP and netatalk, in my case) tends leaves a bunch of ugly files/directories hanging around and I would rather not include them in my compressed tar file. In writing the script, though, I ran into some questions and I am not sure what the recommended approach would be. The script works, as it is, but I feel its a little hacked together and also a little limited in its application. There is something to be said for programs that just work (this does) but I want to take it a little further as an educational endeavor and would like it to appear robust, future-thinking, and pythonic. Very good point of view, imo. Be aware that some of the notes below are personal opinions. My initial questions are: 1. Is there a better way to implement a --quiet flag? I don't think so. 2. I am not very clear on the use of Exceptions (or even if I am using it in a good way here) — is what I have done the right approach? You can consider exceptions, in general, as a kind of intra-program (interruption-) signal system. When an exception occurs, the normal execution flow is stopped, and the program branches to a special routine designed to cope with the signal -- if any. Else it stops with a message on the terminal (actually on stderr). There are python builtin exception types, most errors; if you don't catch them, then the user gets the kind of error message you're probably familiar with ;-) If you do, by wrapping the potentially interrupting bit of code into a try...except construct, then the occurrence of an error lets the program jump into the except routine: this is a sophisticated and specialised goto. You can design your own exception types that work the same way. Just record needed info in __init__ and write a meaningful message in __str__ (see below). Custom exception types can be used for (1) real errors = abnormal cases (2) exceptional, but normal, cases (like in your case) (3) any need for signaling between separate parts of your code. 3. Finally, in general: any feedback on how to improve this? (I am thinking, just now, that the script is only suitable for a command line usage, and couldn’t be imported by another script, for example.) Yo. Just do it! (the if __name__==__main__: part won't be executed on import -- write a func, eg clean(), that can be called from importing code -- then when it runs stand-alone the main part could just call it after parsing the command-line args) Any feedback is greatly appreciated. Writing a script like this is a good learning tool (for me, at least). I have posted this email online if you want to see the script with pretty code formatting: http://blog.damontimm.com/python-script-clean-bzip/ Thanks for any insight you may provide. Damon Script follows #! /usr/bin/env python '''Script to perform a clean bzip2 on a directory (or directories). Removes extraneous files that are created by Apple/AFP/netatalk before compressing. ''' import os import tarfile from optparse import OptionParser IGNORE_DIRS = ( '.AppleDouble', ) IGNORE_FILES = ('.DS_Store', ) +++ for using constants class DestinationTarFileExists(Exception): '''If the destination tar.bz2 file already exists.''' def __init__(self, filename): self.filename = filename def __str__(self, filename): ''' (just an example) ''' return 'Destination tar file %s already exists.' %(self.filename) By defining the magic methods above, you store relevant info about an exception, and get an output format for it. __str__ is doubly magic for an exception, because (in addition to define its str(), which can often be useful), it's also automatically output when the exception falls through uncaught (written after the exception type). def ignore_walk(directory): '''Ignore defined files and directories when doing the walk.''' for dirpath, dirnames, filenames in os.walk(directory): dirnames[:] = [ dn for dn in dirnames if dn not in IGNORE_DIRS ] filenames[:] = [ fn for fn in filenames if fn not in IGNORE_FILES ] yield dirpath, dirnames, filenames First, it seems you use [:] only to preserves the object identity so that it remains a generator. But it may be better (at least clearer for me) to filter and transform the generation process so as to get what you actually need, I guess: iterating on (dirpath,filename) pairs. If I'm right on this, maybe try to figure out how do that. I would call the func eg filtered_dir_walk or relevant_dir_walk. def tar_bzip2_directories(directories): for directory in directories:
Re: [Tutor] Script Feedback
Hello Denis Steven - Thanks for your replies. I have taken another stab at things to try and bring it a little further up to snuff ... some more comments/thoughts follow ... On Tue, Mar 30, 2010 at 12:57 PM, Steven D'Aprano st...@pearwood.info wrote: I usually create a function print_ or pr, something like this: def print_(obj, verbosity=1): if verbosity 0: print obj and then have a variable verbosity which defaults to 1 and is set to 0 if the user passes the --quiet flag. Then in my code, I write: print_(this is a message, verbosity) Your suggestion prompted me to remember having looked into this earlier (and found an old thread of mine) -- some folks had recommended using the logging module -- which I have implemented in round two (seems to work). I think it accomplishes the same thing that you are suggesting, only using one of Python's built-ins. On Tue, Mar 30, 2010 at 12:57 PM, Steven D'Aprano st...@pearwood.info wrote: Separate the underlying functionality from the application-level code. These functions should NEVER print anything: they do all communication through call-backs, or by returning a value, or raising an exception. I tried to implement this, however, I am not sure how the 'callback' works ... is that just a function that a user would pass to *my* function that gets called at the end of the script? Also, I tried to separate out the logic a little so the functions make more sense ... I think I may remove the 'ignore_walk' function and just add it to the tar_bz2_directory function (see below) ... but am still unclear about the callback concept. 2010/3/30 spir ☣ denis.s...@gmail.com: First, it seems you use [:] only to preserves the object identity so that it remains a generator. But it may be better (at least clearer for me) to filter and transform the generation process so as to get what you actually need, I guess: iterating on (dirpath,filename) pairs. If I'm right on this, maybe try to figure out how do that. I would call the func eg filtered_dir_walk or relevant_dir_walk. I am not sure where I first got this 'ignore_walk' bit but I do remember taking it from another program of mine ... to be honest, though, I am rethinking its use and may implement it using fnmatch testing so that I may implement wildcards (eg, *.pyc) ... right now, it won't match wildcards and that might be helpful. Again, thank you both for your feedback. I made some changes tonight (posted below) and also updated the changes on: http://blog.damontimm.com/python-script-clean-bzip/ (if you want pretty colors). Damon CODE BELOW --- #! /usr/bin/env python '''Script to perform a clean bzip2 on a directory (or directories). Removes extraneous files that are created by Apple/AFP/netatalk before compressing. ''' import os import tarfile import logging from optparse import OptionParser # Default files and directories to exclude from the bzip tar IGNORE_DIRS = ('.AppleDouble',) IGNORE_FILES = ('.DS_Store',) class DestinationTarFileExists(Exception): '''If the destination tar.bz2 file already exists.''' def ignore_walk(directory, ignore_dirs=None, ignore_files=None): '''Ignore defined files and directories when doing the walk.''' # TODO: this does not currently take wild cards into account. For example, # if you wanted to exclude *.pyc files ... should fix that. Perhaps # consider moving this entirely into the below function (or making it more # reusable for other apps). for dirpath, dirnames, filenames in os.walk(directory): if ignore_dirs: dirnames[:] = [dn for dn in dirnames if dn not in ignore_dirs] if ignore_files: filenames[:] = [fn for fn in filenames if fn not in ignore_files] yield dirpath, dirnames, filenames def tar_bzip2_directory(directory, ignore_dirs=IGNORE_DIRS, ignore_files=IGNORE_FILES ): '''Takes a directory and creates a tar.bz2 file (based on the directory name). You can exclude files and sub-directories as desired.''' file_name = '-'.join(directory.split(' ')) tar_name = file_name.replace('/','').lower() + .tar.bz2 if os.path.exists(tar_name): msg = (The file %s already exists. + Please move or rename it and try again.) % tar_name raise DestinationTarFileExists(msg) tar = tarfile.open(tar_name, 'w:bz2') for dirpath, dirnames, filenames in ignore_walk(directory, ignore_dirs, ignore_files): for file in filenames: logging.info(os.path.join(dirpath, file)) tar.add(os.path.join(dirpath, file)) tar.close() def main(args=None, callback=None): directories = [] for arg in args: if os.path.isdir(arg): directories.append(arg) else: logging.ERROR(Ingoring: %s (it's not a directory). % arg) for dir in directories: try: tar_bzip2_directory(dir)
Re: [Tutor] Need some help on How to Think Like a Computer Scientist: Learning with Python exercise
On 03/31/2010 04:00 AM, Yahoo Mail wrote: Hello All, I am competely new in Python programming. When i reading Chapter 4 in How to Think Like a Computer Scientist: Learning with Python , I am stuck in the exercise 4. Here is the question: Enter the following expressions into the Python shell: 1. True or False 2. True and False 3. not(False) and True 4. True or 7 5. False or 7 6. True and 0 7. False or 8 8. happy and sad 9. happy or sad 10. and sad 11. happy and Analyze these results. What observations can you make about values of different types and logical operators? Can you write these observations in the form of simple /rules/ about and and or expressions? I have no problem with 1-4, but compelely wrong with the rest. Like question 5, i throught the answer is True, but when i type it in IDLE, I got 7 instead, question 8 happy' and 'sad', my answer is True, but the answer is 'happy'. Can you please tell me why i am wrong. I really appreciate any assistance you can give. This is python's flavor of short-circuiting. Read the doc at: help(BOOLEAN) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Remote access from Windows PC to a Linux box
On 03/31/2010 03:29 AM, Mike Baker wrote: Hi, I'm trying to connect to a Linux box from my Windows machine and execute a series of commands - (ls, pwd, cat 'somefile', etc...). I'm using Putty to do the ssh and have set up with Putty's Pagent agent to allow me to enter a passphrase once per session to handle security keys between the two boxes (so, no passwords needed for my remote scripts). I have code that will give me a remote prompt on the Linux machine where I can manually enter commands. This works great, but I want a script to always execute the same series of commands without having to do so manually.. I also have code that will execute a single command like cat a file and write the ouput to a new file. However, when I try to use the communicate object in subprocess, my window hangs. Seeing your case, probably a simple shell script on the server side would be an easier option. Whenever you ssh to the server, you just execute this startup script. You may also be able to configure putty to execute this script automatically, though since I never used putty I don't know if putty can do that. Or alternatively, you can create a .bashrc (or whatever the remote box's terminal default startup script is). ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Simple bank account oriented object
Hi im doin a programmin course at university and in one on my exercise i have to do that I had to define a class CompteBancaire(CompteBancaire is bankaccount in french), that would allow me to create objects Compte1, Compte2,etc. The following methods need to be defined - depot(somme) would allow me to add cash to my account balance - retrait(somme)would allow me to withdraw some cash from my account - ajouterInterest() would allow me to add interest - affiche() would allow me to display the account owner and his account balance the retrait(somme) method is not supposed to let the account balance being negative. 3.2 Create a sub-class to CompteBancaire and name it CompteEtudiant. Each CompteEtudiant (student account) should have a $1000CAD credit line. Write a builder or constructor for this new class. Surcharge the retrait(somme) method to make sure that the student can withdraw to their limit. Test the class Here's my code for now this is 3.1and 3.2 in the same code Please help me i think im on the right track but i need some guidance in the dark. lol Thank you tutors #Exercice 3,1 - Gestion d'un compte bancaire class CompteBancaire: définition d'un compte bancaire def __init__(self,nom,solde,interet): #Nous allons instancier et initialiser les objets à la classe self.nom, self.solde, self.interet = nom,solde,interet def depot(self,somme=0):#Définition des fonctions self.solde=self.solde+somme #Pour additionner les dépôts au compte def retrait(self,somme=0): #Pour soustraire les dépôts au compte if self.solde-somme0: print Les fonds sont insuffisants. Essayez un autre montant pour votre retrait! else: self.solde=self.solde-somme def calculInteret(self,calculInteret=0): #Calcul des intérêts et du solde résiduel self.interet=self.solde*calculInteret/100 self.solde=(self.solde*calculInteret/100)+self.solde def affiche_solde(self): print Le solde du compte bancaire de %s est de %d $CAD %(self.nom,self.solde) print Vous avez récolté %d $CDN en intérêt%(self.interet) # ## # création de la gestion d'un compte étudiant autorisant une marge de crédit de (1 000$) class CompteEtudiant(CompteBancaire): définition du compte bancaire pour étudiant dérivé du compte bancaire standard def __init__(self, nom='Étudiant', solde=200, margeCre = 1000): #Limite de marge de crédit fixé à 1 000$ CompteBancaire.__init__(self, nom='Sandon', solde=800, interet=0) self.nom, self.solde, self.margeCre = nom, solde, margeCre def margeCre (self, somme=0): if somme-self.soldemargeCre: print Désolé vous dépassez la marge de crédit autorisé else: self.solde = (self.solde-somme) margeCre=margeCre+self.solde def affiche_solde(self, somme=0): print Le solde du compte bancaire de %s est de %d $CAD %(self.nom,self.solde) print Le solde de votre marge de crédit est de %d $CAD %(self.margeCre) print Vous avez récolté %d $CDN en intérêt%(self.interet) ## #jeux d'essai avec des valeurs fictives if __name__=='__main__':#Référence au corps principal du programme. compte1 = CompteBancaire('Sandon',800,0) compte1.depot(0) compte1.retrait(1200) compte1.calculInteret(10) compte1.affiche_solde() compte2 = CompteEtudiant('Étudiant', 800) compte2.retrait(900) compte2.affiche_solde() ## -- Ocram the newbie ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Simple bank account oriented object
On 03/31/2010 01:26 PM, Marco Rompré wrote: Please help me i think im on the right track but i need some guidance in the dark. lol And what's your question? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] characters
In Python, could space be counted as a character same as a letter? -- Shurui Liu (Aaron Liu) Computer Science Engineering Technology University of Toledo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] characters
Shurui Liu (Aaron Liu) wrote: In Python, could space be counted as a character same as a letter? len(...) len(object) - integer Return the number of items of a sequence or mapping. As a space is an item it will be counted. -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] characters
yeah, thank you! On Wed, Mar 31, 2010 at 1:41 AM, Christian Witts cwi...@compuscan.co.za wrote: Shurui Liu (Aaron Liu) wrote: In Python, could space be counted as a character same as a letter? len(...) len(object) - integer Return the number of items of a sequence or mapping. As a space is an item it will be counted. -- Kind Regards, Christian Witts -- Shurui Liu (Aaron Liu) Computer Science Engineering Technology University of Toledo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor