From kumarmysore at hotmail.com Mon Jan 2 12:01:36 2017 From: kumarmysore at hotmail.com (anatta anatta) Date: Mon, 2 Jan 2017 17:01:36 +0000 Subject: [Tutor] path string Message-ID: Dear Tutor. I am trying to create unsuccessfully source path as a string 'str7' in part_1 of the code below, to be used in part_2 of the code. When I define the source path explicitly in part_2 of the code (#sourcePath = r'H://TCVFLDAT'), the code works right. How else could I find the path in part-1 and use it in part 2? ###################### Here is my code: ###################### # -*- coding: utf-8 -*- """ Created on Wed Jun 01 17:05:07 2016 @author: anatta """ # Required module import os import shutil ###part_1 ### looking for files to be copied and obtaining source path ### # Function for getting files from a folder def fetchFiles(pathToFolder, flag, keyWord): ''' fetchFiles() requires three arguments: pathToFolder, flag and keyWord flag must be 'STARTS_WITH' or 'ENDS_WITH' keyWord is a string to search the file's name Be careful, the keyWord is case sensitive and must be exact. Example: fetchFiles('/Documents/Photos/','ENDS_WITH','.jpg') returns: _pathToFiles and _fileNames ''' _pathToFiles = [] _fileNames = [] for dirPath, dirNames, fileNames in os.walk(pathToFolder): if flag == 'ENDS_WITH': selectedPath = [os.path.join(dirPath,item) for item in fileNames if item.endswith(keyWord)] _pathToFiles.extend(selectedPath) selectedFile = [item for item in fileNames if item.endswith(keyWord)] _fileNames.extend(selectedFile) elif flag == 'STARTS_WITH': selectedPath = [os.path.join(dirPath,item) for item in fileNames if item.startswith(keyWord)] _pathToFiles.extend(selectedPath) selectedFile = [item for item in fileNames if item.startswith(keyWord)] _fileNames.extend(selectedFile) else: print fetchFiles.__doc__ break # Try to remove empty entries if none of the required files are in directory try: _pathToFiles.remove('') _imageFiles.remove('') except ValueError: pass # Warn if nothing was found in the given path #if selectedFile == []: #print 'No files with given parameters were found in:\n', dirPath, '\n' #print len(_fileNames), 'files were found is searched folder(s)' #return _pathToFiles, _fileNames #print _pathToFiles, _fileNames print 'path to first tuple file is:', _pathToFiles [0] str1 = ' '.join(_pathToFiles [0]) #convert tuple element 0 to string print 'length of str1 is: ', len (str1) str2 = str1.replace(" ", "") #remove white spaces print 'str2 is', str2 str3 = str2[13:16] #extract rgeistration print 'str3 is registration:', str3 str4 = 'FLDAT' print 'str4 is: ', str4 str5 = str3.__add__(str4) print 'str 5 is: ',str5 str6 = 'H://' print 'str6 is: ', str5 str7 = str6.__add__(str5) print 'str7 is: ', str7 #print _fileNames print 'Number of files found: ', len(_fileNames) fetchFiles('H://','ENDS_WITH','.FLD') #### part_2 #### copying files from sourcePath to destPath #sourcePath = r'H://TCVFLDAT' sourcePath = r'str7' print 'Source path is: ', sourcePath destPath = r'c://test_o/' print 'Destination path is: ', destPath #ls=os.listdir('.')#list current dir #print('listing current dir\n') #print(ls) for root, dirs, files in os.walk(sourcePath): #figure out where we're going dest = destPath + root.replace(sourcePath, '') #if we're in a directory that doesn't exist in the destination folder #then create a new folder if not os.path.isdir(dest): os.mkdir(dest) print 'Directory created at: ' + dest else: print 'Directory already exists:' + dest for root, dirs, files in os.walk(sourcePath): #figure out where we're going dest = destPath + root.replace(sourcePath, '') filetype = '.FLD'# name the file ext to be copied print 'All files of this type will be copied', filetype #loop through all files in the directory for f in files: #compute current (old) & new file locations oldLoc = root + '\\' + f newLoc = dest + '\\' + f #print 'Old location is:', oldLoc #print 'New location is:', newLoc if not os.path.isfile(newLoc): try: #filetype = '.FLD'# name the file ext to be copied #print 'All files of this type will be copied', filetype filename, file_ext = os.path.splitext(oldLoc) print 'filename is:', filename print 'file ext is', file_ext if file_ext == filetype: shutil.copy2(oldLoc, newLoc) print 'File ' + f + ' copied.' else: print 'File ' + f + ' not copied' except IOError: print 'file "' + f + '" already exists' #################### Below is the output: #################### Python 2.7.11 |Anaconda 4.0.0 (64-bit)| (default, Feb 16 2016, 09:58:36) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. Anaconda is brought to you by Continuum Analytics. Please check out: http://continuum.io/thanks and https://anaconda.org >>> runfile('D:/university_2/my_code_2/2017_01_02/get_reg_&_copy_file.py', wdir='D:/university_2/my_code_2/2017_01_02') path to first tuple file is: H://TCVFLDAT\TCV00000.FLD length of str1 is: 49 str2 is H://TCVFLDAT\TCV00000.FLD str3 is registration: TCV str4 is: FLDAT str 5 is: TCVFLDAT str6 is: TCVFLDAT str7 is: H://TCVFLDAT Number of files found: 21 Source path is: str7 Destination path is: c://test_o/ >>> From alan.gauld at yahoo.co.uk Mon Jan 2 19:08:41 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 3 Jan 2017 00:08:41 +0000 Subject: [Tutor] path string In-Reply-To: References: Message-ID: On 02/01/17 17:01, anatta anatta wrote: > I am trying to create unsuccessfully source path as > a string 'str7' in part_1 of the code below, When you say unsuccessfully what do you mean? What do you expect? What do you get? > to be used in part_2 of the code. For that you need to expose it outside the function, the best way to do that is to return it as a value, which you comment suggests you want to do. But the only return is commented out, so you need to tidy that up. But personally I think your function is trying to do too much. You should simplify it to only return the files and have another function that returns the path. Functions that try to do too many things (ie more than one) are notoriously difficult to debug. > When I define the source path explicitly in part_2 > of the code (#sourcePath = r'H://TCVFLDAT'), the > code works right. I'll take your word for it. > How else could I find the path in part-1 and use it in part 2? Return the value (assuming it is the right value) and in part two assign the return from the function to a variable. For my analysis below I've removed all the flag nonsense which is just cluttering things up for now and gone with the ENDS_WITH option as default.... > def fetchFiles(pathToFolder, flag, keyWord): > > _pathToFiles = [] > _fileNames = [] > > for dirPath, dirNames, fileNames in os.walk(pathToFolder): > selectedPath = [os.path.join(dirPath,item) for item in fileNames if item.endswith(keyWord)] > _pathToFiles.extend(selectedPath) > > selectedFile = [item for item in fileNames if item.endswith(keyWord)] > _fileNames.extend(selectedFile) You could simplify that by putting the selectedFiles line before the selectedPath line and use selectedFiles inside the comprehension. > > # Try to remove empty entries if none of the required files are in directory > try: > _pathToFiles.remove('') > _imageFiles.remove('') It would probably be better to check if they were empty before putting them in. Since you use the endswith() test I'm thinking there should never be any empty ones in this scenario anyway? > except ValueError: > pass > > #return _pathToFiles, _fileNames Here is the missing return statement but it's not returning what you said you wanted, ie str7 > #print _pathToFiles, _fileNames > print 'path to first tuple file is:', _pathToFiles [0] > str1 = ' '.join(_pathToFiles [0]) #convert tuple element 0 to string > print 'length of str1 is: ', len (str1) It might be wise to print the string itself to check you have what you want, I'm not sure you do... But I'm not really sure what you want since your code logic is confusing me a bit here. > str2 = str1.replace(" ", "") #remove white spaces So why did you add it above? Why not just use an empty string in the join? However, more seriously, what affect does this have on any paths/filenames that you found with spaces in them? Is that really what you want? > print 'str2 is', str2 > str3 = str2[13:16] #extract rgeistration > print 'str3 is registration:', str3 I'll assume this is right since I've no idea what format you think your filenames have. However, in general, relying on fixed positions within a string is not a good idea. This might be a valid case for using a regex which can more flexibly match your pattern. But for now just stick with the simple fixed values... > str4 = 'FLDAT' > print 'str4 is: ', str4 > str5 = str3.__add__(str4) You shouldn't really call the dunder methods directly you should use the + operator: str5 = str3 + str4 Or, in this case, save a variable and use the literal: str5 = str3 + 'FLDAT' > print 'str 5 is: ',str5 > str6 = 'H://' > print 'str6 is: ', str5 Did you really mean that? You've already printed str5. And do you really need a double slash after the drive letter? That's usually only needed if using backslashes ('H:\\'). > str7 = str6.__add__(str5) Again you could just use the literals: str7 = 'H://' + str3 = 'FLDAT' > print 'str7 is: ', str7 > > fetchFiles('H://','ENDS_WITH','.FLD') No assignment of any return value here > #### part_2 #### copying files from sourcePath to destPath > > sourcePath = r'str7' This assigns the literal string 'str7' is that what you want? You cannot access the variable str7 that was inside the function. It was a local variable and will have been destroyed by now. > print 'Source path is: ', sourcePath > destPath = r'c://test_o/' > print 'Destination path is: ', destPath > for root, dirs, files in os.walk(sourcePath): > > #figure out where we're going > dest = destPath + root.replace(sourcePath, '') > > #if we're in a directory that doesn't exist in the destination folder > #then create a new folder > if not os.path.isdir(dest): > os.mkdir(dest) > print 'Directory created at: ' + dest > else: > print 'Directory already exists:' + dest > > for root, dirs, files in os.walk(sourcePath): > #figure out where we're going > dest = destPath + root.replace(sourcePath, '') > filetype = '.FLD'# name the file ext to be copied > print 'All files of this type will be copied', filetype > #loop through all files in the directory > for f in files: > > #compute current (old) & new file locations > oldLoc = root + '\\' + f > newLoc = dest + '\\' + f > #print 'Old location is:', oldLoc > #print 'New location is:', newLoc > > if not os.path.isfile(newLoc): > try: > filename, file_ext = os.path.splitext(oldLoc) > print 'filename is:', filename > print 'file ext is', file_ext > if file_ext == filetype: > shutil.copy2(oldLoc, newLoc) > print 'File ' + f + ' copied.' You can save some work by using comma separation: print 'File', f,'copied.' No spaces needed and no string additions going on. > else: > print 'File ' + f + ' not copied' > except IOError: > print 'file "' + f + '" already exists' > > #################### > Below is the output: > #################### > > > Python 2.7.11 |Anaconda 4.0.0 (64-bit)| (default, Feb 16 2016, 09:58:36) [MSC v.1500 64 bit (AMD64)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > Anaconda is brought to you by Continuum Analytics. > Please check out: http://continuum.io/thanks and https://anaconda.org >>>> runfile('D:/university_2/my_code_2/2017_01_02/get_reg_&_copy_file.py', wdir='D:/university_2/my_code_2/2017_01_02') > path to first tuple file is: H://TCVFLDAT\TCV00000.FLD Note you have a mix of // and \ as separators. Probably better to just use one. > length of str1 is: 49 > str2 is H://TCVFLDAT\TCV00000.FLD > str3 is registration: TCV > str4 is: FLDAT > str 5 is: TCVFLDAT > str6 is: TCVFLDAT > str7 is: H://TCVFLDAT > Number of files found: 21 > Source path is: str7 > Destination path is: c://test_o/ -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From mrzenwiz at gmail.com Mon Jan 2 20:21:52 2017 From: mrzenwiz at gmail.com (MR ZenWiz) Date: Mon, 2 Jan 2017 17:21:52 -0800 Subject: [Tutor] Total newbie question Message-ID: I'm trying to install python 4.6 on my Xubuntu 16.04 desktop, and I keep getting scads of errors that culminate with this from make test: running build running build_ext INFO: Can't locate Tcl/Tk libs and/or headers warning: building with the bundled copy of libffi is deprecated on this platform. It will not be distributed with Python 3.7 Python build finished successfully! The necessary bits to build these optional modules were not found: _bz2 _curses _curses_panel _dbm _gdbm _lzma _sqlite3 _ssl _tkinter readline zlib To find the necessary bits, look in setup.py in detect_modules() for the module's name. I'm not sure how to handle this, but the upshot is I can't run idle (or idle3) on my system at all. What's the trick to getting all of python set up so I can use it? I have not found a good guide for how to do this. Thanks. MR From alan.gauld at yahoo.co.uk Tue Jan 3 04:00:55 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 3 Jan 2017 09:00:55 +0000 Subject: [Tutor] Total newbie question In-Reply-To: References: Message-ID: On 03/01/17 01:21, MR ZenWiz wrote: > I'm trying to install python 4.6 on my Xubuntu 16.04 desktop, I assume you mean Python 3.6? And my first question is why? Do you have some specific features in 3.6 that you need? Otherwise just go with the latest version in your package manager which will probably be 3.4 or 3.5. Both are stable releases and as a newbie should have more than enough to keep you busy until packages appear for 3.6. Seriously, life is too short to build from scratch unless you really know you need to. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From cs at zip.com.au Tue Jan 3 05:04:50 2017 From: cs at zip.com.au (Cameron Simpson) Date: Tue, 3 Jan 2017 21:04:50 +1100 Subject: [Tutor] Total newbie question In-Reply-To: References: Message-ID: <20170103100450.GA22895@cskk.homeip.net> On 02Jan2017 17:21, MR ZenWiz wrote: >I'm trying to install python 4.6 on my Xubuntu 16.04 desktop, and I >keep getting scads of errors that culminate with this from make test: > >running build >running build_ext >INFO: Can't locate Tcl/Tk libs and/or headers You lack the tk development libraries and/or headers. Try (as root): apt-get install tk-dev >The necessary bits to build these optional modules were not found: >_bz2 _curses _curses_panel >_dbm _gdbm _lzma >_sqlite3 _ssl _tkinter >readline zlib You need a bunch of other devleopment libraries too. You can use "apt-cache search" to look for package names, eg "apt-cache search readline". Based on an Ubuntu system also here try installing: libsqlite3-dev, libbz2-dev, libncursesw5-dev, libgdbm-dev, lzma-dev, libssl-dev, libreadline-dev, zlib1g-dev. Then do a clean configure again and see what it says. Cheers, Cameron Simpson From __peter__ at web.de Tue Jan 3 11:07:41 2017 From: __peter__ at web.de (Peter Otten) Date: Tue, 03 Jan 2017 17:07:41 +0100 Subject: [Tutor] Total newbie question References: <20170103100450.GA22895@cskk.homeip.net> Message-ID: Cameron Simpson wrote: > On 02Jan2017 17:21, MR ZenWiz wrote: >>I'm trying to install python 4.6 on my Xubuntu 16.04 desktop, and I >>keep getting scads of errors that culminate with this from make test: >> >>running build >>running build_ext >>INFO: Can't locate Tcl/Tk libs and/or headers > > You lack the tk development libraries and/or headers. Try (as root): > > apt-get install tk-dev > >>The necessary bits to build these optional modules were not found: >>_bz2 _curses _curses_panel >>_dbm _gdbm _lzma >>_sqlite3 _ssl _tkinter >>readline zlib > > You need a bunch of other devleopment libraries too. You can use > "apt-cache search" to look for package names, eg "apt-cache search > readline". > > Based on an Ubuntu system also here try installing: libsqlite3-dev, > libbz2-dev, libncursesw5-dev, libgdbm-dev, lzma-dev, libssl-dev, > libreadline-dev, zlib1g-dev. A nice shortcut for this is to install the build dependencies of the Python 3 used by your distribution: $ sudo apt-get build-dep python3.x Replace x with the actual minor version present on your system. > Then do a clean configure again and see what it says. > > Cheers, > Cameron Simpson > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From kumarmysore at hotmail.com Tue Jan 3 10:59:25 2017 From: kumarmysore at hotmail.com (anatta anatta) Date: Tue, 3 Jan 2017 15:59:25 +0000 Subject: [Tutor] Fw: path string In-Reply-To: References: Message-ID: Dear Tutor, Please disregard my request below. I know the problem! I have not defined the variable in question as a global variable. regret the inconvenience caused. Best. Kumar. + ________________________________ From: anatta anatta Sent: Monday, January 2, 2017 5:01 PM To: tutor at python.org Subject: path string Dear Tutor. I am trying to create unsuccessfully source path as a string 'str7' in part_1 of the code below, to be used in part_2 of the code. When I define the source path explicitly in part_2 of the code (#sourcePath = r'H://TCVFLDAT'), the code works right. How else could I find the path in part-1 and use it in part 2? ###################### Here is my code: ###################### # -*- coding: utf-8 -*- """ Created on Wed Jun 01 17:05:07 2016 @author: anatta """ # Required module import os import shutil ###part_1 ### looking for files to be copied and obtaining source path ### # Function for getting files from a folder def fetchFiles(pathToFolder, flag, keyWord): ''' fetchFiles() requires three arguments: pathToFolder, flag and keyWord flag must be 'STARTS_WITH' or 'ENDS_WITH' keyWord is a string to search the file's name Be careful, the keyWord is case sensitive and must be exact. Example: fetchFiles('/Documents/Photos/','ENDS_WITH','.jpg') returns: _pathToFiles and _fileNames ''' _pathToFiles = [] _fileNames = [] for dirPath, dirNames, fileNames in os.walk(pathToFolder): if flag == 'ENDS_WITH': selectedPath = [os.path.join(dirPath,item) for item in fileNames if item.endswith(keyWord)] _pathToFiles.extend(selectedPath) selectedFile = [item for item in fileNames if item.endswith(keyWord)] _fileNames.extend(selectedFile) elif flag == 'STARTS_WITH': selectedPath = [os.path.join(dirPath,item) for item in fileNames if item.startswith(keyWord)] _pathToFiles.extend(selectedPath) selectedFile = [item for item in fileNames if item.startswith(keyWord)] _fileNames.extend(selectedFile) else: print fetchFiles.__doc__ break # Try to remove empty entries if none of the required files are in directory try: _pathToFiles.remove('') _imageFiles.remove('') except ValueError: pass # Warn if nothing was found in the given path #if selectedFile == []: #print 'No files with given parameters were found in:\n', dirPath, '\n' #print len(_fileNames), 'files were found is searched folder(s)' #return _pathToFiles, _fileNames #print _pathToFiles, _fileNames print 'path to first tuple file is:', _pathToFiles [0] str1 = ' '.join(_pathToFiles [0]) #convert tuple element 0 to string print 'length of str1 is: ', len (str1) str2 = str1.replace(" ", "") #remove white spaces print 'str2 is', str2 str3 = str2[13:16] #extract rgeistration print 'str3 is registration:', str3 str4 = 'FLDAT' print 'str4 is: ', str4 str5 = str3.__add__(str4) print 'str 5 is: ',str5 str6 = 'H://' print 'str6 is: ', str5 str7 = str6.__add__(str5) print 'str7 is: ', str7 #print _fileNames print 'Number of files found: ', len(_fileNames) fetchFiles('H://','ENDS_WITH','.FLD') #### part_2 #### copying files from sourcePath to destPath #sourcePath = r'H://TCVFLDAT' sourcePath = r'str7' print 'Source path is: ', sourcePath destPath = r'c://test_o/' print 'Destination path is: ', destPath #ls=os.listdir('.')#list current dir #print('listing current dir\n') #print(ls) for root, dirs, files in os.walk(sourcePath): #figure out where we're going dest = destPath + root.replace(sourcePath, '') #if we're in a directory that doesn't exist in the destination folder #then create a new folder if not os.path.isdir(dest): os.mkdir(dest) print 'Directory created at: ' + dest else: print 'Directory already exists:' + dest for root, dirs, files in os.walk(sourcePath): #figure out where we're going dest = destPath + root.replace(sourcePath, '') filetype = '.FLD'# name the file ext to be copied print 'All files of this type will be copied', filetype #loop through all files in the directory for f in files: #compute current (old) & new file locations oldLoc = root + '\\' + f newLoc = dest + '\\' + f #print 'Old location is:', oldLoc #print 'New location is:', newLoc if not os.path.isfile(newLoc): try: #filetype = '.FLD'# name the file ext to be copied #print 'All files of this type will be copied', filetype filename, file_ext = os.path.splitext(oldLoc) print 'filename is:', filename print 'file ext is', file_ext if file_ext == filetype: shutil.copy2(oldLoc, newLoc) print 'File ' + f + ' copied.' else: print 'File ' + f + ' not copied' except IOError: print 'file "' + f + '" already exists' #################### Below is the output: #################### Python 2.7.11 |Anaconda 4.0.0 (64-bit)| (default, Feb 16 2016, 09:58:36) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. Anaconda is brought to you by Continuum Analytics. Please check out: http://continuum.io/thanks and https://anaconda.org Thank You for Using Anaconda continuum.io How was your experience getting set up? Is there anything you'd like to share with us? We would love to hear your feedback! We'll use it to make Anaconda even better. Send feedback to the Anaconda team :: Anaconda Cloud anaconda.org Where packages, notebooks, and environments are shared. Powerful collaboration and package management for open source and private projects. Public projects and ... >>> runfile('D:/university_2/my_code_2/2017_01_02/get_reg_&_copy_file.py', wdir='D:/university_2/my_code_2/2017_01_02') path to first tuple file is: H://TCVFLDAT\TCV00000.FLD length of str1 is: 49 str2 is H://TCVFLDAT\TCV00000.FLD str3 is registration: TCV str4 is: FLDAT str 5 is: TCVFLDAT str6 is: TCVFLDAT str7 is: H://TCVFLDAT Number of files found: 21 Source path is: str7 Destination path is: c://test_o/ >>> From mrzenwiz at gmail.com Tue Jan 3 14:38:09 2017 From: mrzenwiz at gmail.com (MR ZenWiz) Date: Tue, 3 Jan 2017 11:38:09 -0800 Subject: [Tutor] Total newbie question In-Reply-To: References: <20170103100450.GA22895@cskk.homeip.net> Message-ID: Forgot to include the list. On Tue, Jan 3, 2017 at 11:37 AM, MR ZenWiz wrote: > On Tue, Jan 3, 2017 at 8:07 AM, Peter Otten <__peter__ at web.de> wrote: >> Cameron Simpson wrote: >> >>> On 02Jan2017 17:21, MR ZenWiz wrote: >>>>I'm trying to install python 4.6 on my Xubuntu 16.04 desktop, and I >>>>keep getting scads of errors that culminate with this from make test: >>>> > : >> >> A nice shortcut for this is to install the build dependencies of the Python >> 3 used by your distribution: >> >> $ sudo apt-get build-dep python3.x >> >> Replace x with the actual minor version present on your system. >> > admar at marbase:~/Downloads $ sudo apt-get build-dev python3.5 > E: Invalid operation build-dev > > I also tried: > > admar at marbase:~/Downloads $ sudo apt-get build-dep python3 > Reading package lists... Done > E: You must put some 'source' URIs in your sources.list > admar at marbase:~/Downloads $ sudo apt-get build-dep python3.5 > Reading package lists... Done > E: You must put some 'source' URIs in your sources.list From cs at zip.com.au Tue Jan 3 20:15:30 2017 From: cs at zip.com.au (Cameron Simpson) Date: Wed, 4 Jan 2017 12:15:30 +1100 Subject: [Tutor] Total newbie question In-Reply-To: References: Message-ID: <20170104011530.GA63051@cskk.homeip.net> On 03Jan2017 17:07, Peter Otten <__peter__ at web.de> wrote: >Cameron Simpson wrote: >> On 02Jan2017 17:21, MR ZenWiz wrote: >>>I'm trying to install python 4.6 on my Xubuntu 16.04 desktop, [...] >>>INFO: Can't locate Tcl/Tk libs and/or headers >> You lack the tk development libraries and/or headers. Try (as root): >> apt-get install tk-dev [...] >> You need a bunch of other devleopment libraries too. [...] > >A nice shortcut for this is to install the build dependencies of the Python >3 used by your distribution: > >$ sudo apt-get build-dep python3.x > >Replace x with the actual minor version present on your system. I Did Not Know This! Yes, that sounds far more reliable than my guess-the-names approach. Thank you, Cameron Simpson From alan.gauld at yahoo.co.uk Wed Jan 4 04:27:30 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 4 Jan 2017 09:27:30 +0000 Subject: [Tutor] Fw: path string In-Reply-To: References: Message-ID: On 03/01/17 15:59, anatta anatta wrote: > Please disregard my request below. > > I know the problem! > > I have not defined the variable in question as a global variable. That's one solution but its not a very good one. Global variables are not considered good practice for many reasons. In particular, they make code reuse difficult and if you ever need to use your code in a multi-threaded environment, to improve performance say, they are nearly impossible to work with. It's much better to pass the required value out of the function as a return value. > regret the inconvenience caused. No inconvenience, its what the list is here for! :-) hth -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From __peter__ at web.de Wed Jan 4 04:43:00 2017 From: __peter__ at web.de (Peter Otten) Date: Wed, 04 Jan 2017 10:43 +0100 Subject: [Tutor] Total newbie question References: <20170103100450.GA22895@cskk.homeip.net> Message-ID: MR ZenWiz wrote: > Forgot to include the list. > > > On Tue, Jan 3, 2017 at 11:37 AM, MR ZenWiz wrote: >> On Tue, Jan 3, 2017 at 8:07 AM, Peter Otten <__peter__ at web.de> wrote: >>> Cameron Simpson wrote: >>> >>>> On 02Jan2017 17:21, MR ZenWiz wrote: >>>>>I'm trying to install python 4.6 on my Xubuntu 16.04 desktop, and I >>>>>keep getting scads of errors that culminate with this from make test: >>>>> >> : >>> >>> A nice shortcut for this is to install the build dependencies of the >>> Python 3 used by your distribution: >>> >>> $ sudo apt-get build-dep python3.x >>> >>> Replace x with the actual minor version present on your system. >>> >> admar at marbase:~/Downloads $ sudo apt-get build-dev python3.5 >> E: Invalid operation build-dev It has to be build-dep, not build-dev. From mrzenwiz at gmail.com Wed Jan 4 01:51:26 2017 From: mrzenwiz at gmail.com (MR ZenWiz) Date: Tue, 3 Jan 2017 22:51:26 -0800 Subject: [Tutor] Total newbie question In-Reply-To: <20170104011530.GA63051@cskk.homeip.net> References: <20170104011530.GA63051@cskk.homeip.net> Message-ID: On Tue, Jan 3, 2017 at 5:15 PM, Cameron Simpson wrote: > On 03Jan2017 17:07, Peter Otten <__peter__ at web.de> wrote: >> >> Cameron Simpson wrote: >>> >>> On 02Jan2017 17:21, MR ZenWiz wrote: >>>> >>>> I'm trying to install python 4.6 on my Xubuntu 16.04 desktop, [...] >>>> INFO: Can't locate Tcl/Tk libs and/or headers >>> >>> You lack the tk development libraries and/or headers. Try (as root): >>> apt-get install tk-dev > > [...] >>> >>> You need a bunch of other devleopment libraries too. [...] >> >> >> A nice shortcut for this is to install the build dependencies of the >> Python >> 3 used by your distribution: >> >> $ sudo apt-get build-dep python3.x >> >> Replace x with the actual minor version present on your system. > > > I Did Not Know This! > > Yes, that sounds far more reliable than my guess-the-names approach. > > Thank you, > If that had worked, I'd be quite pleased, but as I posted earlier, apgt-get claims not to know what to do with that. I tried deleting all the ~/.local/python3* files and also all python files in /etc and /usr, then reinstalled all the (previously) system installed version via synaptic, and python3.5 seems to work as a command, but idle3 does not: admar at marbase:~ $ which idle3 /usr/local/bin/idle3 admar at marbase:~ $ which idle3.5 /usr/local/bin/idle3.5 admar at marbase:~ $ which python3 /usr/bin/python3 admar at marbase:~ $ which python3.5 /usr/bin/python3.5 admar at marbase:~ $ idle3 bash: /usr/local/bin/idle3: /usr/local/bin/python3.5: bad interpreter: No such file or directory admar at marbase:~ $ idle3.5 bash: /usr/local/bin/idle3.5: /usr/local/bin/python3.5: bad interpreter: No such file or directory It appears that while python is installed in /usr/bin, idle is in /usr/local/bin and expects the python interpreter to be also under /usr/local, which does not seem to be the default. I created a symlink 'ln -s /usr/bin/python3.5 /usr/local/bin/python3.5' and now idle comes up. While this works, it is not at all intuitive (and I haven't exercised it to see how robust this is). What would make the idle want something that isn't there without such hackery? Thanks. MR From alan.gauld at yahoo.co.uk Wed Jan 4 04:57:09 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 4 Jan 2017 09:57:09 +0000 Subject: [Tutor] Total newbie question In-Reply-To: References: <20170104011530.GA63051@cskk.homeip.net> Message-ID: On 04/01/17 06:51, MR ZenWiz wrote: > It appears that while python is installed in /usr/bin, idle is in > /usr/local/bin and expects the python interpreter to be also under > /usr/local, which does not seem to be the default. > > I created a symlink 'ln -s /usr/bin/python3.5 > /usr/local/bin/python3.5' and now idle comes up. Did you install the idle-python3.5 package too? That should have created a launcher in your menu system for idle. On Ubuntu (and most Linux systems) you have to install "extra" features like idle as packages. It's well worth browsing the available python packages using synaptic, or whatever manager you prefer. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From kumarmysore at hotmail.com Thu Jan 5 08:01:49 2017 From: kumarmysore at hotmail.com (anatta anatta) Date: Thu, 5 Jan 2017 13:01:49 +0000 Subject: [Tutor] prenting a line form appearing in log file Message-ID: Dear Tutors, Thanks in advance for the help. anatta. + I have created a log file, using 'logging' module, which records items of my interest after the execution of the program. The program in the beginning asks for name of the person who runs the program, as below: name = raw_input ("Please enter your name.") print 'Hi ', name, 'Please go ahead and press enter to transfer files' The log file records the variable 'name' in the log file at the right location as I have coded. So far so good. However the log file also records the following statements at the end of the log file. Hi 'name', Please go ahead and transfer files How can I prevent this line from appearing at the end of the logfile. +++ From s.molnar at sbcglobal.net Thu Jan 5 08:29:33 2017 From: s.molnar at sbcglobal.net (S. P. Molnar) Date: Thu, 05 Jan 2017 08:29:33 -0500 Subject: [Tutor] Help with a Conversion Message-ID: <586E4A3D.3060601@sbcglobal.net> I have just started attempting programming in Python and am using Spyder with Python 3.5.2 on a Linux platform. (I first started programing in Fortran II using punched paper tape. Yes, am a rather elderly . . .). I have bumbled through, what I foolishly thought was a simple problem, a short program to change frequency to wavelength for a plot of ultraviolet spectra. I have attached a pdf of the program. During my attempt at programming I have printed results at various stages. Printing wavelength = [row[0] for row in data] gives me 25000 as the first frequency in the wavelength list (the corresponding wavelength is 400). To change the frequency to wave length I did the following: p=1/1e7 wave_length = p*np.array(frequency) (The relationship between wavelength and frequency is: wavelength = 1.0e7/frequency, where 1e7 is the speed of light) Apparently whhat I have managed to do is divide each element of the frequency list by 1/1e7. What I want to do is divide 1e7 by each element of the freqquency list. How di I do this? Please keep in mind that many, many hyears ago I learned the ole arithmetic and an not trying to start a flame war. Thanks in advance for the assistance tha I am sure will be most helpful. -- Stephen P. Molnar, Ph.D. Life is a fuzzy set www.Molecular-Modeling.net Stochastic and multivariate (614)312-7528 (c) Skype: smolnar1 From alan.gauld at yahoo.co.uk Thu Jan 5 11:27:55 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 5 Jan 2017 16:27:55 +0000 Subject: [Tutor] prenting a line form appearing in log file In-Reply-To: References: Message-ID: On 05/01/17 13:01, anatta anatta wrote: > I have created a log file, using 'logging' module, > name = raw_input ("Please enter your name.") > print 'Hi ', name, 'Please go ahead and press enter to transfer files' > > The log file records the variable 'name' in the log file at the > right location as I have coded. So far so good. > > However the log file also records the following statements > at the end of the log file. > > Hi 'name', Please go ahead and transfer files > > How can I prevent this line from appearing at the end of the logfile. Its hard to tell what's happening without seeing your code. If it is very long try creating a shirter example that exhibits the same behaviour and post that. (Doing so may even show you the error.) But with the limited information you've given us, we are just making wild guesses. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Thu Jan 5 11:41:24 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 5 Jan 2017 16:41:24 +0000 Subject: [Tutor] Help with a Conversion In-Reply-To: <586E4A3D.3060601@sbcglobal.net> References: <586E4A3D.3060601@sbcglobal.net> Message-ID: On 05/01/17 13:29, S. P. Molnar wrote: > Fortran II using punched paper tape. Yes, am a rather elderly . . .). You are not the only one, there are at least 2 more of us on this list that started in that era... > short program to change frequency to wavelength for a plot of > ultraviolet spectra. I have attached a pdf of the program. This is a text list so attachments usually get stripped off. Please post the code in the body of the email using plain text formatting. > To change the frequency to wave length I did the following: > > p=1/1e7 p = 1e-7 > wave_length = p*np.array(frequency) I don't really use numpy so don't know what that line does. But assuming it applies the multiplication to each array element I'd probably use: wave_lengths = [p*f for f in frequencies] or possibly wave_lengths = map(lambda f: p*f, frequencies) where frequencies was a tuple/list of frequency values. However... > (The relationship between wavelength and frequency is: wavelength = > 1.0e7/frequency, where 1e7 is the speed of light) That formula doesn't look like the one you use above if my guess is correct. That would look like: wave_length = [1e7/f for f in frequencies] ie positive exponent and division instead of multiplication > Apparently what I have managed to do is divide each element of the frequency list by 1/1e7. > > What I want to do is divide 1e7 by each element of the freqquency list. > How di I do this? Rearrange the equation and use division instead of multiplication I think that by calculating 1/p you have made things much more complicated - unless there is some subtle arithmetic magic going on that I'm missing? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From s.molnar at sbcglobal.net Thu Jan 5 12:26:59 2017 From: s.molnar at sbcglobal.net (S. P. Molnar) Date: Thu, 05 Jan 2017 12:26:59 -0500 Subject: [Tutor] Help with a Conversion In-Reply-To: References: <586E4A3D.3060601@sbcglobal.net> Message-ID: <586E81E3.4050001@sbcglobal.net> On 01/05/2017 11:41 AM, Alan Gauld via Tutor wrote: > On 05/01/17 13:29, S. P. Molnar wrote: > >> Fortran II using punched paper tape. Yes, am a rather elderly . . .). > You are not the only one, there are at least 2 more of us on > this list that started in that era... > >> short program to change frequency to wavelength for a plot of >> ultraviolet spectra. I have attached a pdf of the program. > This is a text list so attachments usually get stripped off. > Please post the code in the body of the email using plain text > formatting. > >> To change the frequency to wave length I did the following: >> >> p=1/1e7 > p = 1e-7 > >> wave_length = p*np.array(frequency) > I don't really use numpy so don't know what that line does. > But assuming it applies the multiplication to each array element > I'd probably use: > > wave_lengths = [p*f for f in frequencies] > > or possibly > > wave_lengths = map(lambda f: p*f, frequencies) > > where frequencies was a tuple/list of frequency values. > > However... > >> (The relationship between wavelength and frequency is: wavelength = >> 1.0e7/frequency, where 1e7 is the speed of light) > That formula doesn't look like the one you use above > if my guess is correct. That would look like: > > wave_length = [1e7/f for f in frequencies] > > ie positive exponent and division instead of multiplication > >> Apparently what I have managed to do is divide each element of the frequency list by 1/1e7. >> >> What I want to do is divide 1e7 by each element of the freqquency list. >> How di I do this? > Rearrange the equation and use division instead of multiplication > I think that by calculating 1/p you have made things much more > complicated - unless there is some subtle arithmetic magic going > on that I'm missing? > Many thanks for the reply and your suggestions. As it happens, I stumbled on the solution through trial and error. The correct line is: wave_length = 1e7/np.array(frequency). All is now well. -- Stephen P. Molnar, Ph.D. Life is a fuzzy set www.Molecular-Modeling.net Stochastic and multivariate (614)312-7528 (c) Skype: smolnar1 From __peter__ at web.de Thu Jan 5 13:10:53 2017 From: __peter__ at web.de (Peter Otten) Date: Thu, 05 Jan 2017 19:10:53 +0100 Subject: [Tutor] Help with a Conversion References: <586E4A3D.3060601@sbcglobal.net> Message-ID: S. P. Molnar wrote: > I have just started attempting programming in Python and am using Spyder > with Python 3.5.2 on a Linux platform. (I first started programing in > Fortran II using punched paper tape. Yes, am a rather elderly . . .). > > I have bumbled through, what I foolishly thought was a simple problem, a > short program to change frequency to wavelength for a plot of > ultraviolet spectra. I have attached a pdf of the program. > > During my attempt at programming I have printed results at various > stages. Printing wavelength = [row[0] for row in data] gives me 25000 > as the first frequency in the wavelength list (the corresponding > wavelength is 400). > > To change the frequency to wave length I did the following: > > > p=1/1e7 > wave_length = p*np.array(frequency) > > (The relationship between wavelength and frequency is: wavelength = > 1.0e7/frequency, where 1e7 is the speed of light) > > > Apparently whhat I have managed to do is divide each element of the > frequency list by 1/1e7. > > What I want to do is divide 1e7 by each element of the freqquency list. > > How di I do this? Since you are using numpy anyway I'd put the frequencies into a numpy.array as soon as possible: >>> import numpy >>> frequencies = numpy.array([25000, 1250, 400]) Because of numpy's "broadcasting" you can mix skalars and vectors as you already tried -- and with the right formula, lamda = c / nu, you get the correct result: >>> speed_of_light = 1e7 >>> wavelengths = speed_of_light / frequencies >>> wavelengths array([ 400., 8000., 25000.]) The equivalent list comprehension in plain Python looks like this: >>> frequencies = [25000, 1250, 400] >>> wavelengths = [speed_of_light/freq for freq in frequencies] >>> wavelengths [400.0, 8000.0, 25000.0] > Please keep in mind that many, many hyears ago I learned the ole > arithmetic That hasn't changed and is honoured by numpy; you were probably confused by the new tool ;) > and an not trying to start a flame war. > Thanks in advance for the assistance tha I am sure will be most helpful. From steve at pearwood.info Thu Jan 5 18:18:29 2017 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 6 Jan 2017 10:18:29 +1100 Subject: [Tutor] Help with a Conversion In-Reply-To: <586E4A3D.3060601@sbcglobal.net> References: <586E4A3D.3060601@sbcglobal.net> Message-ID: <20170105231828.GK3887@ando.pearwood.info> On Thu, Jan 05, 2017 at 08:29:33AM -0500, S. P. Molnar wrote: [...] > To change the frequency to wave length I did the following: > > > p=1/1e7 > wave_length = p*np.array(frequency) > > (The relationship between wavelength and frequency is: wavelength = > 1.0e7/frequency, where 1e7 is the speed of light) > > > Apparently whhat I have managed to do is divide each element of the > frequency list by 1/1e7. Indeed :-) This is a matter of arithmetic: Let p = 1/x then p*f = (1/x)*f = f/x So you have divided each frequency by x, namely 1e7. What you want is: x/f which divides x (1e7) by the frequency. The interactive interpreter is very good for exploring simple questions like this. If you need help starting the interactive interpreter, please ask, although I haven't used Spyder for many years and I'm not familiar with it. But in the regular Python interpreter, I can do this: py> import numpy as np py> data = np.array([1, 2, 3]) py> data array([1, 2, 3]) py> factor = 1/10.0 py> factor*data array([ 0.1, 0.2, 0.3]) py> factor/data array([ 0.1 , 0.05 , 0.03333333]) (lines starting with "py>" is the code I have typed). So to get the result you want, you should be able to do this: wave_length = 1e7/np.array(frequency) -- Steve From s.molnar at sbcglobal.net Thu Jan 5 13:31:06 2017 From: s.molnar at sbcglobal.net (S. P. Molnar) Date: Thu, 05 Jan 2017 13:31:06 -0500 Subject: [Tutor] Help with a Conversion In-Reply-To: References: <586E4A3D.3060601@sbcglobal.net> Message-ID: <586E90EA.3030404@sbcglobal.net> On 01/05/2017 01:10 PM, Peter Otten wrote: > S. P. Molnar wrote: > >> I have just started attempting programming in Python and am using Spyder >> with Python 3.5.2 on a Linux platform. (I first started programing in >> Fortran II using punched paper tape. Yes, am a rather elderly . . .). >> >> I have bumbled through, what I foolishly thought was a simple problem, a >> short program to change frequency to wavelength for a plot of >> ultraviolet spectra. I have attached a pdf of the program. >> >> During my attempt at programming I have printed results at various >> stages. Printing wavelength = [row[0] for row in data] gives me 25000 >> as the first frequency in the wavelength list (the corresponding >> wavelength is 400). >> >> To change the frequency to wave length I did the following: >> >> >> p=1/1e7 >> wave_length = p*np.array(frequency) >> >> (The relationship between wavelength and frequency is: wavelength = >> 1.0e7/frequency, where 1e7 is the speed of light) >> >> >> Apparently whhat I have managed to do is divide each element of the >> frequency list by 1/1e7. >> >> What I want to do is divide 1e7 by each element of the freqquency list. >> >> How di I do this? > Since you are using numpy anyway I'd put the frequencies into a numpy.array > as soon as possible: > >>>> import numpy >>>> frequencies = numpy.array([25000, 1250, 400]) > Because of numpy's "broadcasting" you can mix skalars and vectors as you > already tried -- and with the right formula, lamda = c / nu, you get the > correct result: > >>>> speed_of_light = 1e7 >>>> wavelengths = speed_of_light / frequencies >>>> wavelengths > array([ 400., 8000., 25000.]) > > The equivalent list comprehension in plain Python looks like this: > >>>> frequencies = [25000, 1250, 400] >>>> wavelengths = [speed_of_light/freq for freq in frequencies] >>>> wavelengths > [400.0, 8000.0, 25000.0] > >> Please keep in mind that many, many hyears ago I learned the ole >> arithmetic > That hasn't changed and is honoured by numpy; you were probably confused by > the new tool ;) > >> and an not trying to start a flame war. >> Thanks in advance for the assistance tha I am sure will be most helpful. > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > Somehow I KNEW THIS WAS THE LIWST TO Ask. Thanks very much. -- Stephen P. Molnar, Ph.D. Life is a fuzzy set www.Molecular-Modeling.net Stochastic and multivariate (614)312-7528 (c) Skype: smolnar1 From amutsikiwa at gmail.com Fri Jan 6 07:55:01 2017 From: amutsikiwa at gmail.com (Admire Mutsikiwa) Date: Fri, 6 Jan 2017 14:55:01 +0200 Subject: [Tutor] Challenges with psycopg2 on Python 3.2 Message-ID: I am running Python on Debian 7 Wheezy. I am having challenges with psycopg2 on python 3.2. However, it is working well on python 2.7. When I do import psycopg2 on Python 2.7, the system will not complain. However, it screams on the Python3.2 prompt, it gives >>> import psycopg2 File "", line 1 import psycopg2 ^ IndentationError: unexpected indent I am new to Python and wants to work with Python 3 Any pointers will be greatly appreciated. Kind regards, Admire From alan.gauld at yahoo.co.uk Fri Jan 6 12:48:15 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 6 Jan 2017 17:48:15 +0000 Subject: [Tutor] Challenges with psycopg2 on Python 3.2 In-Reply-To: References: Message-ID: On 06/01/17 12:55, Admire Mutsikiwa wrote: > it screams on the Python3.2 prompt, it gives Hardly screaming, rather a polite complaint that you've messed up your indentation. >>>> import psycopg2 > File "", line 1 > import psycopg2 > ^ > IndentationError: unexpected indent I'll guess that you have a space or two in front of import. Python is very fussy about spacing at the front of lines, aka indentation. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From rikudou__sennin at live.com Tue Jan 10 12:56:54 2017 From: rikudou__sennin at live.com (adil gourinda) Date: Tue, 10 Jan 2017 17:56:54 +0000 Subject: [Tutor] small remark Message-ID: When I was surfing in ?Python Library? I made some observations and I want to share them with you in attention to have an answer : 1) I suggest some changes in the following sections : ------------------------------------------------------------------------------------------------- *date.replace(year=self.year, month=self.month, day=self.day) ? . For example, if "d == date(2002, 12, 31)", then "d.replace(day=26) == date(2002, 12, 26)". ->change to: *date.replace(year=self.year, month=self.month, day=self.day) ? . For example: >>> d=date(2002,12,31) >>> d.replace(day=26) datetime.date(2002, 12, 26) ----------------------------------------------------------------------------------------------- *date.weekday() ? . For example, "date(2002, 12, 4).weekday() == 2", a Wednesday. ? . ?change to : *date.weekday() ? . For example: >>> date(2002, 12, 4).weekday() 2 (a Wednesday) ------------------------------------------------------------------------------ *date.isoweekday() ? . For example, "date(2002, 12, 4).isoweekday() == 3", a Wednesday. ? . ?change to: *date.isoweekday() ? . For example: >>> date(2002, 12, 4).isoweekday() 3 -------------------------------------------------------------------------------------------------------------- *date.isoformat() ? . For example, "date(2002, 12, 4).isoformat() == '2002-12-04'". ?change to: *date.isoformat() ? . For example: >>> date(2002, 12, 4).isoformat() '2002-12-04' ------------------------------------------------------------------------------------------------------------------- *date.ctime() ..., for example "date(2002, 12, 4).ctime() == 'Wed Dec 4 00:00:00 2002'". ? . ?change to : *date.ctime() ..., for example: >>> date(2002, 12, 4).ctime() 'Wed Dec 4 00:00:00 2002' --------------------------------------------------------------------------------------------------------------- *datetime.ctime() ..., for example "datetime(2002, 12, 4, 20, 30, 40).ctime() == 'Wed Dec 4 20:30:40 2002'". .... ?change to: *datetime.ctime() ..., for example: >>> datetime(2002, 12, 4, 20, 30, 40).ctime() 'Wed Dec 4 20:30:40 2002' Those are examples in script format that the reader can try them which make the documentation more understandable for beginners like me. 2) If we compare some methods between them we will find some methods more generalized than others, So why we continue to use the latter : * List.insert(i,x) vs List.append(x) vs List.extend(x) : list.append(x) is restricted in the number of items in comparison with list.extend(x) and it is restricted in the position of items in comparison with list.insert(i,x), So I don?t see the utility of list.append(x) in front of the two others method. * For log function I suggest this optimization in its presentation : math.log(x[, base]) With one argument, return the natural logarithm of *x* (to base *e*). With two arguments, return the logarithm of *x* to the given *base*, calculated as "log(x)/log(base)". math.log2(x) Return the base-2 logarithm of *x*. This is usually more accurate than "log(x, 2)". ? math.log10(x) Return the base-10 logarithm of *x*. This is usually more accurate than "log(x, 10)". -------- math.log(x[, base]) *return the logarithm of *x* to the given *base*, calculated as "log(x)/log(base)". *if base is omitted=> return the natural logarithm of *x* (to base *e*). *if base=2 => math.log2(x): Return the base-2 logarithm of *x*. This is usually more accurate than "log(x, 2)". *if base=10 => math.log10(x): Return the base-10 logarithm of *x*. This is usually more accurate than "log(x, 10)". Thank you for your attention and I wish I was helpful [?] From alan.gauld at yahoo.co.uk Wed Jan 11 05:21:32 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 11 Jan 2017 10:21:32 +0000 Subject: [Tutor] small remark In-Reply-To: References: Message-ID: On 10/01/17 17:56, adil gourinda wrote: > When I was surfing in ?Python Library? I made some observations and I want to share them That's good and as a place to discuss those observations the tutor list is a suitable forum. However, if you want the proposals considered for actual implementation, you will need to submit them via the bug tracker on python.org > *date.replace(year=self.year, month=self.month, day=self.day) > > ? . For example, if "d == date(2002, 12, 31)", then "d.replace(day=26) == date(2002, 12, 26)". > > ->change to: > > *date.replace(year=self.year, month=self.month, day=self.day) > > ? . For example: > > >>> d=date(2002,12,31) > >>> d.replace(day=26) > datetime.date(2002, 12, 26) I see what you are getting at but I guess the current form is more compact and that's why it was chosen. > *date.weekday() > > ? . For example, "date(2002, 12, 4).weekday() == 2", a Wednesday. ? . > > ?change to : > > *date.weekday() > > ? . For example: > > >>> date(2002, 12, 4).weekday() > 2 (a Wednesday) > Those are examples in script format that the reader can try They are not really in "script" form, they are in interactive interpreter form which is actually different to when used in a script, but I guess that's what you mean - that they can be typed at the interpreter. Of course the existing examples can be typed at the interpreter too, but they just return True... > 2) If we compare some methods between them we will find > some methods more generalized than others, > So why we continue to use the latter : There can be many reasons: 1) the specific method might be easier to use in the most common cases 2) the generalised method may be less efficient than the specialized 3) there may be a large body of legacy code that uses the specialised version and it would be a lot of work to change it. 4) there may be subtle differences in the way the methods work for certain data types > * List.insert(i,x) vs List.append(x) vs List.extend(x) : > > list.append(x) is restricted in the number of items in comparison with list.extend(x) No, the both take exactly 1 item each. The item can be a list. but... They do slightly different things. for example compare lst = [0] lst.extend([1,2,3]) lst2 = [0] lst2.append([1,2,3]) If we were to get rid of append, say, then the use of extend to replicate append's functionality gets a bit ugly: lst3 = [0] lst3.extend([[1,2,3]]) > it is restricted in the position of items in comparison > with list.insert(i,x), But you can't replicate extend() with insert() - at least I can't think of a way. And even for appending, if you don't know the size of the list you wind up with: lst.insert(len(lst), data) Which is both messy and slow. > So I don?t see the utility of list.append(x) Appending is by far the most commonly used of the three operations and append() is simpler and it is faster - it doesn't have to do anything complex like unpack its arguments(extend) or break open a list and rearrange the contents(insert) it just adds whatever it is given to the end. > * For log function I suggest ... I'm not familiar with the log functions but I suspect performance of the most common scenarios may be the reasons here too, but I'll leave others to comment more fully. Finally, it is probably possible to build optimised versions of the general functions that would recognise the special cases and treat them differently. And if enough people ask for it somebody may take the time to do it. But if you really want it you need to discuss it via the official channels. Python certainly does have a lot of redundant functions - just look at how many ways there are to start an external program (system/popen/command/ call/Popen/fork/exec etc...) And even when the docs try hard to direct people to the recommended option (like the subprocess module) many just prefer the older ways because they know them, or they are slightly simpler to use. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From rampappula at gmail.com Wed Jan 11 01:31:54 2017 From: rampappula at gmail.com (ramakrishna reddy) Date: Tue, 10 Jan 2017 22:31:54 -0800 Subject: [Tutor] Convert tuple within tuple into single tuple Message-ID: Hi All, Is there any way to convert x = (1, 2, 3, (4, 5)) to x = (1, 2, 3, 4, 5) in python 2.7 Thanks in advance Ram. From unee0x at gmail.com Tue Jan 10 21:53:04 2017 From: unee0x at gmail.com (kay Cee) Date: Tue, 10 Jan 2017 21:53:04 -0500 Subject: [Tutor] Importing classes Message-ID: Is there a proper way to import a class from a module? If so, please tell. Thank You, Unee0x From alan.gauld at yahoo.co.uk Wed Jan 11 14:50:11 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 11 Jan 2017 19:50:11 +0000 Subject: [Tutor] Importing classes In-Reply-To: References: Message-ID: On 11/01/17 02:53, kay Cee wrote: > Is there a proper way to import a class from a module? If so, please tell. The most common way is probably: >>> from mymodule import Myclass >>> myobject = Myclass() but its just as good to do >>> import mymodule >>> myobject = mymodule.Myclass() -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Wed Jan 11 14:57:51 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 11 Jan 2017 19:57:51 +0000 Subject: [Tutor] Convert tuple within tuple into single tuple In-Reply-To: References: Message-ID: On 11/01/17 06:31, ramakrishna reddy wrote: > Hi All, > > Is there any way to convert x = (1, 2, 3, (4, 5)) to x = (1, 2, 3, 4, 5) in > python 2.7 You can write a function(*) to flatten the data structure, but you need to be careful and think through how you expect it to handle strings, say... or dictionaries? Or user defined collection objects? That's probably why there is no built-in method to flatten a data structure. Such functions are often recursive in nature looking something like this list based example from my tutorial: def printList(L): # if its empty do nothing if not L: return # if it's a list call printList on 1st element if type(L[0]) == type([]): printList(L[0]) else: #no list so just print print( L[0] ) # now process the rest of L printList( L[1:] ) Obviously that prints rather than building a new list but it should be fairly easy to modify it. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From emilevansebille at gmail.com Wed Jan 11 15:05:47 2017 From: emilevansebille at gmail.com (Emile van Sebille) Date: Wed, 11 Jan 2017 12:05:47 -0800 Subject: [Tutor] Convert tuple within tuple into single tuple In-Reply-To: References: Message-ID: On 01/10/2017 10:31 PM, ramakrishna reddy wrote: > Hi All, > > Is there any way to convert x = (1, 2, 3, (4, 5)) to x = (1, 2, 3, 4, 5) in > python 2.7 > Almost: # /usr/bin/env python Python 2.7.3 (default, Sep 22 2012, 02:37:18) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import itertools >>> a = list(itertools.chain((1,2,3),(4,5))) >>> a [1, 2, 3, 4, 5] Emile From __peter__ at web.de Wed Jan 11 16:02:36 2017 From: __peter__ at web.de (Peter Otten) Date: Wed, 11 Jan 2017 22:02:36 +0100 Subject: [Tutor] Convert tuple within tuple into single tuple References: Message-ID: ramakrishna reddy wrote: > Hi All, > > Is there any way to convert x = (1, 2, 3, (4, 5)) to x = (1, 2, 3, 4, 5) > in python 2.7 Is the structure of x always the same? Then you can build a new tuple from >>> x[:-1] # all items but the last (1, 2, 3) and >>> x[-1] # the last item (4, 5) by concatenating them: >>> x[:-1] + x[-1] (1, 2, 3, 4, 5) From adeadmarshal at gmail.com Fri Jan 13 01:59:00 2017 From: adeadmarshal at gmail.com (Ali Moradi) Date: Fri, 13 Jan 2017 10:29:00 +0330 Subject: [Tutor] problem with python3 Tkinter scroll bar Message-ID: Hi. i can't fix this error in my code about scroll bar. what should i do? i'm a beginner in Python plz help. https://paste.pound-python.org/show/CIKA8eOFbdq18r3nFUBv/ From adeadmarshal at gmail.com Fri Jan 13 01:55:51 2017 From: adeadmarshal at gmail.com (Ali Moradi) Date: Fri, 13 Jan 2017 10:25:51 +0330 Subject: [Tutor] problem with scroll in Tkinter In-Reply-To: References: Message-ID: https://paste.pound-python.org/show/CIKA8eOFbdq18r3nFUBv/ On Fri, Jan 13, 2017 at 10:25 AM, Ali Moradi wrote: > hi. I've written this code and i can't fix the scrollbar error. i am a > beginner in Python plz help. this is python3 code. > From alan.gauld at yahoo.co.uk Fri Jan 13 04:18:04 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 13 Jan 2017 09:18:04 +0000 Subject: [Tutor] problem with scroll in Tkinter In-Reply-To: References: Message-ID: On 13/01/17 06:55, Ali Moradi wrote: > https://paste.pound-python.org/show/CIKA8eOFbdq18r3nFUBv/ > > On Fri, Jan 13, 2017 at 10:25 AM, Ali Moradi wrote: > >> hi. I've written this code and i can't fix the scrollbar error. i am a >> beginner in Python plz help. this is python3 code. You've posted 70+ lines of code but no indication of the problem. I'd suggest that you: 1) simplify your code to remove all irrelevant bits, that way you can focus on what is actually the issue. So remove all the sqlite query stuff and all the ttk styling stuff - unless the problem is the styling of course! 2) post the simplified code with a clear description of the problem - what did you expect? what did you get? Were there any error messages (you'll need to run it from a terminal to see them) By the time you remove the irrelevant stuff it should be small enough to post within the email (using plain text) which will encourage more people to look at it. Please don't expect us to run code received from complete strangers, especially since you've already told us its got bugs in it! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From __peter__ at web.de Fri Jan 13 05:42:52 2017 From: __peter__ at web.de (Peter Otten) Date: Fri, 13 Jan 2017 11:42:52 +0100 Subject: [Tutor] problem with scroll in Tkinter References: Message-ID: Ali Moradi wrote: > https://paste.pound-python.org/show/CIKA8eOFbdq18r3nFUBv/ > > On Fri, Jan 13, 2017 at 10:25 AM, Ali Moradi > wrote: > >> hi. I've written this code and i can't fix the scrollbar error. i am a >> beginner in Python plz help. this is python3 code. According to http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/listbox-scrolling.html yscrollcommand has to be configured on the list box, i. e. instead of self.scrollbar.config(yscrollcommand=self.listbox.yview) you need self.listbox.config(yscrollcommand=self.scrollbar.set) Other problems: * Chaining grid doesn't work; self.text is set to None here: self.text = tk.Text(self.frame_content, width=60, height=30).grid(row=1, column=1) * You access self.db before you set it. * column=1 is used for both Scrollbar and Text widget. From nicole at resourceinnovations.ca Fri Jan 13 10:40:25 2017 From: nicole at resourceinnovations.ca (Nicole King) Date: Fri, 13 Jan 2017 12:10:25 -0330 Subject: [Tutor] Editing Data in Non Versioned SDE Using python With An Update Cursor Message-ID: Hello, I have a python script that calculates x coordinates , y coordinates for a point geometry that sits within a feature dataset of an SDE (SQL Express). The script worked fine on a file geodatabase however when it runs on the SDE feature class, it stalls at the updateCursor function. "ERROR: 999999: Error executing function....Objects in the class cannot be updated outside an edit session [FSB.DBO.Structures]" The script breaks on updCursor.updateRow(row): workspace = arcpy.env.workspace ="insertworkspace" edit = arcpy.da.Editor(workspace) edit.startEditing(False, True) edit.startOperation() updCursor = arcpy.UpdateCursor(projectedFC,"", spatialRef) for row in updCursor: pnt = row.Shape.getPart(0) row.POINT_X = pnt.X row.POINT_Y = pnt.Y updCursor.updateRow(row) del updCursor, row edit.stopOperation() edit.stopEditing(True) If anyone has any information, ideas or input on editing data in non versioned SDE with a update cursor using python it would be greatly appreciated. Thank you, Nicole King Forest Interpretation Specialist Resource Innovations Inc. Bus: (709) 639-8275 Fax: (709) 639-8758 From s.molnar at sbcglobal.net Fri Jan 13 13:39:28 2017 From: s.molnar at sbcglobal.net (S. P. Molnar) Date: Fri, 13 Jan 2017 13:39:28 -0500 Subject: [Tutor] Incorporate an Integer as part of a Label Message-ID: <58791EE0.2040702@sbcglobal.net> I am a very new python pseudo-programmer (Fortran II was my first language eons ago) and have encountered a problem that is giving me fits (google is no help). I have written a python program that takes the output from a quantum chemistry program, carries out some calculations and saves two files a figure as a png file and the spectrum of the molecule as a csv file. The problem that I am having is incorporating the numerical designator of the molecule in the names of the files. I've managed to figure out how to input the numerical designator: name_1 = input("Enter Molecule Number: ") name_1 =str(name_1) print('Name 1 = ',name_1) name = name_1 + '.out.abs.dat' data_1 = np.loadtxt(name, skiprows=0) As there are two different output files involved with each orca calculation I go through the above lines again for the second file with the dame numerical integer input. The problem is how do I get teh numerical molecule designator into the label I want to use for the two results of the Python calculation? plt.title("Absorption Spectrum ()") plt.savefig('.png', bboxinches='tight') and with open('.csv', 'w') as f: where is the integer molefule number designator that is the only input for the calculation. Thanks in advance. -- Stephen P. Molnar, Ph.D. Life is a fuzzy set www.Molecular-Modeling.net Stochastic and multivariate (614)312-7528 (c) Skype: smolnar1 From zemmoura.khalil at gmail.com Fri Jan 13 17:04:10 2017 From: zemmoura.khalil at gmail.com (ZEMMOURA Khalil Zakaria) Date: Fri, 13 Jan 2017 23:04:10 +0100 Subject: [Tutor] file opened by open() are closed automaticaly Message-ID: <20170113220409.GA2633@sheltron.localdomain> Hi, I am playing with python3.6 and i noticed a change in the behaviour of the open() builtin function. The file opened using open() is closed automaticaly after iterationg over it in the python shell Here is the dummy code i am using: # Beggin testfile = open('test.txt') for line in testfile: print(line) # End the first time the code runs well and gives me the expected result. the secod time that i run the loop, nothing is printed on the screen. when i type: testfile.close and press the tab key to autocomplete: here is what i get >>> testfile.close( testfile.closed when i run that commande and ignore the message: testfile.close() nothing is prined on the terminal, and python runs the commande as if the file is still opened. i searched in the doc and this behaviour is not documented. I don't now if it is a bug or i didn't search in the right place. Thanks From __peter__ at web.de Sat Jan 14 04:45:05 2017 From: __peter__ at web.de (Peter Otten) Date: Sat, 14 Jan 2017 10:45:05 +0100 Subject: [Tutor] file opened by open() are closed automaticaly References: <20170113220409.GA2633@sheltron.localdomain> Message-ID: ZEMMOURA Khalil Zakaria wrote: > Hi, > > I am playing with python3.6 and i noticed a change in the behaviour of the > open() builtin function. > > The file opened using open() is closed automaticaly after iterationg over > it in the python shell > > Here is the dummy code i am using: > > # Beggin > > testfile = open('test.txt') > for line in testfile: > print(line) > > # End > > the first time the code runs well and gives me the expected result. > the secod time that i run the loop, nothing is printed on the screen. That is not new. The file is not closed, you have just reached the end of it >>> f = open("tmp.txt") >>> for line in f: print(line, end="") ... alpha beta gamma >>> for line in f: print(line, end="") ... >>> You can move the file pointer with seek: >>> f.seek(0) 0 >>> for line in f: print(line, end="") ... alpha beta gamma > > when i type: > > testfile.close and press the tab key to autocomplete: > > here is what i get >>>> testfile.close( testfile.closed There is an attribute "closed" that tells you the state of the file and a close() method that closes an open file and does nothing if the file is already closed: >>> f.close() >>> f.closed True >>> f.close() When you try to iterate over a closed file an exception is raised: >>> for line in f: print(line, end="") ... Traceback (most recent call last): File "", line 1, in ValueError: I/O operation on closed file. > when i run that commande and ignore the message: > testfile.close() > nothing is prined on the terminal, and python runs the commande as if the > file is still opened. I doubt that. > i searched in the doc and this behaviour is not documented. The documentation is not as concise as one might wish. Have a look at . > I don't now if it is a bug or i didn't search in the right place. No bug. From __peter__ at web.de Sat Jan 14 04:53:43 2017 From: __peter__ at web.de (Peter Otten) Date: Sat, 14 Jan 2017 10:53:43 +0100 Subject: [Tutor] Incorporate an Integer as part of a Label References: <58791EE0.2040702@sbcglobal.net> Message-ID: S. P. Molnar wrote: > I am a very new python pseudo-programmer (Fortran II was my first > language eons ago) and have encountered a problem that is giving me fits > (google is no help). > > I have written a python program that takes the output from a quantum > chemistry program, carries out some calculations and saves two files a > figure as a png file and the spectrum of the molecule as a csv file. > > The problem that I am having is incorporating the numerical designator > of the molecule in the names of the files. > > I've managed to figure out how to input the numerical designator: > > name_1 = input("Enter Molecule Number: ") > name_1 =str(name_1) > print('Name 1 = ',name_1) > name = name_1 + '.out.abs.dat' > data_1 = np.loadtxt(name, skiprows=0) > > As there are two different output files involved with each orca > calculation I go through the above lines again for the second file with > the dame numerical integer input. > > The problem is how do I get teh numerical molecule designator into the > label I want to use for the two results of the Python calculation? > > plt.title("Absorption Spectrum ()") > > plt.savefig('.png', bboxinches='tight') > > and > > with open('.csv', 'w') as f: > > where is the integer molefule number designator that is the > only input for the calculation. Have a look at the str.format() method: >>> number = 42 >>> title = "absorption spectrum {}".format(number) >>> title 'absorption spectrum 42' There are many bells and whistles: >>> filename = "data-{number:05}.{suffix}".format(number=number, suffix="csv") >>> filename 'data-00042.csv' See for the details. From __peter__ at web.de Sat Jan 14 05:08:54 2017 From: __peter__ at web.de (Peter Otten) Date: Sat, 14 Jan 2017 11:08:54 +0100 Subject: [Tutor] Editing Data in Non Versioned SDE Using python With An Update Cursor References: Message-ID: Nicole King wrote: > Hello, > > > > I have a python script that calculates x coordinates , y coordinates for > a point geometry that sits within a feature dataset of an SDE (SQL > Express). The script worked fine on a file geodatabase however when it > runs on the SDE feature class, it stalls at the updateCursor function. > > > > "ERROR: 999999: Error executing function....Objects in the class cannot be > updated outside an edit session [FSB.DBO.Structures]" > > > > The script breaks on updCursor.updateRow(row): > > > > workspace = arcpy.env.workspace ="insertworkspace" > edit = arcpy.da.Editor(workspace) > > edit.startEditing(False, True) > edit.startOperation() > > updCursor = arcpy.UpdateCursor(projectedFC,"", spatialRef) After reading https://pro.arcgis.com/en/pro-app/arcpy/data-access/updatecursor-class.htm I would guess that the second argument has to be a list of field names, i. e. updCursor = arcpy.UpdateCursor( projectedFC, ["POINT_X", "POINT_Y"], "", spatialRef ) > for row in updCursor: > pnt = row.Shape.getPart(0) > row.POINT_X = pnt.X > row.POINT_Y = pnt.Y > updCursor.updateRow(row) > > del updCursor, row > > edit.stopOperation() > edit.stopEditing(True) > > If anyone has any information, ideas or input on editing data in non > versioned SDE with a update cursor using python it would be greatly > appreciated. The goal of the tutor mailing list is to help newbies with the Python language, the standard library, and common external packages. As yours is a specialist topic you will most likely get better answers when you ask questions concerning arcgis on a dedicated mailing list or forum. From steve at pearwood.info Sat Jan 14 05:09:31 2017 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 14 Jan 2017 21:09:31 +1100 Subject: [Tutor] Editing Data in Non Versioned SDE Using python With An Update Cursor In-Reply-To: References: Message-ID: <20170114100930.GT3887@ando.pearwood.info> On Fri, Jan 13, 2017 at 12:10:25PM -0330, Nicole King wrote: > Hello, > > > > I have a python script that calculates x coordinates , y coordinates for a > point geometry that sits within a feature dataset of an SDE (SQL Express). It looks like you are using arcpy, which is a specialised piece of software that I know very little about. I don't think anyone else here does either, although you might get lucky. But I might try to *guess* an answer. See below. If nobody gives you a good answer, you may have to take your question to a specialised arcpy forum or mailing list. But one thing they will almost certainly want is to see more than just the final error message: > "ERROR: 999999: Error executing function....Objects in the class cannot be > updated outside an edit session [FSB.DBO.Structures]" They will almost certainly want to see the entire traceback, starting from the line Traceback and ending with the error you quoted. Your code is: > workspace = arcpy.env.workspace ="insertworkspace" > edit = arcpy.da.Editor(workspace) > > edit.startEditing(False, True) > edit.startOperation() > > updCursor = arcpy.UpdateCursor(projectedFC,"", spatialRef) > for row in updCursor: > pnt = row.Shape.getPart(0) > row.POINT_X = pnt.X > row.POINT_Y = pnt.Y > updCursor.updateRow(row) > > del updCursor, row > > edit.stopOperation() > edit.stopEditing(True) My *guess* here is that maybe you need to change the "edit.startEditing" line. You have: edit.startEditing(False, True) but maybe it needs to be edit.startEditing(True, True) or something? Try reading the documentation for that command and see if that helps. Good luck! -- Steve From ben+python at benfinney.id.au Sat Jan 14 06:04:21 2017 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 14 Jan 2017 22:04:21 +1100 Subject: [Tutor] file opened by open() are closed automaticaly References: <20170113220409.GA2633@sheltron.localdomain> Message-ID: <85lgudsy16.fsf@benfinney.id.au> ZEMMOURA Khalil Zakaria writes: > The file opened using open() is closed automaticaly after iterationg > over it in the python shell You can interrogate a file to ask whether it is closed; the ?closed? attribute will be True when the file is closed. > testfile = open('test.txt') > for line in testfile: > print(line) What happens if you insert this line before the ?print? statement:: for line in testfile: assert (not testfile.closed), "file was closed unexpectedly!" print(line) If what you say is true, that ?assert? statement will raise an exception with that custom message. > the first time the code runs well and gives me the expected result. > the secod time that i run the loop, nothing is printed on the screen. If you try to read from a file that is already closed, an error occurs:: >>> testfile.close() >>> testfile.readline() Traceback (most recent call last): File "", line 1, in ValueError: I/O operation on closed file. But you're not getting that error. So, some other reason explains the lack of output. -- \ ?? whoever claims any right that he is unwilling to accord to | `\ his fellow-men is dishonest and infamous.? ?Robert G. | _o__) Ingersoll, _The Liberty of Man, Woman and Child_, 1877 | Ben Finney From zemmoura.khalil at gmail.com Sat Jan 14 18:09:20 2017 From: zemmoura.khalil at gmail.com (ZEMMOURA Khalil Zakaria) Date: Sun, 15 Jan 2017 00:09:20 +0100 Subject: [Tutor] file opened by open() are closed automaticaly In-Reply-To: References: <20170113220409.GA2633@sheltron.localdomain> Message-ID: <20170114230919.GB4447@sheltron.localdomain> Thanks a lot. that helped me to understand that behaviour. Best regards. From adeadmarshal at gmail.com Mon Jan 16 10:11:45 2017 From: adeadmarshal at gmail.com (Ali Moradi) Date: Mon, 16 Jan 2017 18:41:45 +0330 Subject: [Tutor] Searching db while typing on Entry widget Message-ID: Hi. i want to search one field of my db while i type text in my Entry widget. how can i do that? and another problem is that now when i click on one of the item lists it always writes the first field of my db in the Text widget, i think i did the loop wrong maybe but i am not sure. #! /usr/bin/env python3 #GeologyDict by Ali M import sqlite3 as sqlite import tkinter as tk from tkinter import Text from tkinter import Entry from tkinter import Scrollbar from tkinter import ttk #GUI Widgets class GeologyDict: def __init__(self, master): master.title("EsperantoDict") master.resizable(False, False) master.configure(background='#EAFFCD') self.style = ttk.Style() self.style.configure("TFrame", background='#EAFFCD') self.style.configure("TButton", background='#EAFFCD') self.style.configure("TLabel", background='#EAFFCD') self.frame_header = ttk.Frame(master, relief=tk.FLAT) self.frame_header.pack(side=tk.TOP, padx=5, pady=5) self.logo = tk.PhotoImage(file=r'C:\Geologydict\eo.png') self.small_logo = self.logo.subsample(10, 10) ttk.Label(self.frame_header, image=self.small_logo).grid(row=0, column=0, stick="ne", padx=5, pady=5, rowspan=2) ttk.Label(self.frame_header, text='EsperantoDict', font=('Arial', 18, 'bold')).grid(row=0, column=1) self.frame_content = ttk.Frame(master) self.frame_content.pack() self.entry_search = ttk.Entry(self.frame_content) self.entry_search.grid(row=0, column=0) self.entry_search.insert(tk.END, "Type to Search") self.entry_search.bind('', self.entry_delete) self.button_search = ttk.Button(self.frame_content, text="Search") aks = tk.PhotoImage(file=r'C:\Geologydict\search.png') small_aks = aks.subsample(3, 3) self.button_search.config(image=small_aks, compound=tk.LEFT) self.button_search.grid(row=0, column=1, columnspan=2) self.listbox = tk.Listbox(self.frame_content, height=28) self.listbox.grid(row=1, column=0) self.scrollbar = ttk.Scrollbar(self.frame_content, orient=tk.VERTICAL, command=self.listbox.yview) self.scrollbar.grid(row=1, column=1, sticky='ns') self.listbox.config(yscrollcommand=self.scrollbar.set) self.listbox.bind('<>', self.enter_meaning) self.textbox = tk.Text(self.frame_content, width=60, height=27) self.textbox.grid(row=1, column=2) # SQLite self.db = sqlite.connect(r'C:\Geologydict\test.db') self.cur = self.db.cursor() self.cur.execute('SELECT Esperanto FROM words') for row in self.cur: self.listbox.insert(tk.END, row) # SQLite def enter_meaning(self, tag): if self.listbox.curselection(): self.cur.execute('SELECT English FROM words') for row in self.cur: self.cur.fetchall() self.textbox.insert(tk.END, row) def entry_delete(self, tag): self.entry_search.delete(0, tk.END) return None def main(): root = tk.Tk() geologydict = GeologyDict(root) root.mainloop() if __name__ == '__main__': main() From alan.gauld at yahoo.co.uk Mon Jan 16 19:08:55 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 17 Jan 2017 00:08:55 +0000 Subject: [Tutor] Searching db while typing on Entry widget In-Reply-To: References: Message-ID: On 16/01/17 15:11, Ali Moradi wrote: > Hi. i want to search one field of my db while i type text in my Entry > widget. how can i do that? Assuming you mean a live search type of thing, like Google etc do then you need to bind the keypress (or maybe the key-up) event to a function that does the search based on the current contents of the entry box. > and another problem is that now when i click on > one of the item lists it always writes the first field of my db in the Text > widget, i think i did the loop wrong maybe but i am not sure. #! ... > > def enter_meaning(self, tag): > if self.listbox.curselection(): > self.cur.execute('SELECT English FROM words') > for row in self.cur: > self.cur.fetchall() I suspect this should be outside the loop? You presumably only want to fetchall once? And then you want to loop over the results you retrieved? [Alternatively you can loop over the cursor without the fetchall. I've never actually tried that approach but it should work... Most of the examples I've seen use the execute call as the iteration though: for row in cur.execute(....): but iterating over the cursor after execute might work too. But you should only use one of those techniques not both. ] Normally I'd do something like: cur.execute(...) for row in cur.fetchall(): process(row) HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From __peter__ at web.de Tue Jan 17 05:12:17 2017 From: __peter__ at web.de (Peter Otten) Date: Tue, 17 Jan 2017 11:12:17 +0100 Subject: [Tutor] Searching db while typing on Entry widget References: Message-ID: Ali Moradi wrote: > Hi. i want to search one field of my db while i type text in my Entry > widget. how can i do that? Use a StringVar and set a callback with its trace() method: http://effbot.org/tkinterbook/variable.htm > and another problem is that now when i click on > one of the item lists it always writes the first field of my db in the > Text widget, i think i did the loop wrong maybe but i am not sure. As Alan says, either use fetchall() or iterate over the cursor What you do: # wrong! for row in cursor: # fist iteration: row is now the first match cursor.fetchall() # iterates over the remaining matches # and discards them. Therefore there are no # iterations for the containing loop. insert_into_text(row) I dabbled with your code and will give my version below because there are enough changes that a diff will be hard to read. If the database table is big updating the Text widget directly in the trace callback will get slow, but for the small sample data that I used it worked sufficiently well. One simple quick fix would be to require a minimum length of the search string, but if you want to do it right you have to move the search into a separate thread and populate the Text widget from that. import sqlite3 as sqlite import tkinter as tk from tkinter import Entry, Scrollbar, Text from tkinter import ttk class GeologyDict: def __init__(self, master): master.title("EsperantoDict") master.resizable(False, False) master.configure(background='#EAFFCD') self.style = ttk.Style() self.style.configure("TFrame", background='#EAFFCD') self.style.configure("TButton", background='#EAFFCD') self.style.configure("TLabel", background='#EAFFCD') self.frame_header = ttk.Frame(master, relief=tk.FLAT) self.frame_header.pack(side=tk.TOP, padx=5, pady=5) self.logo = tk.PhotoImage(file=r'C:\Geologydict\eo.png') self.small_logo = self.logo.subsample(10, 10) label = ttk.Label(self.frame_header, image=self.small_logo) label.grid( row=0, column=0, stick="ne", padx=5, pady=5, rowspan=2 ) label = ttk.Label( self.frame_header, text='EsperantoDict', font=('Arial', 18, 'bold') ) label.grid(row=0, column=1) self.frame_content = ttk.Frame(master) self.frame_content.pack() self.entry_var = tk.StringVar() self.entry_search = ttk.Entry( self.frame_content, textvariable=self.entry_var ) self.entry_search.grid(row=0, column=0) self.entry_search.insert(tk.END, "Type to Search") self.entry_search.bind('', self.entry_delete) self.button_search = ttk.Button( self.frame_content, text="Search" ) aks = tk.PhotoImage(file=r'C:\Geologydict\search.png') small_aks = aks.subsample(3, 3) self.button_search.config(image=small_aks, compound=tk.LEFT) self.button_search.grid(row=0, column=1, columnspan=2) self.listbox = tk.Listbox(self.frame_content, height=28) self.listbox.grid(row=1, column=0) self.scrollbar = ttk.Scrollbar( self.frame_content, orient=tk.VERTICAL, command=self.listbox.yview ) self.scrollbar.grid(row=1, column=1, sticky='ns') self.listbox.config(yscrollcommand=self.scrollbar.set) self.listbox.bind('<>', self.listbox_select) self.textbox = tk.Text(self.frame_content, width=60, height=27) self.textbox.grid(row=1, column=2) self.db = sqlite.connect(r'C:\Geologydict\test.db') self.cur = self.db.cursor() self.cur.execute('SELECT Esperanto FROM words') for row in self.cur: self.listbox.insert(tk.END, row) self.entry_var.trace("w", self.trace_entry) def trace_entry(self, *args): try: text = self.entry_var.get() self.enter_meaning(text, exact=False) except Exception as err: print(err) def listbox_select(self, event): text = self.listbox.get( self.listbox.curselection()[0] )[0] self.enter_meaning(text, exact=True) def enter_meaning(self, token, exact=False): if exact: sql = ( 'SELECT Esperanto, English ' 'FROM words ' 'WHERE Esperanto = ?' ) else: sql = ( 'SELECT Esperanto, English ' 'FROM words ' 'WHERE Esperanto like ?' ) token = "%" + token.replace("%", "%%") + '%' self.cur.execute(sql, (token,)) self.textbox.delete("1.0", tk.END) text = "\n\n".join( "{}. {} ? {}".format(index, *row) for index, row in enumerate(self.cur, 1) ) self.textbox.insert(tk.END, text) def entry_delete(self, tag): self.entry_search.delete(0, tk.END) return None def main(): root = tk.Tk() geologydict = GeologyDict(root) root.mainloop() if __name__ == '__main__': main() From highseaspb at earthlink.net Tue Jan 17 21:36:19 2017 From: highseaspb at earthlink.net (Laura Meldrum) Date: Tue, 17 Jan 2017 18:36:19 -0800 (GMT-08:00) Subject: [Tutor] How can we learn to use Python Message-ID: <16205000.10893.1484706980183@wamui-mosaic.atl.sa.earthlink.net> HELP, PLEASE www.sololearn.com/Play/Python/hoc says to "download the Python 3.x version that is compatible with your operating system" OK, but when I go to https://www.python.org/downloads/windows/ there is a seemingly endless list of possible downloads. What should I and my students download so they can learn some coding through https://www.sololearn.com/hour-of-code/? And, What if some students have MACs? Please advise. Laura From alan.gauld at yahoo.co.uk Wed Jan 18 05:15:48 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 18 Jan 2017 10:15:48 +0000 Subject: [Tutor] How can we learn to use Python In-Reply-To: <16205000.10893.1484706980183@wamui-mosaic.atl.sa.earthlink.net> References: <16205000.10893.1484706980183@wamui-mosaic.atl.sa.earthlink.net> Message-ID: On 18/01/17 02:36, Laura Meldrum wrote: > www.sololearn.com/Play/Python/hoc says to "download the Python 3.x version > that is compatible with your operating system" So the first question is - what is your operating system? Assuming it is a version of Windows then you next need to find out whether it is 32bit or 64bit. Prior to version 8 you can do that via the MyComputer icon and right-clicking to get the properties dialog. On windows 8 upwards you go to Settings->System->About. Listed in the details will be a note about whether it is 32bit or 64 bit. Now you can go to the python.org web site and navigate to the Python 3.6 Windows Download section https://www.python.org/downloads/release/python-360/ where you should find options like: Windows x86-64 executable installer for 64 bit PCs and Windows x86 executable installer for 32 bit PCs. Download whichever is appropriate. You might want to also download the Windows Help File since that will integrate better with your OS and save you visiting the Python web site as often, but it's not an essential item. Finally, there is an alternative download site that I usually recommend for Windows programmers called Activestate.com and its Python package has some extra tools and features specifically for Windows programmers, but if you are complete programming beginners you probably don't need those yet. > And, What if some students have MACs? Macs have Python installed by defauilt so they can just open a Terminal window and type python at the prompt. This version is fine for learning the basics. BUT it is an older version of Python so you are probably better installing the latest version... On the same download page there is an option: Mac OS X 64-bit/32-bit installer BUT, there are a few issues for Mac users especially if you plan on using the IDLE development environment. In that case I recommend going to the activestate.com web site and downloading their free community editions of Activepython and ActiveTcl for Mac. That should avoid any of the issues. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From sarika1989.08 at gmail.com Wed Jan 18 05:18:50 2017 From: sarika1989.08 at gmail.com (Sarika Shrivastava) Date: Wed, 18 Jan 2017 15:48:50 +0530 Subject: [Tutor] How can I run this test script using selenium while making connection and running the code I am facing issue Please see my code below Message-ID: import unittest from selenium import webdriver from selenium.webdriver.common.keys import Keys import time class PythonOrgSearch(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome('C:\Users\uidk9685\Downloads\chromedriver.exe') # print self.driver time.sleep(0.5) def test_search_in_python_org(self): driver = self.driver # driver.get("http://www.python.org") # self.assertIn("Python", driver.title) # elem = driver.find_element_by_name("q") # elem.send_keys("pycon") # elem.send_keys(Keys.RETURN) # assert "No results found." not in driver.page_source def tearDown(self): pass # self.driver.close() if __name__ == "__main__": unittest.main() [image: Inline image 2] -- Best regards, Sarika Shrivastava Associate Engineer Continental Automotive Components (India) Pvt. Ltd., 8th Floor, Gold Hill Supreme Software Park, Plot No. 21, 22, 27 & 28, Shanthipura Road, Electronics City, Phase II, Hosur Road, Bangalore-560 100 Tel: +919741457409 Mobile: +919741457409 E-Mail: sarika.shrivastava at continental-corporation.com Web: www.continental-corporation.com From george at fischhof.hu Wed Jan 18 07:35:39 2017 From: george at fischhof.hu (George Fischhof) Date: Wed, 18 Jan 2017 13:35:39 +0100 Subject: [Tutor] How can I run this test script using selenium while making connection and running the code I am facing issue Please see my code below In-Reply-To: References: Message-ID: 2017-01-18 11:18 GMT+01:00 Sarika Shrivastava : > import unittest > from selenium import webdriver > from selenium.webdriver.common.keys import Keys > import time > > class PythonOrgSearch(unittest.TestCase): > > def setUp(self): > self.driver = > webdriver.Chrome('C:\Users\uidk9685\Downloads\chromedriver.exe') > # print self.driver > time.sleep(0.5) > > def test_search_in_python_org(self): > driver = self.driver > > # driver.get("http://www.python.org") > # self.assertIn("Python", driver.title) > # elem = driver.find_element_by_name("q") > # elem.send_keys("pycon") > # elem.send_keys(Keys.RETURN) > # assert "No results found." not in driver.page_source > > > def tearDown(self): > pass > # self.driver.close() > > if __name__ == "__main__": > unittest.main() > > > > > [image: Inline image 2] > -- > Best regards, > > Sarika Shrivastava > Associate Engineer > > Continental Automotive Components (India) Pvt. Ltd., > 8th Floor, Gold Hill Supreme Software Park, > Plot No. 21, 22, 27 & 28, Shanthipura Road, > Electronics City, Phase II, Hosur Road, > Bangalore-560 100 > > Tel: +919741457409 > Mobile: +919741457409 > E-Mail: sarika.shrivastava at continental-corporation.com > Web: www.continental-corporation.com > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > Hi Sarika, maybe it is better and easyer to use pytest instead of unittest. pytest automaticallt finds the tests in files named test_*.py or *_test.py, and will run functions with the similar names. You can find pytest documentation on the following link: http://docs.pytest.org/en/latest/ and pytest can be installed by pip: pip install pytest BR, George From george at fischhof.hu Wed Jan 18 07:45:37 2017 From: george at fischhof.hu (George Fischhof) Date: Wed, 18 Jan 2017 13:45:37 +0100 Subject: [Tutor] How can I run this test script using selenium while making connection and running the code I am facing issue Please see my code below In-Reply-To: References: Message-ID: 2017-01-18 11:18 GMT+01:00 Sarika Shrivastava : > import unittest > from selenium import webdriver > from selenium.webdriver.common.keys import Keys > import time > > class PythonOrgSearch(unittest.TestCase): > > def setUp(self): > self.driver = > webdriver.Chrome('C:\Users\uidk9685\Downloads\chromedriver.exe') > # print self.driver > time.sleep(0.5) > > def test_search_in_python_org(self): > driver = self.driver > > # driver.get("http://www.python.org") > # self.assertIn("Python", driver.title) > # elem = driver.find_element_by_name("q") > # elem.send_keys("pycon") > # elem.send_keys(Keys.RETURN) > # assert "No results found." not in driver.page_source > > > def tearDown(self): > pass > # self.driver.close() > > if __name__ == "__main__": > unittest.main() > > > > > [image: Inline image 2] > -- > Best regards, > > Sarika Shrivastava > Associate Engineer > > Continental Automotive Components (India) Pvt. Ltd., > 8th Floor, Gold Hill Supreme Software Park, > Plot No. 21, 22, 27 & 28, Shanthipura Road, > Electronics City, Phase II, Hosur Road, > Bangalore-560 100 > > Tel: +919741457409 > Mobile: +919741457409 > E-Mail: sarika.shrivastava at continental-corporation.com > Web: www.continental-corporation.com > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > I am sorry, I saw only the first part of the title of Your message. And I thought that You have issues with the unittest framework. For web automation I use the library splinter, which uses selenium, but it is easier. BR, George From sarika1989.08 at gmail.com Wed Jan 18 21:29:06 2017 From: sarika1989.08 at gmail.com (Sarika Shrivastava) Date: Thu, 19 Jan 2017 07:59:06 +0530 Subject: [Tutor] How can I run this test script using selenium while making connection and running the code I am facing issue Please see my code below In-Reply-To: References: Message-ID: Yes I dont have issue with unittest framework but i dont have to reconized my issue How can I resolve this issue ?? So I need to use splinter??? On Thu, Jan 19, 2017 at 7:56 AM, Sarika Shrivastava wrote: > Yes I dont have issue with unittest framework but i dont have to reconized > my issue How can I resolve this issue ?? > So I need to use splinter??? > > On Wed, Jan 18, 2017 at 6:15 PM, George Fischhof > wrote: > >> >> >> 2017-01-18 11:18 GMT+01:00 Sarika Shrivastava : >> >>> import unittest >>> from selenium import webdriver >>> from selenium.webdriver.common.keys import Keys >>> import time >>> >>> class PythonOrgSearch(unittest.TestCase): >>> >>> def setUp(self): >>> self.driver = >>> webdriver.Chrome('C:\Users\uidk9685\Downloads\chromedriver.exe') >>> # print self.driver >>> time.sleep(0.5) >>> >>> def test_search_in_python_org(self): >>> driver = self.driver >>> >>> # driver.get("http://www.python.org") >>> # self.assertIn("Python", driver.title) >>> # elem = driver.find_element_by_name("q") >>> # elem.send_keys("pycon") >>> # elem.send_keys(Keys.RETURN) >>> # assert "No results found." not in driver.page_source >>> >>> >>> def tearDown(self): >>> pass >>> # self.driver.close() >>> >>> if __name__ == "__main__": >>> unittest.main() >>> >>> >>> >>> >>> [image: Inline image 2] >>> -- >>> Best regards, >>> >>> Sarika Shrivastava >>> Associate Engineer >>> >>> Continental Automotive Components (India) Pvt. Ltd., >>> 8th Floor, Gold Hill Supreme Software Park, >>> Plot No. 21, 22, 27 & 28, Shanthipura Road, >>> Electronics City, Phase II, Hosur Road, >>> Bangalore-560 100 >>> >>> Tel: +919741457409 <+91%2097414%2057409> >>> Mobile: +919741457409 <+91%2097414%2057409> >>> E-Mail: sarika.shrivastava at continental-corporation.com >>> Web: www.continental-corporation.com >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> https://mail.python.org/mailman/listinfo/tutor >>> >> >> >> I am sorry, I saw only the first part of the title of Your message. And I >> thought that You have issues with the unittest framework. >> For web automation I use the library splinter, which uses selenium, but >> it is easier. >> >> BR, >> George >> > > > > -- > Best regards, > > Sarika Shrivastava > Associate Engineer > > Continental Automotive Components (India) Pvt. Ltd., > 8th Floor, Gold Hill Supreme Software Park, > Plot No. 21, 22, 27 & 28, Shanthipura Road, > Electronics City, Phase II, Hosur Road, > Bangalore-560 100 > > Tel: +919741457409 <+91%2097414%2057409> > Mobile: +919741457409 <+91%2097414%2057409> > E-Mail: sarika.shrivastava at continental-corporation.com > Web: www.continental-corporation.com > -- Best regards, Sarika Shrivastava Associate Engineer Continental Automotive Components (India) Pvt. Ltd., 8th Floor, Gold Hill Supreme Software Park, Plot No. 21, 22, 27 & 28, Shanthipura Road, Electronics City, Phase II, Hosur Road, Bangalore-560 100 Tel: +919741457409 Mobile: +919741457409 E-Mail: sarika.shrivastava at continental-corporation.com Web: www.continental-corporation.com From alan.gauld at yahoo.co.uk Thu Jan 19 05:43:27 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 19 Jan 2017 10:43:27 +0000 Subject: [Tutor] How can I run this test script using selenium while making connection and running the code I am facing issue Please see my code below In-Reply-To: References: Message-ID: On 19/01/17 02:29, Sarika Shrivastava wrote: > Yes I dont have issue with unittest framework but i dont have to reconized > my issue How can I resolve this issue ?? What is the issue? You haven't told us what is wrong. What happens? What did you expect to happen? Are there any error messages? If so post them so we can see. Since the code you have posted does virtually nothing it's hard to guess what might be going wrong. > So I need to use splinter??? Probably not, since splinter is built on top of selenium. But it might be slightly easier to use - I don't know since I've never heard of it before. >>>> import unittest >>>> from selenium import webdriver >>>> from selenium.webdriver.common.keys import Keys >>>> import time >>>> >>>> class PythonOrgSearch(unittest.TestCase): >>>> >>>> def setUp(self): >>>> self.driver = >>>> webdriver.Chrome('C:\Users\uidk9685\Downloads\chromedriver.exe') >>>> # print self.driver >>>> time.sleep(0.5) >>>> >>>> def test_search_in_python_org(self): >>>> driver = self.driver This line doesn't do much, it only saves you typing 'self.' twice in the commented code. >>>> >>>> # driver.get("http://www.python.org") >>>> # self.assertIn("Python", driver.title) >>>> # elem = driver.find_element_by_name("q") >>>> # elem.send_keys("pycon") >>>> # elem.send_keys(Keys.RETURN) >>>> # assert "No results found." not in driver.page_source >>>> >>>> >>>> def tearDown(self): >>>> pass >>>> # self.driver.close() >>>> >>>> if __name__ == "__main__": >>>> unittest.main() >>>> >>>> [image: Inline image 2] I'm not sure if this image was relevant or not but as a text based list images often get stripped by the server... If there was useful information in it you will need to describe it or, if it was textual, paste it into the body Finally, selenium is a bit off-topic for this list since it's not part of the core library or language. You might get a better response on the selenium support forum. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From adsquaired at gmail.com Thu Jan 19 16:29:16 2017 From: adsquaired at gmail.com (ad^2) Date: Thu, 19 Jan 2017 16:29:16 -0500 Subject: [Tutor] Another way to strip? Message-ID: Hello all, I'm looking for a cleaner more elegant way to achieve stripping out a file name from a list which contains a path and file extension. Ex. my_list = ['/var/tmp/02_80_5306_4444_2017_01_19_08-36-57_4918_0.zip', '/var/tmp/02_80_5309_4444_2017_01_19_08-40-30_4205_0.zip', '/var/tmp/02_80_5302_4444_2017_01_19_08-40-07_2536_0.zip', '/var/tmp/02_80_5302_4444_2017_01_19_09-03-30_8831_0.zip', '/var/tmp/02_80_5303_4444_2017_01_19_08-39-42_8677_0.zip', '/var/tmp/02_80_5308_4444_2017_01_19_08-39-06_7600_0.zip', '/var/tmp/02_80_5305_4444_2017_01_19_08-37-24_4699_0.zip', '/var/tmp/02_80_5309_4444_2017_01_19_08-40-30_4205_1.zip', '/var/tmp/02_80_5304_4444_2017_01_19_08-40-55_8450_0.zip', '/var/tmp/02_80_5301_4444_2017_01_19_08-38-22_6999_0.zip', '/var/tmp/02_80_5307_4444_2017_01_19_08-38-09_1763_0.zip'] >>> for i in my_list: ... i.strip('/var/tmp/.zip') '02_80_5306_4444_2017_01_19_08-36-57_4918_0' '02_80_5309_4444_2017_01_19_08-40-30_4205_0' '02_80_5302_4444_2017_01_19_08-40-07_2536_0' '02_80_5302_4444_2017_01_19_09-03-30_8831_0' '02_80_5303_4444_2017_01_19_08-39-42_8677_0' '02_80_5308_4444_2017_01_19_08-39-06_7600_0' '02_80_5305_4444_2017_01_19_08-37-24_4699_0' '02_80_5309_4444_2017_01_19_08-40-30_4205_1' '02_80_5304_4444_2017_01_19_08-40-55_8450_0' '02_80_5301_4444_2017_01_19_08-38-22_6999_0' '02_80_5307_4444_2017_01_19_08-38-09_1763_0' or in the case the directory may change in the future I can use variables somewhere. >>> path = '/var/tmp/' >>> extension = '.zip' for i in my_list: ... i.strip(path + extension) ... '02_80_5306_4444_2017_01_19_08-36-57_4918_0' '02_80_5309_4444_2017_01_19_08-40-30_4205_0' ......... ....... ...... ... The results are what I need but is there another way to perform the same thing? Thanks, ad^2 From alan.gauld at yahoo.co.uk Thu Jan 19 19:40:46 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 20 Jan 2017 00:40:46 +0000 Subject: [Tutor] Another way to strip? In-Reply-To: References: Message-ID: On 19/01/17 21:29, ad^2 wrote: > I'm looking for a cleaner more elegant way to achieve stripping out a file > name from a list which contains a path and file extension. > > Ex. > > my_list = ['/var/tmp/02_80_5306_4444_2017_01_19_08-36-57_4918_0.zip', > '/var/tmp/02_80_5309_4444_2017_01_19_08-40-30_4205_0.zip', Take a look at the os.path module. It has lots of utility functions for splitting paths into their various bits and as a bonus it caters for all the different OS path formats too. Its likely to be both easier to use and more reliable than trying to use string functions on the path. In your case os.path.basename() is likely to be the best option. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From dyoo at hashcollision.org Thu Jan 19 19:42:03 2017 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 19 Jan 2017 16:42:03 -0800 Subject: [Tutor] Another way to strip? In-Reply-To: References: Message-ID: On Jan 19, 2017 4:36 PM, "ad^2" wrote: Hello all, I'm looking for a cleaner more elegant way to achieve stripping out a file name from a list which contains a path and file extension. Would os.path.split help here? https://docs.python.org/3.6/library/os.path.html#os.path.split From steve at pearwood.info Thu Jan 19 19:53:09 2017 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 20 Jan 2017 11:53:09 +1100 Subject: [Tutor] Another way to strip? In-Reply-To: References: Message-ID: <20170120005309.GE7345@ando.pearwood.info> On Thu, Jan 19, 2017 at 04:29:16PM -0500, ad^2 wrote: > Hello all, > > I'm looking for a cleaner more elegant way to achieve stripping out a file > name from a list which contains a path and file extension. > > Ex. > > my_list = ['/var/tmp/02_80_5306_4444_2017_01_19_08-36-57_4918_0.zip', > '/var/tmp/02_80_5309_4444_2017_01_19_08-40-30_4205_0.zip', [...] > '/var/tmp/02_80_5307_4444_2017_01_19_08-38-09_1763_0.zip'] > > >>> for i in my_list: > ... i.strip('/var/tmp/.zip') That doesn't do what you think it does! That strips off each individual character '/', 'v', 'a', 'r', ... 'i', 'p' from the front and back of the string. If the format of the name changes, this could be disasterous: py> path = '/var/tmp/tz-19_08-40-30_4205-a.zip' py> path.strip('/var/tmp/.zip') # expecting tz-19_08-40-30_4205-a '-19_08-40-30_4205-' What you want is the basename of the path, less the extension: py> import os py> path = '/var/tmp/02_80_5309_4444_2017_01_19_08-40-30_4205_0.zip' py> os.path.basename(path) '02_80_5309_4444_2017_01_19_08-40-30_4205_0.zip' py> os.path.splitext(os.path.basename(path))[0] '02_80_5309_4444_2017_01_19_08-40-30_4205_0' That's a bit unwieldy, so create a helper function: import os def base(path): return os.path.splitext(os.path.basename(path))[0] Now you can safely use this on your list: for path in my_list: print(base(path)) Or if you want a new list, you can use a list comprehension: filenames = [base(path) for path in my_list] or the map() function: # Python 2 filenames = map(base, my_list) # Python 3 filenames = list(map(base, my_list)) -- Steve From sourceonly at gmail.com Tue Jan 24 21:55:30 2017 From: sourceonly at gmail.com (source liu) Date: Wed, 25 Jan 2017 02:55:30 +0000 Subject: [Tutor] Feature or ... after python 2.7 Message-ID: Hi?list Yesterday, someone hacked in my server and running some bad thing , but I do find something interesting After I inspected processes, I found if you are using python version above 2.7. (2.7.16 if I remembered it correctly), one could run python script with perl $cat test.py #!/bin/env python print "I am python" $perl test.py I am python But it would fail if you tried to use python2.6(which go with rhel6.8) really interesting From alan.gauld at yahoo.co.uk Wed Jan 25 04:03:24 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 25 Jan 2017 09:03:24 +0000 Subject: [Tutor] Feature or ... after python 2.7 In-Reply-To: References: Message-ID: On 25/01/17 02:55, source liu wrote: > 2.7. (2.7.16 if I remembered it correctly), one could run python script > with perl > > $cat test.py > #!/bin/env python > print "I am python" > > > $perl test.py > I am python > That is just because this particular print statement is compatible with Perl. If you had tried anything more complex then it would have bombed. > But it would fail if you tried to use python2.6(which go with rhel6.8) I'm not sure what you mean here but you could run the code above in any version of Python v2 or perl and it should work. The first6 line is a comment so ignored by both perl and python. And the print statement works in both languages. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From sourceonly at gmail.com Wed Jan 25 12:32:36 2017 From: sourceonly at gmail.com (source liu) Date: Wed, 25 Jan 2017 17:32:36 +0000 Subject: [Tutor] Feature or ... after python 2.7 In-Reply-To: References: Message-ID: On Wed, 25 Jan 2017 at 17:07 Alan Gauld via Tutor wrote: > On 25/01/17 02:55, source liu wrote: > > > 2.7. (2.7.16 if I remembered it correctly), one could run python script > > with perl > > > > $cat test.py > > #!/bin/env python > > print "I am python" > > > > > > $perl test.py > > I am python > > > > That is just because this particular print statement > is compatible with Perl. If you had tried anything > more complex then it would have bombed. > How to you define complex? The script import lots of modules such as urllib2 > > > But it would fail if you tried to use python2.6(which go with rhel6.8) > > I'm not sure what you mean here but you could run the > code above in any version of Python v2 or perl and > it should work. The first6 line is a comment so > ignored by both perl and python. And the print > statement works in both languages. My fault, the PYTHONPATH is not correct with my Python 2.6 , which misleading me to think Python 2.6 can't do this > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > http://www.flickr.com/photos/alangauldphotos > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Liu An Institution of modern physics, Shanghai, China From alan.gauld at yahoo.co.uk Wed Jan 25 19:12:02 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 26 Jan 2017 00:12:02 +0000 Subject: [Tutor] Feature or ... after python 2.7 In-Reply-To: References: Message-ID: On 25/01/17 17:32, source liu wrote: >>> $cat test.py >>> #!/bin/env python >>> print "I am python" >>> >>> $perl test.py >>> I am python >>> >> >> That is just because this particular print statement >> is compatible with Perl. If you had tried anything >> more complex then it would have bombed. > > How to you define complex? The script import lots of modules such as > urllib2 The script above doesn't, it just has a single print line. That's why Perl is able to run it. If it had any import statements Perl would complain. When you type perl filename The perl interpreter tries to run the file regardless of its extension or the shebang hint in the first line. If it looks like valid perl (which the print is) then it will execute it. Similarly when you run python filename Python will do the same, the interpreter doesn't care what the file is called or what the shebang line says it just tries to run the text in the file. The file extension and/or shebang line only matter to the OS and its shell. (and even then only in specific cases) Now where urlib2 comes into the picture I have no idea because you didn't mention that previously. But I'm pretty sure both Python 2.7 and 2.6 will know what to do with it whereas perl will not but it will try to execute its own import method (which fails silently...). But it will almost certainly fail when you try to use the features of the imported modules. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From brian.wiley at sap.com Wed Jan 25 15:56:40 2017 From: brian.wiley at sap.com (Wiley, Brian) Date: Wed, 25 Jan 2017 20:56:40 +0000 Subject: [Tutor] cannot open idle in 3.6 version but can in 2.7 Message-ID: <0d4840d9aa404ecc8b72fb9bd8286ea2@USPHLE13US04.global.corp.sap> Hi there, I would like to learn and utilize both python versions. For some reason when access shell for 3.6 I get this message: "Your Python may not be configured for Tk. **", file=sys.__stderr__) How can I make sure both work? Brian Wiley GCO Sales Technology and Support | 1st Level Support On behalf of SAP SE Global Customer Operations | Global Customer Strategy and Business Operations | Sales Tools, Technology & BIO | Applications Enablement & Support SAP Americas | 4343 N. Scottsdale Rd | Scottsdale, AZ 85251 | UNITED STATES T +1 (610) 661-8935 | M +1 (610) 220-0892 E brian.wiley at sap.com www.sap.com "Here lies a man who knew how to enlist in his service better [people] than himself" - Andrew Carnegie's Tombstone Please click here for all your self-learning needs Or launch Sales Central by clicking the icon below [cid:image001.png at 01D1A093.B3F2B740] End User Support contact information: Email: gco_app_assistance at sap.com Service Request: GCO Shared Service Framework Americas 1-604-974-3647 APJ +6567058540 EMEA/MEE +496227779212 P Please consider the impact on the environment before printing this e-mail. Pflichtangaben/Mandatory Disclosure Statement: http://www.sap.com/company/legal/impressum.epx Diese E-Mail kann Betriebs- oder Gesch?ftsgeheimnisse oder sonstige vertrauliche Informationen enthalten. Sollten Sie diese E-Mail irrt?mlich erhalten haben, ist Ihnen eine Kenntnisnahme des Inhalts, eine Vervielf?ltigung oder Weitergabe der E-Mail ausdr?cklich untersagt. Bitte benachrichtigen Sie uns und vernichten Sie die empfangene E-Mail. Vielen Dank. This e-mail may contain trade secrets or privileged, undisclosed, or otherwise confidential information. If you have received this e-mail in error, you are hereby notified that any review, copying, or distribution of it is strictly prohibited. Please inform us immediately and destroy the original transmittal. Thank you for your cooperation. From alan.gauld at yahoo.co.uk Thu Jan 26 03:51:53 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 26 Jan 2017 08:51:53 +0000 Subject: [Tutor] cannot open idle in 3.6 version but can in 2.7 In-Reply-To: <0d4840d9aa404ecc8b72fb9bd8286ea2@USPHLE13US04.global.corp.sap> References: <0d4840d9aa404ecc8b72fb9bd8286ea2@USPHLE13US04.global.corp.sap> Message-ID: On 25/01/17 20:56, Wiley, Brian wrote: > I would like to learn and utilize both python versions. > For some reason when access shell for 3.6 I get this message: > > "Your Python may not be configured for Tk. **", file=sys.__stderr__) That usually means you've installed a Python that has not been built with the Tk bindings. You need to find a Tk compatible version. Which OS are you using? Where/how did you get your Python 3.6? If you compiled from source you need to go into the config file before building - ISTR you can do that by running make config... But there are probably pre-built binaries for your OS somewhere. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From guest0x013 at gmail.com Fri Jan 27 12:12:28 2017 From: guest0x013 at gmail.com (Freedom Peacemaker) Date: Fri, 27 Jan 2017 18:12:28 +0100 Subject: [Tutor] randomly generated error Message-ID: Hi, main idea was to : - get random characters word - randomly colour letters in my word - from this coloured word print all yellow letters As it is random i need to be sure that at least one letter is yellow so i put yellow color into final variable. This code works but randomly generates error. And i have no idea how solve this problem. Please help me Traceback (most recent call last): File "proj3", line 23, in w = "".join((colorpass[i.end()]) for i in re.finditer(re.escape(Y), colorpass)) File "proj3", line 23, in w = "".join((colorpass[i.end()]) for i in re.finditer(re.escape(Y), colorpass)) IndexError: string index out of range This is my code: from random import choice from string import ascii_letters, digits import re chars = ascii_letters + digits word = "".join([choice(chars) for i in range(10)]) R = '\033[31m' # red G = '\033[32m' # green B = '\033[34m' # blue P = '\033[35m' # purple Y = '\033[93m' # yellow colors = [R, G, B, P, Y] colorpass = "\033[93m" for char in word: colorpass += char + choice(colors) print(colorpass) w = "".join((colorpass[i.end()]) for i in re.finditer(re.escape(Y), colorpass)) print(w) I am using Python 3.5.2 on Ubuntu 16.04 From __peter__ at web.de Fri Jan 27 15:18:42 2017 From: __peter__ at web.de (Peter Otten) Date: Fri, 27 Jan 2017 21:18:42 +0100 Subject: [Tutor] randomly generated error References: Message-ID: Freedom Peacemaker wrote: > Hi, > main idea was to : > - get random characters word > - randomly colour letters in my word > - from this coloured word print all yellow letters > > As it is random i need to be sure that at least one letter is yellow so i > put yellow color into final variable. Why? > This code works but randomly > generates error. And i have no idea how solve this problem. Please help me > > Traceback (most recent call last): > File "proj3", line 23, in > w = "".join((colorpass[i.end()]) for i in re.finditer(re.escape(Y), > colorpass)) > File "proj3", line 23, in > w = "".join((colorpass[i.end()]) for i in re.finditer(re.escape(Y), > colorpass)) > IndexError: string index out of range > > This is my code: > > from random import choice > from string import ascii_letters, digits > import re > > chars = ascii_letters + digits > > word = "".join([choice(chars) for i in range(10)]) > > R = '\033[31m' # red > G = '\033[32m' # green > B = '\033[34m' # blue > P = '\033[35m' # purple > Y = '\033[93m' # yellow > > colors = [R, G, B, P, Y] > > colorpass = "\033[93m" > for char in word: > colorpass += char + choice(colors) The character is followed by the color-code sequence. If the last color is yellow re.end() == len(colorpos) which is not a valid index into the string. > print(colorpass) > > w = "".join((colorpass[i.end()]) for i in re.finditer(re.escape(Y), > colorpass)) > print(w) > > I am using Python 3.5.2 on Ubuntu 16.04 To print a colored character you have to put the color sequence before it, so I'd do just that. Here's an example without regular expressions: word = "".join(choice(chars) for i in range(10)) colored_word = "".join(choice(colors) + c for c in word) yellow_chars = "".join(part[0] for part in colored_word.split(Y)[1:]) print(word) print(colored_word) print("\033[0m", end="") print(yellow_chars) As we know that at least one character follows the color it is OK to write part[0] above. If that's not the case it's easy to avoid the exception by using part[:1] as that works for the empty string, too: >>> "foo"[:1] 'f' >>> ""[:1] '' From jf_byrnes at comcast.net Fri Jan 27 16:47:27 2017 From: jf_byrnes at comcast.net (Jim) Date: Fri, 27 Jan 2017 15:47:27 -0600 Subject: [Tutor] Using venv Message-ID: It has been suggested to me that I should use a virtual environment and venv would be a good choice. I've read through PEP405 and this link [1]. Though some of it seems a little confusing to me, I'm sure I can get it up and running. This question seems a little dumb and maybe I am being a little dense, but then what? Your program/script is done how do you run it? Do you always have to activate your venv and run it from there? I like to run Tkinter programs from a launcher. Would that be possible and what would the command look like? Lately I have been writing some Libreoffice calc macros and evaluating pyspread for it's macro capability. Would modules installed in my venv be available to the spreadsheet programs? Thanks, Jim [1] https://realpython.com/blog/python/python-virtual-environments-a-primer/ From cs at zip.com.au Fri Jan 27 17:49:57 2017 From: cs at zip.com.au (Cameron Simpson) Date: Sat, 28 Jan 2017 09:49:57 +1100 Subject: [Tutor] Using venv In-Reply-To: References: Message-ID: <20170127224957.GA99321@cskk.homeip.net> On 27Jan2017 15:47, jim wrote: >It has been suggested to me that I should use a virtual environment >and venv would be a good choice. I've read through PEP405 and this >link [1]. >Though some of it seems a little confusing to me, I'm sure I can get >it up and running. This question seems a little dumb and maybe I am >being a little dense, but then what? > >Your program/script is done how do you run it? Do you always have to >activate your venv and run it from there? I like to run Tkinter >programs from a launcher. Would that be possible and what would the >command look like? Lately I have been writing some Libreoffice calc >macros and evaluating pyspread for it's macro capability. Would modules >installed in my venv be available to the spreadsheet programs? The mere act of using the python from inside the venv invokes a python that runs off the venv, so all you really need to do is to contrive to execute that python instead of the system python where you want it. If your scripts start with something like this: #!/usr/bin/env python3 then you can simply contrive that "python3" is found from the virtualenv. You might put a symlink in your personal $HOME/bin directory, or source the venv's "activate" file from your shell's profile (this making the venv searched ahead of the system paths), etc. Or your launcher might simply invoke: $HOME/path/to/your/venv/bin/python your-tk-inter-script.py Cheers, Cameron Simpson From jf_byrnes at comcast.net Sat Jan 28 13:13:39 2017 From: jf_byrnes at comcast.net (Jim) Date: Sat, 28 Jan 2017 12:13:39 -0600 Subject: [Tutor] Using venv In-Reply-To: <20170127224957.GA99321@cskk.homeip.net> References: <20170127224957.GA99321@cskk.homeip.net> Message-ID: On 01/27/2017 04:49 PM, Cameron Simpson wrote: > On 27Jan2017 15:47, jim wrote: >> It has been suggested to me that I should use a virtual environment >> and venv would be a good choice. I've read through PEP405 and this >> link [1]. >> Though some of it seems a little confusing to me, I'm sure I can get >> it up and running. This question seems a little dumb and maybe I am >> being a little dense, but then what? >> >> Your program/script is done how do you run it? Do you always have to >> activate your venv and run it from there? I like to run Tkinter >> programs from a launcher. Would that be possible and what would the >> command look like? Lately I have been writing some Libreoffice calc >> macros and evaluating pyspread for it's macro capability. Would >> modules installed in my venv be available to the spreadsheet programs? > > The mere act of using the python from inside the venv invokes a python > that runs off the venv, so all you really need to do is to contrive to > execute that python instead of the system python where you want it. > > If your scripts start with something like this: > > #!/usr/bin/env python3 > > then you can simply contrive that "python3" is found from the > virtualenv. You might put a symlink in your personal $HOME/bin > directory, or source the venv's "activate" file from your shell's > profile (this making the venv searched ahead of the system paths), etc. > > Or your launcher might simply invoke: > > $HOME/path/to/your/venv/bin/python your-tk-inter-script.py > > Cheers, > Cameron Simpson Thank you. Got it up and running and tested it with a previously written Tkinter script, which works fine. Regards, Jim From 01patrickliu at gmail.com Sun Jan 29 13:31:19 2017 From: 01patrickliu at gmail.com (=?UTF-8?B?5YqJ5qyK6Zme?=) Date: Mon, 30 Jan 2017 02:31:19 +0800 Subject: [Tutor] I hope you can build a platform for studying in Traditional Chinese.Please Message-ID: Hello: I am the student in junior high school.I would like to learn python, but there are few traditional Chinese resources on the website, especially the Python's documents are all in English I can not read it.( https://docs.python.org/2/) I hope you can build a platform for studying in Traditional Chinese.Please Thank yo very much. (Taiwan and China are different, the language is also,Taiwan is traditional Chinese,China is Simplified Chinese) patrick liu From robertvstepp at gmail.com Sun Jan 29 16:33:06 2017 From: robertvstepp at gmail.com (boB Stepp) Date: Sun, 29 Jan 2017 15:33:06 -0600 Subject: [Tutor] I hope you can build a platform for studying in Traditional Chinese.Please In-Reply-To: References: Message-ID: Hello! On Sun, Jan 29, 2017 at 12:31 PM, ??? <01patrickliu at gmail.com> wrote: > Hello: I am the student in junior high school.I would like to learn python, > but there are few traditional Chinese resources on the website, especially > the Python's documents are all in English I can not read it.( > https://docs.python.org/2/) > I hope you can build a platform for studying in Traditional Chinese.Please > Thank yo very much. > (Taiwan and China are different, the language is also,Taiwan is traditional > Chinese,China is Simplified Chinese) You may have already seen this, but in case you have not, there is: https://wiki.python.org/moin/ChineseLanguage There is mention of a couple of Taiwan forums which may be a source of assistance. Also a search for "python documentation in chinese" yields some hits, such as: http://docspy3zh.readthedocs.io/en/latest/ It is referring to Python 3.2.2 instead of the most current documentation, but perhaps it might be a useful start. Good luck! -- boB From adsquaired at gmail.com Mon Jan 30 09:45:24 2017 From: adsquaired at gmail.com (ad^2) Date: Mon, 30 Jan 2017 09:45:24 -0500 Subject: [Tutor] Lock File Usage Message-ID: Hello all, I have more more todo on a script I just finished. Prevent it from executing again if the process is running from the last job. Can't go to production without it. Ex. it runs in cron every hour to process batches of large size files. Potentially the processing could take longer than one hour depending on the file submissions. So, IF: no lock file, create a lock file, execute, delete lock file when finished successfully. ElSE: the script is running, exit. Then, cron will try again an hour later. I do not necessarily require a "lock file" just looking for a recommendation on a best practice with low complexity to make this work. I was hoping not to use the subprocess module to simulate what could be done in Bash. But, if that's the answer then so be it. Thanks, Ad^2 From alan.gauld at yahoo.co.uk Mon Jan 30 13:15:48 2017 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Mon, 30 Jan 2017 18:15:48 +0000 Subject: [Tutor] Lock File Usage In-Reply-To: References: Message-ID: On 30/01/17 14:45, ad^2 wrote: > So, IF: no lock file, create a lock file, execute, delete lock file when > finished successfully. ElSE: the script is running, exit. Then, cron will > try again an hour later. That's probably the most common way of doing what you want. But you need to make absolutely sure you delete the old file after you are done, even in the event of failures. try/finally at the top level would vbe a good start. But many also use a second cron job to check for files older than, say, T+50% (or whatever is the worst case) and then either delete them or flag a warning to the admins to check. This can run before the batch job that uses the files starts. You may accidentally miss one run but you should never miss more than that. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From ben+python at benfinney.id.au Mon Jan 30 19:33:10 2017 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 31 Jan 2017 11:33:10 +1100 Subject: [Tutor] Lock File Usage References: Message-ID: <85y3xsrruh.fsf@benfinney.id.au> "ad^2" writes: > So, IF: no lock file, create a lock file, execute, delete lock file > when finished successfully. ElSE: the script is running, exit. Then, > cron will try again an hour later. > > I do not necessarily require a "lock file" just looking for a > recommendation on a best practice with low complexity to make this > work. The third-party ?fasteners? library provides an API for locks that you will want to consider. Specifically, the interpprocess lock decorators seem to be what you want. -- \ ?? Nature ? is seen to do all things Herself and through | `\ herself of own accord, rid of all gods.? ?Titus Lucretius | _o__) Carus, c. 40 BCE | Ben Finney