unable to run the basic Embedded Python example
I cannot get the simple program https://docs.python.org/3/extending/embedding.html#very-high-level-embedding to work. My environment: * Windows 10 * Microsoft Visual Studio 2019 * Qt Creator 10.0.1 (only as an IDE) * Python not installed This is what I did: 1. I downloaded https://www.python.org/ftp/python/3.11.4/Python-3.11.4.tgz 2. I extracted Python-3.11.4.tgz into C:\temp\Python-3.11.4 3. I opened the "x64 Native Tools Command Prompt for VS 2019" which comes with Microsoft Visual Studio 2019 4. In "x64 Native Tools Command Prompt for VS 2019": ** ** Visual Studio 2019 Developer Command Prompt v16.11.26 ** Copyright (c) 2021 Microsoft Corporation ** [vcvarsall.bat] Environment initialized for: 'x64' C:\Program Files (x86)\Microsoft Visual Studio\2019\Community>cd C:\temp\Python-3.11.4\PCbuild C:\temp\Python-3.11.4\PCbuild>build.bat -d // <= option '-d' means "debug" Downloading nuget... [many lines omitted] Build succeeded. C:\temp\Python-3.11.4\PCbuild\pythoncore.vcxproj(578,5): warning MSB3073: The command ""C:\Program Files\Git\cmd\git.exe" name-rev --name-only HEAD > "C:\temp\Python-3.11.4\PCbuild\obj\311amd64_Debug\pythoncore\gitbranch.txt"" exited with code 128. C:\temp\Python-3.11.4\PCbuild\pythoncore.vcxproj(578,5): warning MSB4181: The "Exec" task returned false but did not log an error. C:\temp\Python-3.11.4\PCbuild\pythoncore.vcxproj(579,5): warning MSB3073: The command ""C:\Program Files\Git\cmd\git.exe" rev-parse --short HEAD > "C:\temp\Python-3.11.4\PCbuild\obj\311amd64_Debug\pythoncore\gitversion.txt"" exited with code 128. C:\temp\Python-3.11.4\PCbuild\pythoncore.vcxproj(579,5): warning MSB4181: The "Exec" task returned false but did not log an error. C:\temp\Python-3.11.4\PCbuild\pythoncore.vcxproj(580,5): warning MSB3073: The command ""C:\Program Files\Git\cmd\git.exe" describe --all --always --dirty > "C:\temp\Python-3.11.4\PCbuild\obj\311amd64_Debug\pythoncore\gittag.txt"" exited with code 128. C:\temp\Python-3.11.4\PCbuild\pythoncore.vcxproj(580,5): warning MSB4181: The "Exec" task returned false but did not log an error. 6 Warning(s) 0 Error(s) Time Elapsed 00:00:34.87 C:\temp\Python-3.11.4\PCbuild> 5. I copied the example https://docs.python.org/3/extending/embedding.html#very-high-level-embedding, unchanged, to 'C:\temp\embedded_python\main.c'. 6. I created Qt Creator project file 'C:\temp\embedded_python\ embedded_python.pro': TEMPLATE = app TARGET = embedded_python SOURCES += main.c PYTHON_DIR = C:/temp/Python-3.11.4 INCLUDEPATH += $${PYTHON_DIR}/Include INCLUDEPATH += $${PYTHON_DIR}/PC LIBS += $${PYTHON_DIR}/PCbuild/amd64/python311_d.lib 7. I built the project: 20:02:38: Running steps for project embedded_python... 20:02:38: Starting: "C:\Qt\6.1.3\msvc2019_64\bin\qmake.exe" C:\temp\embedded_python\embedded_python.pro -spec win32-msvc "CONFIG+=debug" "CONFIG-=qml_debug" "CONFIG-=qtquickcompiler" Info: creating stash file C:\temp\build-embedded_python-Desktop_Qt_6_1_3_MSVC2019_64bit-Debug\.qmake.stash 20:02:38: The process "C:\Qt\6.1.3\msvc2019_64\bin\qmake.exe" exited normally. 20:02:38: Starting: "C:\Qt\Tools\QtCreator\bin\jom\jom.exe" -f C:/temp/build-embedded_python-Desktop_Qt_6_1_3_MSVC2019_64bit-Debug/Makefile qmake_all jom 1.1.3 - empower your cores 20:02:38: The process "C:\Qt\Tools\QtCreator\bin\jom\jom.exe" exited normally. 20:02:38: Starting: "C:\Qt\Tools\QtCreator\bin\jom\jom.exe" C:\Qt\Tools\QtCreator\bin\jom\jom.exe -f Makefile.Debug cl -c -nologo -Zc:wchar_t -FS -Zc:strictStrings -Zi -MDd -utf-8 -W3 -w44456 -w44457 -w44458 /Fddebug\embedded_python.vc.pdb -DUNICODE -D_UNICODE -DWIN32 -D_ENABLE_EXTENDED_ALIGNED_STORAGE -DWIN64 -DQT_GUI_LIB -DQT_CORE_LIB -I..\embedded_python -I. -I..\Python-3.11.4\Include -I..\Python-3.11.4\PC -I..\..\Qt\6.1.3\msvc2019_64\include -I..\..\Qt\6.1.3\msvc2019_64\include\QtGui -I..\..\Qt\6.1.3\msvc2019_64\include\QtCore -Idebug -IC:/VulkanSDK/ 1.0.51.0/Include -I..\..\Qt\6.1.3\msvc2019_64\mkspecs\win32-msvc -Fodebug\ @C:\Users\dave\AppData\Local\Temp\main.obj.21168.0.jom main.c ..\embedded_python\main.c(12): warning C4996: 'Py_SetProgramName': deprecated in 3.11 link /NOLOGO /DYNAMICBASE /NXCOMPAT /DEBUG /SUBSYSTEM:WINDOWS "/MANIFESTDEPENDENCY:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' publicKeyToken='6595b64144ccf1df' language='*' processorArchitecture='*'" /MANIFEST:embed /OUT:debug\embedded_python.exe @C:\Users\dave\AppData\Local\Temp\embedded_python.exe.21168.484.jom 20:02:39:
Re: Creating logs with Python
Thank you Gerard! I am working on a project and needed that... :) 73, and thanks, Dave (NK7Z) https://www.nk7z.net ARRL Volunteer Examiner ARRL Technical Specialist, RFI ARRL Asst. Director, NW Division, Technical Resources On 2/22/23 07:03, Weatherby,Gerard wrote: https://docs.python.org/3/howto/logging.html From: Python-list on behalf of Bibi Date: Wednesday, February 22, 2023 at 9:44 AM To: python-list@python.org Subject: Creating logs with Python *** Attention: This is an external email. Use caution responding, opening attachments or clicking on links. *** Hello I want to store and make available as part of my project, logs, for access to data. Do you have any proposals? Kind regards -- https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!ntBEz59Ey9Aq3lepQ3xSKwSYtD_mYgoMO3OPqxMUrzbHNliAV76yHKsVIbEDpznq3hXNHvGxG3RNUPVxj5k$<https://urldefense.com/v3/__https:/mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!ntBEz59Ey9Aq3lepQ3xSKwSYtD_mYgoMO3OPqxMUrzbHNliAV76yHKsVIbEDpznq3hXNHvGxG3RNUPVxj5k$> -- https://mail.python.org/mailman/listinfo/python-list
Re: Function to Print a nicely formatted Dictionary or List?
Hi, I quite like the format that JSON gives - thanks a lot! Cheers Dave > On 9 Jun 2022, at 20:02, Stefan Ram wrote: > > Since nicety is in the eyes of the beholder, I would not > hesitate to write a custom function in this case. Python > has the standard modules "pprint" and "json". > > main.py > > import json > d ={ 1:2, 'alpha': 'beta' } > print( json.dumps( d, indent=4 )) > > output > > { >"1": 2, >"alpha": "beta" > } > -- https://mail.python.org/mailman/listinfo/python-list
Function to Print a nicely formatted Dictionary or List?
Hi, Before I write my own I wondering if anyone knows of a function that will print a nicely formatted dictionary? By nicely formatted I mean not all on one line! Cheers Dave -- https://mail.python.org/mailman/listinfo/python-list
Re: How to test characters of a string
Hi, I’ve found you also need to take care of multiple disk CD releases. These have a format of “1-01 Track Name” “2-02 Trackl Name" Meaning Disk 1 Track1, Disk 2, Track 2. Also A and B Sides (from Vinyl LPs) “A1-Track Name” “B2-Track Name” Side A, Track 1, etc. Cheers Dave > On 8 Jun 2022, at 19:36, Dennis Lee Bieber wrote: > > On Wed, 8 Jun 2022 01:53:26 + (UTC), Avi Gross > declaimed the following: > > >> >> So is it necessary to insist on an exact pattern of two digits followed by a >> space? >> >> >> That would fail on "44 Minutes", "40 Oz. Dream", "50 Mission Cap", "50 Ways >> to Say Goodbye", "99 Ways to Die" >> >> It looks to me like you need to compare TWICE just in case. If it matches in >> the original (perhaps with some normalization of case and whitespace, fine. >> If not will they match if one or both have something to remove as a prefix >> such as "02 ". And if you are comparing items where the same song is in two >> different numeric sequences on different disks, ... > > I suspect the OP really needs to extract the /track number/ from the > ID3 information, and (converting to a 2digit formatted string) see if the > file name begins with that track number... The format of the those > filenames appear to be those generated by some software when ripping CDs to > MP3s -- for example: > > -=-=- > c:\Music\Roger Miller\All Time Greatest Hits>dir > Volume in drive C is OS > Volume Serial Number is 4ACC-3CB4 > > Directory of c:\Music\Roger Miller\All Time Greatest Hits > > 04/11/2022 05:06 PM . > 04/11/2022 05:06 PM .. > 07/26/2018 11:20 AM 4,493,279 01 Dang Me.mp3 > 07/26/2018 11:20 AM 5,072,414 02 Chug-A-Lug.mp3 > 07/26/2018 11:20 AM 4,275,844 03 Do-Wacka-Do.mp3 > 07/26/2018 11:20 AM 4,284,208 04 In the Summertime.mp3 > 07/26/2018 11:20 AM 6,028,730 05 King of the Road.mp3 > 07/26/2018 11:20 AM 4,662,182 06 You Can't Roller Skate in a > Buffalo Herd.mp3 > 07/26/2018 11:20 AM 5,624,704 07 Engine, Engine #9.mp3 > 07/26/2018 11:20 AM 5,002,492 08 One Dyin' and a Buryin'.mp3 > 07/26/2018 11:21 AM 6,799,224 09 Last Word in Lonesome Is Me.mp3 > 07/26/2018 11:21 AM 5,637,230 10 Kansas City Star.mp3 > 07/26/2018 11:21 AM 4,656,910 11 England Swings.mp3 > 07/26/2018 11:21 AM 5,836,638 12 Husbands and Wives.mp3 > 07/26/2018 11:21 AM 5,470,216 13 I've Been a Long Time Leavin'.mp3 > 07/26/2018 11:21 AM 6,230,236 14 Walkin' in the Sunshine.mp3 > 07/26/2018 11:21 AM 6,416,060 15 Little Green Apples.mp3 > 07/26/2018 11:21 AM 9,794,442 16 Me and Bobby McGee.mp3 > 07/26/2018 11:22 AM 7,330,642 17 Where Have All the Average People > Gone.mp3 > 07/26/2018 11:22 AM 7,334,752 18 South.mp3 > 07/26/2018 11:22 AM 6,981,924 19 Tomorrow Night in Baltimore.mp3 > 07/26/2018 11:22 AM 9,353,872 20 River in the Rain.mp3 > 20 File(s)121,285,999 bytes > 2 Dir(s) 295,427,198,976 bytes free > > c:\Music\Roger Miller\All Time Greatest Hits> > -=-=- > > Untested (especially the ID3 "variable" -- substitute variables as > needed to match the original code): > >>>> id3Track = 2 >>>> track_number = "%2.2d " % id3Track >>>> track_number > '02 ' >>>> filename = "02 This is the life.mp3" >>>> if filename.startswith(track_number): > ... nametitle = filename[3:] > ... else: > ... nametitle = filename > ... >>>> if nametitle.endswith(".mp3"): > ... nametitle = nametitle[:-4] > ... >>>> nametitle > 'This is the life' > > Handling ASCII ' and " vs Unicode "smart" quotes is a different matter. > > One may still run the risk of having a filename without a track number > BUT having a number that just manages to match the track number. To account > for that I'd suggest using the sequence: > > * Strip extension (if filename.lower().endswith(".mp3"): ...) > * Handle any Unicode/ASCII quotes in both filename AND ID3 track title > * Compare filename and title. > * IF MATCHED -- done > * IF NOT MATCHED > * Format ID3 track number as shown above > * Compare filename to (formatted track number + track > title) > * IF MATCHED -- done > * IF NOT MATCHED > * Log full filename and ID3 track > title/track number to a > log for later examination. > > > > -- > Wulfraed Dennis Lee Bieber AF6VN > wlfr...@ix.netcom.comhttp://wlfraed.microdiversity.freeddns.org/ > -- > https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
Re: How to replace characters in a string?
Hi, This is a tool I’m using on my own files to save me time. Basically or most of the tracks were imported with different version iTunes over the years. There are two problems: 1. File System characters are replaced (you can’t have ‘/‘ or ‘:’ in a file name). 2. Smart Quotes were added at some point, these need to replaced. 3. Other character based of name being of a non-english origin. If find others I’ll add them. I’m using MusicBrainz to do a fuzzy match and get the correct name. it’s not perfect, but works for 99% of files which is good enough for me! Cheers Dave > On 8 Jun 2022, at 18:23, Avi Gross via Python-list > wrote: > > Dave, > > Your goal is to compare titles and there can be endless replacements needed > if you allow the text to contain anything but ASCII. > > Have you considered stripping out things instead? I mean remove lots of stuff > that is not ASCII in the first place and perhaps also remove lots of extra > punctuation likesingle quotes or question marks or redundant white space and > compare the sort of skeletons of the two? > > And even if that fails, could you have a measure of how different they are > and tolerate if they were say off by one letter albeit "My desert" matching > "My Dessert" might not be a valid match with one being a song about an arid > environment and the other about food you don't need! > > Your seemingly simple need can expand into a fairly complex project. There > may be many ideas on how to deal with it but not anything perfect enough to > catch all cases as even a trained human may have to make decisions at times > and not match what other humans do. We have examples like the TV show > "NUMB3RS" that used a perfectly valid digit 3 to stand for an "E" but yet is > often written when I look it up as NUMBERS. You have obvious cases where > titles of songs may contain composite symbols like "œ" which will not compare > to one where it is written out as "oe" so the idea of comparing is quite > complex and the best you might do is heuristic. > > UNICODE has many symbols that are almost the same or even look the same or > maybe in one font versus another. There are libraries of functions that allow > some kinds of comparisons or conversions that you could look into but the > gain for you may not be worth it. Nothing stops a person from naming a song > any way they want and I speak many languages and often see a song re-titled > in the local language and using the local alphabet mixed often with another. > > Your original question is perhaps now many questions, depending on what you > choose. You started by wanting to know how to compare and it is moving on to > how to delete parts or make substitutions or use regular expressions and it > can get worse. You can, for example, take a string and identify the words > within it and create a regular expression that inserts sequences between the > words that match any zero or one or more non-word characters such as spaces, > tabs, punctuation or non-ASCII, so that song titles with the same words in a > sequence match no matter what is between them. The possibilities are endless > but consider some of the techniques that are used by some programs that parse > text and suggest alternate spellings or even programs like Google Translate > that can take a sentence and then suggest you may mean a slightly altered > sentence with one word changed to fit better. > > You need to decide what you want to deal with and what will be mis-classified > by your program. Some of us have suggested folding the case of the words but > that means asong about a dark skinned person in Poland called "Black Polish" > would match a song about keeping your shoes dark with "black polish" so I > keep repeating it is very hard or frankly impossible, to catch every case I > can imagine and the many I can't! > > But the emphasis here is not your overall problem. It is about whether and > how the computer language called python, and perhaps some add-on modules, can > be used to solve each smaller need such as recognizing a pattern or replacing > text. It can do quite a bit but only when the specification of the problem is > exact. > > > > > -Original Message- > From: Dave > To: python-list@python.org > Sent: Wed, Jun 8, 2022 5:09 am > Subject: Re: How to replace characters in a string? > > Hi, > > Thanks for this! > > So, is there a copy function/method that returns a MutableString like in > objective-C? I’ve solved this problems before in a number of languages like > Objective-C and AppleScript. > > Basically there is a set of common char
Re: How to replace characters in a string?
> On 8 Jun 2022, at 11:25, Dave wrote: > >myNewString = theString.replace("\u2014", “]” #just an example Opps! Make that myNewString = myNewString.replace("\u2014", “]” #just an example -- https://mail.python.org/mailman/listinfo/python-list
Re: How to replace characters in a string?
Hi, I misunderstood how it worked, basically I’ve added this function: def filterCommonCharacters(theString): myNewString = theString.replace("\u2019", "'") return myNewString Which returns a new string replacing the common characters. This can easily be extended to include other characters as and when they come up by adding a line as so: myNewString = theString.replace("\u2014", “]” #just an example Which is what I was trying to achieve. All the Best Dave > On 8 Jun 2022, at 11:17, Chris Angelico wrote: > > On Wed, 8 Jun 2022 at 19:13, Dave wrote: >> >> Hi, >> >> Thanks for this! >> >> So, is there a copy function/method that returns a MutableString like in >> objective-C? I’ve solved this problems before in a number of languages like >> Objective-C and AppleScript. >> >> Basically there is a set of common characters that need “normalizing” and I >> have a method that replaces them in a string, so: >> >> myString = [myString normalizeCharacters]; >> >> Would return a new string with all the “common” replacements applied. >> >> Since the following gives an error : >> >> myString = 'Hello' >> myNewstring = myString.replace(myString,'e','a’) >> >> TypeError: 'str' object cannot be interpreted as an integer >> >> I can’t see of a way to do this in Python? >> > > Not sure why you're passing the string as an argument as well as using > it as the object you're calling a method on. All you should need to do > is: > > myString.replace('e', 'a') > > ChrisA > -- > https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
Re: How to replace characters in a string?
Hi, Thanks for this! So, is there a copy function/method that returns a MutableString like in objective-C? I’ve solved this problems before in a number of languages like Objective-C and AppleScript. Basically there is a set of common characters that need “normalizing” and I have a method that replaces them in a string, so: myString = [myString normalizeCharacters]; Would return a new string with all the “common” replacements applied. Since the following gives an error : myString = 'Hello' myNewstring = myString.replace(myString,'e','a’) TypeError: 'str' object cannot be interpreted as an integer I can’t see of a way to do this in Python? All the Best Dave > On 8 Jun 2022, at 10:14, Chris Angelico wrote: > > On Wed, 8 Jun 2022 at 18:12, Dave wrote: > >> I tried the but it doesn’t seem to work? >> myCompareFile1 = ascii(myTitleName) >> myCompareFile1.replace("\u2019", "'") > > Strings in Python are immutable. When you call ascii(), you get back a > new string, but it's one that has actual backslashes and such in it. > (You probably don't need this step, other than for debugging; check > the string by printing out the ASCII version of it, but stick to the > original for actual processing.) The same is true of the replace() > method; it doesn't change the string, it returns a new string. > >>>> word = "spam" >>>> print(word.replace("sp", "h")) > ham >>>> print(word) > spam > > ChrisA > -- > https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
Re: How to replace characters in a string?
PS I’ve also tried: myCompareFile1 = myTitleName myCompareFile1.replace("\u2019", "'") myCompareFile2 = myCompareFileName myCompareFile2.replace("\u2019", "'") Which also doesn’t work, the replace itself work but it still fails the compare? > On 8 Jun 2022, at 10:08, Dave wrote: > > Hi All, > > I decided to start a new thread as this really is a new subject. > > I've got two that appear to be identical, but fail to compare. After getting > the ascii encoding I see that they are indeed different, my question is how > can I replace the \u2019m with a regular single quote mark (or apostrophe)? > > myCompareFile1 = ascii(myTitleName) > myCompareFile2 = ascii(myCompareFileName) > myCompareFile1: 'I\u2019m Mandy Fly Me' > myCompareFile2: "I'm Mandy Fly Me" > > I tried the but it doesn’t seem to work? > myCompareFile1 = ascii(myTitleName) > myCompareFile1.replace("\u2019", "'") > myCompareFile2 = ascii(myCompareFileName) > myCompareFile2.replace("\u2019", "'") > if myCompareFile1 != myCompareFile2: >print('myCompareFile1:',myCompareFile1) >print('myCompareFile2:',myCompareFile2) >myLength1 = len(myCompareFileName) >myLength2 = len(myTitleName) >print('File Name Mismatch - Artist: [' + myArtistName + '] Album: ['+ > myAlbumName + '] Track: [' + myTitleName + '] File: [' + myCompareFileName > + ']') >if (myLength1 == myLength2): >print('lengths match: ',myLength1) >else: > print('lengths mismatch: ',myLength1,' ',myLength2) >print(' ') > Console: > > myCompareFile1: 'I\u2019m Mandy Fly Me' > myCompareFile2: "I'm Mandy Fly Me" > > So it looks like the replace isn’t doing anything? > > I’m an experienced developer but learning Python. > > All the Best > Dave > > > > > > -- > https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
How to replace characters in a string?
Hi All, I decided to start a new thread as this really is a new subject. I've got two that appear to be identical, but fail to compare. After getting the ascii encoding I see that they are indeed different, my question is how can I replace the \u2019m with a regular single quote mark (or apostrophe)? myCompareFile1 = ascii(myTitleName) myCompareFile2 = ascii(myCompareFileName) myCompareFile1: 'I\u2019m Mandy Fly Me' myCompareFile2: "I'm Mandy Fly Me" I tried the but it doesn’t seem to work? myCompareFile1 = ascii(myTitleName) myCompareFile1.replace("\u2019", "'") myCompareFile2 = ascii(myCompareFileName) myCompareFile2.replace("\u2019", "'") if myCompareFile1 != myCompareFile2: print('myCompareFile1:',myCompareFile1) print('myCompareFile2:',myCompareFile2) myLength1 = len(myCompareFileName) myLength2 = len(myTitleName) print('File Name Mismatch - Artist: [' + myArtistName + '] Album: ['+ myAlbumName + '] Track: [' + myTitleName + '] File: [' + myCompareFileName + ']') if (myLength1 == myLength2): print('lengths match: ',myLength1) else: print('lengths mismatch: ',myLength1,' ',myLength2) print(' ') Console: myCompareFile1: 'I\u2019m Mandy Fly Me' myCompareFile2: "I'm Mandy Fly Me" So it looks like the replace isn’t doing anything? I’m an experienced developer but learning Python. All the Best Dave -- https://mail.python.org/mailman/listinfo/python-list
Re: How to test characters of a string
I hate regEx and avoid it whenever possible, I’ve never found something that was impossible to do without it. > On 8 Jun 2022, at 00:49, dn wrote: > > On 08/06/2022 10.18, De ongekruisigde wrote: >> On 2022-06-08, Christian Gollwitzer wrote: >>> Am 07.06.22 um 21:56 schrieb Dave: >>>> It depends on the language I’m using, in Objective C, I’d use isNumeric, >>>> just wanted to know what the equivalent is in Python. >>>> >>> >>> Your problem is also a typical case for regular expressions. You can >>> create an expression for "starts with any number of digits plus optional >>> whitespace" and then replace this with nothing: >> >> Regular expressions are overkill for this and much slower than the >> simple isdigit based solution. > > ... > >> Regular expressions are indeeed extremely powerful and useful but I tend >> to avoid them when there's a (faster) normal solution. > > Yes, simple solutions are (likely) easier to read. > > RegEx-s are more powerful (and well worth learning for this reason), but > are only 'readable' to those who use them frequently. > > Has either of you performed a timeit comparison? > -- > Regards, > =dn > -- > https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
Re: How to test characters of a string
rotfl! Nice one! > On 8 Jun 2022, at 00:24, 2qdxy4rzwzuui...@potatochowder.com wrote: > > On 2022-06-07 at 23:07:42 +0100, > Regarding "Re: How to test characters of a string," > MRAB wrote: > >> On 2022-06-07 21:23, Dave wrote: >>> Thanks a lot for this! isDigit was the method I was looking for and >>> couldn’t find. >>> >>> I have another problem related to this, the following code uses the code >>> you just sent. I am getting a files ID3 tags using eyed3, this part seems >>> to work and I get expected values in this case myTitleName (Track name) is >>> set to “Deadlock Holiday” and myCompareFileName is set to “01 Deadlock >>> Holiday” (File Name with the Track number prepended). The is digit test >>> works and myCompareFileName is set to “Deadlock Holiday”, so they should >>> match, right? >>> >> OT, but are you sure about that name? Isn't it "Dreadlock Holiday" (by >> 10cc)? > > Edsger Dijkstra originally wrote Deadlock Holiday for his band, The > Semaphores. 10cc lost the race condition and had to change the lyrics. > > Sorry. > -- > https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
Re: How to test characters of a string
Yes, it was probably just a typeo on my part. I’ve now fixed the majority of cases but still got two strings that look identical but fail to match, this time (again by 10cc), “I’m Mandy Fly Me”. I’m putting money on it being a utf8 problem but I’m stuck on how to handle it. It’s probably the single quote in I’m, although it has worked with other songs. Any ideas? All the Best Cheers Dave Here is the whole function/method or whatever it’s called in Python: # # checkMusicFiles # def checkMusicFiles(theBaseMusicLibraryFolder): myArtistDict = [] # # Loop thru Artists Folder # myArtistsFoldlerList = getFolderList(theBaseMusicLibraryFolder) myArtistCount = 0 for myArtistFolder in myArtistsFoldlerList: print('Artist: ' + myArtistFolder) # # Loop thru Albums Folder # myAlbumList = getFolderList(theBaseMusicLibraryFolder + myArtistFolder) for myAlbum in myAlbumList: print('Album: ' + myAlbum) # # Loop thru Tracks (Files) Folder # myAlbumPath = theBaseMusicLibraryFolder + myArtistFolder + '/' + myAlbum + '/' myFilesList = getFileList(myAlbumPath) for myFile in myFilesList: myFilePath = myAlbumPath + myFile myID3 = eyed3.load(myFilePath) if myID3 is None: continue myArtistName = myID3.tag.artist if myArtistName is None: continue myAlbumName = myID3.tag.album if myAlbumName is None: continue myTitleName = myID3.tag.title if myTitleName is None: continue myCompareFileName = myFile[0:-4] if myCompareFileName[0].isdigit() and myCompareFileName[1].isdigit(): myCompareFileName = myFile[3:-4] if myCompareFileName != myTitleName: myLength1 = len(myCompareFileName) myLength2 = len(myTitleName) print('File Name Mismatch - Artist: [' + myArtistName + '] Album: ['+ myAlbumName + '] Track: [' + myTitleName + '] File: [' + myCompareFileName + ']') if (myLength1 == myLength2): print('lengths match: ',myLength1) else: print('lengths mismatch: ',myLength1,' ',myLength2) print(' ') return myArtistsFoldlerList > On 8 Jun 2022, at 00:07, MRAB wrote: > > On 2022-06-07 21:23, Dave wrote: >> Thanks a lot for this! isDigit was the method I was looking for and couldn’t >> find. >> I have another problem related to this, the following code uses the code you >> just sent. I am getting a files ID3 tags using eyed3, this part seems to >> work and I get expected values in this case myTitleName (Track name) is set >> to “Deadlock Holiday” and myCompareFileName is set to “01 Deadlock Holiday” >> (File Name with the Track number prepended). The is digit test works and >> myCompareFileName is set to “Deadlock Holiday”, so they should match, right? > OT, but are you sure about that name? Isn't it "Dreadlock Holiday" (by 10cc)? > > [snip] > -- > https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
Re: How to test characters of a string
A, ok will do, was just trying to be a brief as possible, will post more fully in future. > On 7 Jun 2022, at 23:29, Chris Angelico wrote: > > On Wed, 8 Jun 2022 at 07:24, Barry wrote: >> >> >> >>> On 7 Jun 2022, at 22:04, Dave wrote: >>> >>> It depends on the language I’m using, in Objective C, I’d use isNumeric, >>> just wanted to know what the equivalent is in Python. >>> >>> If you know the answer why don’t you just tell me and if you don’t, don’t >>> post! >> >> People ask home work questions here and we try to teach a student with hints >> not finished answers. >> Your post was confused with a home work question. >> > > In the future, to make it look less like a homework question, show > your current code, which would provide context. Last I checked, > homework questions don't usually involve ID3 tags in MP3 files :) > > ChrisA > -- > https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
Re: How to test characters of a string
Hi, Found it! The files name had .mp3 at the end, the problem was being masked by null objects (or whatever) being returned by eyed3. Checked for null objects and then stripped off the .mp3 and its mostly working now. I’ve got a few other eyed3 errors to do with null objects but I can sort those out tomorrow. Thanks for your help - All the Best Dave > On 7 Jun 2022, at 23:01, Dave wrote: > > Hi, > > No, I’ve checked leading/trailing whitespace, it seems to be related to the > variables that are returned from eyed3 in this case, for instance, I added a > check for None: > myTitleName = myID3.tag.title > if myTitleName is None: >continue > Seems like it can return a null object (or none?). > > >> On 7 Jun 2022, at 22:35, De ongekruisigde >> > <mailto:ongekruisi...@news.eternal-september.org>> wrote: >> >> On 2022-06-07, Dave > <mailto:d...@looktowindward.com> <mailto:d...@looktowindward.com >> <mailto:d...@looktowindward.com>>> wrote: >>> Thanks a lot for this! isDigit was the method I was looking for and >>> couldn’t find. >>> >>> I have another problem related to this, the following code uses the code >>> you just sent. I am getting a files ID3 tags using eyed3, this part seems >>> to work and I get expected values in this case myTitleName (Track name) is >>> set to “Deadlock Holiday” and myCompareFileName is set to “01 Deadlock >>> Holiday” (File Name with the Track number prepended). The is digit test >>> works and myCompareFileName is set to “Deadlock Holiday”, so they should >>> match, right? >>> >>> However the if myCompareFileName != myTitleName always gives a mismatch! >>> What could cause two string that look the fail to not match properly? >> >> Possibly leading or trailing spaces, or upper/lower case differences? >> >> >>> myCompareFileName = myFile >>> if myCompareFileName[0].isdigit() and myCompareFileName[1].isdigit(): >>> myCompareFileName = myCompareFileName[3:] >>> >>> if myCompareFileName != myTitleName: >>> print('File Name Mismatch - Artist: ',myArtistName,' Album: >>> ',myAlbumName,' Track:',myTitleName,' File: ',myFile) >>> Thanks a lot >>> Dave >>> >>>> On 7 Jun 2022, at 21:58, De ongekruisigde >>>> wrote: >>>> >>>> On 2022-06-07, Dave wrote: >>>>> Hi, >>>>> >>>>> I’m new to Python and have a simple problem that I can’t seem to find the >>>>> answer. >>>>> >>>>> I want to test the first two characters of a string to check if the are >>>>> numeric (00 to 99) and if so remove the fist three chars from the string. >>>>> >>>>> Example: if “05 Trinket” I want “Trinket”, but “Trinket” I still want >>>>> “Trinket”. I can’t for the life of work out how to do it in Python? >>>> >>>> >>>> s[3:] if s[0:2].isdigit() else s >>>> >>>> >>>>> All the Best >>>>> Dave >>>>> >>>> >>>> -- >>>> You're rewriting parts of Quake in *Python*? >>>> MUAHAHAHA >>>> -- >>>> https://mail.python.org/mailman/listinfo/python-list >>> >> >> >> -- >> You're rewriting parts of Quake in *Python*? >> MUAHAHAHA >> -- >> https://mail.python.org/mailman/listinfo/python-list >> <https://mail.python.org/mailman/listinfo/python-list> >> <https://mail.python.org/mailman/listinfo/python-list >> <https://mail.python.org/mailman/listinfo/python-list>> > -- > https://mail.python.org/mailman/listinfo/python-list > <https://mail.python.org/mailman/listinfo/python-list> -- https://mail.python.org/mailman/listinfo/python-list
Re: How to test characters of a string
Hi, No, I’ve checked leading/trailing whitespace, it seems to be related to the variables that are returned from eyed3 in this case, for instance, I added a check for None: myTitleName = myID3.tag.title if myTitleName is None: continue Seems like it can return a null object (or none?). > On 7 Jun 2022, at 22:35, De ongekruisigde > wrote: > > On 2022-06-07, Dave <mailto:d...@looktowindward.com>> wrote: >> Thanks a lot for this! isDigit was the method I was looking for and couldn’t >> find. >> >> I have another problem related to this, the following code uses the code you >> just sent. I am getting a files ID3 tags using eyed3, this part seems to >> work and I get expected values in this case myTitleName (Track name) is set >> to “Deadlock Holiday” and myCompareFileName is set to “01 Deadlock Holiday” >> (File Name with the Track number prepended). The is digit test works and >> myCompareFileName is set to “Deadlock Holiday”, so they should match, >> right? >> >> However the if myCompareFileName != myTitleName always gives a mismatch! >> What could cause two string that look the fail to not match properly? > > Possibly leading or trailing spaces, or upper/lower case differences? > > >> myCompareFileName = myFile >> if myCompareFileName[0].isdigit() and myCompareFileName[1].isdigit(): >>myCompareFileName = myCompareFileName[3:] >> >> if myCompareFileName != myTitleName: >> print('File Name Mismatch - Artist: ',myArtistName,' Album: >> ',myAlbumName,' Track:',myTitleName,' File: ',myFile) >> Thanks a lot >> Dave >> >>> On 7 Jun 2022, at 21:58, De ongekruisigde >>> wrote: >>> >>> On 2022-06-07, Dave wrote: >>>> Hi, >>>> >>>> I’m new to Python and have a simple problem that I can’t seem to find the >>>> answer. >>>> >>>> I want to test the first two characters of a string to check if the are >>>> numeric (00 to 99) and if so remove the fist three chars from the string. >>>> >>>> Example: if “05 Trinket” I want “Trinket”, but “Trinket” I still want >>>> “Trinket”. I can’t for the life of work out how to do it in Python? >>> >>> >>> s[3:] if s[0:2].isdigit() else s >>> >>> >>>> All the Best >>>> Dave >>>> >>> >>> -- >>> You're rewriting parts of Quake in *Python*? >>> MUAHAHAHA >>> -- >>> https://mail.python.org/mailman/listinfo/python-list >> > > > -- > You're rewriting parts of Quake in *Python*? > MUAHAHAHA > -- > https://mail.python.org/mailman/listinfo/python-list > <https://mail.python.org/mailman/listinfo/python-list> -- https://mail.python.org/mailman/listinfo/python-list
Re: How to test characters of a string
It depends on the language I’m using, in Objective C, I’d use isNumeric, just wanted to know what the equivalent is in Python. If you know the answer why don’t you just tell me and if you don’t, don’t post! > On 7 Jun 2022, at 22:08, 2qdxy4rzwzuui...@potatochowder.com wrote: > > On 2022-06-07 at 21:35:43 +0200, > Dave wrote: > >> I’m new to Python and have a simple problem that I can’t seem to find >> the answer. > >> I want to test the first two characters of a string to check if the >> are numeric (00 to 99) and if so remove the fist three chars from the >> string. > >> Example: if “05 Trinket” I want “Trinket”, but “Trinket” I still want >> “Trinket”. I can’t for the life of work out how to do it in Python? > > How would you do it without Python? > > Given that if the string is called x, then x[y] is the y'th character > (where what you would call "the first character," Python calls "the > zeroth character"), describe the steps you would take *as a person* (or > in some other programming language, if you know one) to carry out this > task. > > Translating that algorithm to Python is the next step. Perhaps > https://docs.python.org/3/library/string.html can help. > -- > https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
Re: How to test characters of a string
Thanks a lot for this! isDigit was the method I was looking for and couldn’t find. I have another problem related to this, the following code uses the code you just sent. I am getting a files ID3 tags using eyed3, this part seems to work and I get expected values in this case myTitleName (Track name) is set to “Deadlock Holiday” and myCompareFileName is set to “01 Deadlock Holiday” (File Name with the Track number prepended). The is digit test works and myCompareFileName is set to “Deadlock Holiday”, so they should match, right? However the if myCompareFileName != myTitleName always gives a mismatch! What could cause two string that look the fail to not match properly? myCompareFileName = myFile if myCompareFileName[0].isdigit() and myCompareFileName[1].isdigit(): myCompareFileName = myCompareFileName[3:] if myCompareFileName != myTitleName: print('File Name Mismatch - Artist: ',myArtistName,' Album: ',myAlbumName,' Track:',myTitleName,' File: ',myFile) Thanks a lot Dave > On 7 Jun 2022, at 21:58, De ongekruisigde > wrote: > > On 2022-06-07, Dave wrote: >> Hi, >> >> I’m new to Python and have a simple problem that I can’t seem to find the >> answer. >> >> I want to test the first two characters of a string to check if the are >> numeric (00 to 99) and if so remove the fist three chars from the string. >> >> Example: if “05 Trinket” I want “Trinket”, but “Trinket” I still want >> “Trinket”. I can’t for the life of work out how to do it in Python? > > > s[3:] if s[0:2].isdigit() else s > > >> All the Best >> Dave >> > > -- > You're rewriting parts of Quake in *Python*? > MUAHAHAHA > -- > https://mail.python.org/mailman/listinfo/python-list -- https://mail.python.org/mailman/listinfo/python-list
How to test characters of a string
Hi, I’m new to Python and have a simple problem that I can’t seem to find the answer. I want to test the first two characters of a string to check if the are numeric (00 to 99) and if so remove the fist three chars from the string. Example: if “05 Trinket” I want “Trinket”, but “Trinket” I still want “Trinket”. I can’t for the life of work out how to do it in Python? All the Best Dave -- https://mail.python.org/mailman/listinfo/python-list
Re: Help with Python/Eyed3 MusicCDIdFrame method
Thanks! That fixed it! > On 6 Jun 2022, at 18:46, MRAB wrote: > > On 2022-06-06 11:37, Dave wrote: >> Hi, >> I’m trying to get the ID3 tags of an mp3 file. I trying to use the >> MusicCDIdFrame >> method but I can’t seem to get it right. Here is a code snippet: >> import eyed3 >> import eyed3.id3 >> import eyed3.id3.frames >> import eyed3.id3.apple >> import eyed3.mp3 >> myID3 = eyed3.load("/Users/Test/Life in the fast lane.mp3") >> myTitle = myID3.tag.title >> myArtist = myID3.tag.artist >> myAlbum = myID3.tag.album >> myAlbumArtist = myID3.tag.album_artist >> myComposer = myID3.tag.composer >> myPublisher = myID3.tag.publisher >> myGenre = myID3.tag.genre.name >> myCDID = myID3.id3.frames.MusicCDIdFrame(id=b'MCDI', toc=b'') >> When I run this, I get the following error: >> File "/Documents/Python/Test1/main.py", line 94, in >> myCDID = myID3.id3.frames.MusicCDIdFrame(id=b'MCDI', toc=b'') >> AttributeError: 'Mp3AudioFile' object has no attribute 'id3' >> Any help or suggestion greatly appreciated. > That line should be: > > myCDID = eyed3.id3.frames.MusicCDIdFrame(id=b'MCDI', toc=b'') > > Also remember that some attributes might be None, e.g. 'myID3.tag.genre' > might be None. > > Another point: it's probably not worth importing the submodules of 'eyed3'; > you're not gaining anything from it. > -- > https://mail.python.org/mailman/listinfo/python-list > <https://mail.python.org/mailman/listinfo/python-list> -- https://mail.python.org/mailman/listinfo/python-list
Help with Python/Eyed3 MusicCDIdFrame method
Hi, I’m trying to get the ID3 tags of an mp3 file. I trying to use the MusicCDIdFrame method but I can’t seem to get it right. Here is a code snippet: import eyed3 import eyed3.id3 import eyed3.id3.frames import eyed3.id3.apple import eyed3.mp3 myID3 = eyed3.load("/Users/Test/Life in the fast lane.mp3") myTitle = myID3.tag.title myArtist = myID3.tag.artist myAlbum = myID3.tag.album myAlbumArtist = myID3.tag.album_artist myComposer = myID3.tag.composer myPublisher = myID3.tag.publisher myGenre = myID3.tag.genre.name myCDID = myID3.id3.frames.MusicCDIdFrame(id=b'MCDI', toc=b'') When I run this, I get the following error: File "/Documents/Python/Test1/main.py", line 94, in myCDID = myID3.id3.frames.MusicCDIdFrame(id=b'MCDI', toc=b'') AttributeError: 'Mp3AudioFile' object has no attribute 'id3' Any help or suggestion greatly appreciated. All the Best Dave -- https://mail.python.org/mailman/listinfo/python-list
python 3.9.12 and python 3.10
Date: Tue, 3 May 2022 19:59:08 +0100 Subject: python 3.9.12 and python 3.10 I installed 3.9 and am able to enter simple code which runs. If I type an error I can highlight it but cannot copy or delete it. I looked for help & found 3.10 and installed it but when I selected the python icon 3.9 appeared with my old errors. I uninstalled 3.10 as 3.9 did not appear in control panel. Dell Inspiron 3793 Win 10 Thanks Dave Francis -- https://mail.python.org/mailman/listinfo/python-list
Subprocess Connection Error
Hello, I bought a book called Coding for Beginners to learn how to code using Python. The first few exercises went fine. When I got to the page called Recognizing types and did the exercise and saved it and tried to run the module it comes up with a Subprocess Connection Error. It says, "IDLE's subprocess didn't make connection. See the Start up failure section of the IDLE doc, online at https://docs.python.org/3/library/idle.html#startup-failure."; I went there and it said to try uninstalling python and then reinstalling it. I did this and it did the same thing again. It also said something about it is because of the antivirus software. I tried installing python on a different computer and it happened at the exact same place in the exercises in the book. I am far from being a computer whiz, just thought it would be fun to learn some simple coding. Any help would be appreciated. One more thing, the book says to save it as "types.py". Thank you, Dave Dungan -- https://mail.python.org/mailman/listinfo/python-list
Visualize dataframes in 2 lines
import sho sho.w(dataframe) Install : pip install sho Medium Article: https://medium.com/@davewd/sho-w-dataframe-my-first-package-b7242088b78f Github: https://github.com/davewd/sho -- https://mail.python.org/mailman/listinfo/python-list
Re: low-level csv
The few times I looked at CSV module it never looked useful to me. I seem to use shlex for everything. For example: def csv_split (s): lex = shlex.shlex(s, posix=True) lex.whitespace_split = True lex.whitespace = ',' return list(lex) will split on commas while honoring quoted values (and stripping out the quotes) Dave On 2019/11/17 08:18, Antoon Pardon wrote: This is python 2.6->2.7 and 3.5->3.7 I need to convert a string that is a csv line to a list and vice versa. I thought to find functions doing this in the csv module but that doesn't seem to be the case. I can of course write special classes that would allow for this using a csv.reader and csv.writer but that would be some convoluted code. Anyone some suggestions? -- https://mail.python.org/mailman/listinfo/python-list
Re: How to delay until a next increment of time occurs ?
Rudy, OK I'm old enough cancer to know what X10 is. :-) I wouldn't think this is too difficult to do as you're only sending. For this application IMO there is too much going on inside python that can interrupt the cycle of modulation. (Intra and Extra python; garbage collection, other processes, etc) I would drop back to a simple program in C that you execute from python to do the actual sending putting your 'message' on the command line to that program (or use a tmpfile). I think your solution will be to execute this program from python. Let me stress, my advise is doing this *reliably*. In that regard you might need look at locking your C process to 1 CPU and giving it highest priority. (man nice) Once you have this working reliably, you could then look to convert it to a python c-module to more tightly integrate it. Dave On 2019/11/14 15:00, R.Wieser wrote: Dave, Can you expand on what you are trying to accomplish with this? There is a small 433 MHz rf transmitter connected to the pin, and when I send the right pattern a wireless wall-wart will respond and switch a lamp on or off. Its just ment as an example of a real-world application of Python, nothing serious. Ofcourse, by doing so I'm learning about how to use python (and the Pi) myself too. :-) It seems a small C program or library you interface python too is a better solution. :-) I already wrote that program in C{something} (I'm not sure what my Pi offers by default) a while ago, but "ported" it to python. For the above mentioned "example" reason. ... Which is also why I didn't even try to just shell to that program, or try to interface with a C{something} library. Though doing such interfacing is in the pipeline (I've already found-and-stored some documentation about it). Regards, Rudy Wieser -- https://mail.python.org/mailman/listinfo/python-list
Re: How to delay until a next increment of time occurs ?
Can you expand on what you are trying to accomplish with this? It seems a small C program or library you interface python too is a better solution. With that said, as others mentioned you might need a real time OS or micro controller if this needs to be dead on timing. Dave On 2019/11/13 09:02, R.Wieser wrote: Hello all, I'm writing some code to toggle a pin on a Raspberry Pi, and would like to have that happen at (multiples of) 300 uSec increments. I tried time.sleep(), but that one disregards the time after the last one ends and the new one is started. In other words, all the time spend in code (or being interrupted by another thread!) between the end of the previous and the start of the current sleep throws the whole repetitive timing off. So, I'm looking for a method that will allow me to wait for a "last time plus increment". Is there one with the properties of sleep() (not just burning processor cycles way, blocking all threads), but referencing a previous time. Regards, Rudy Wieser -- https://mail.python.org/mailman/listinfo/python-list
ANNOUNCE: Thesaurus and ThesaurusCfg - recursive mapping and cfg file data types
This announcement is for a pre-release that I would like people to comment on structure, naming, etc. (Code review maybe not yet. :-) Before you say "It's all been done before." I suggest you take a closer look and I think you may conclude that what I've revised over 7 years is now interesting. --- Thesaurus is a mapping data type with key recursion and attribute aliasing. It is a subclass of dict() and compatible as a dictionary replacement baring where key path recursion may take place. ThesaurusExtended is a subclass of Thesaurus providing additional usability methods. ThesaurusCfg is a subclass of ThesaurusExtended providing a configuration file parser and per key data coercion methods. The Thesaurus family works with Python 2.6+ to 3.8+. A simple example of ThesaurusCfg -- cfgs = ''' prog.version(static_int)= 123 opt.verbose (str_to_bool) = yes hi = Hello ''' from thesauruscfg import thescfg cfg = thescfg() >>> cfg.parse(cfgs) {'prog': {'version': 123}, 'opt': {'verbose': True}, 'hi': 'Hello'} >>> cfg.opt.verbose True import json >>> print(json.dumps(cfg, indent=4, separators=(',', ': '))) { "prog": { "version": 123 }, "opt": { "verbose": true }, "hi": "Hello" } browse: https://git.cinege.com/thesaurus/ or git clone https://git.cinege.com/thesaurus/ --- Dave -- https://mail.python.org/mailman/listinfo/python-list
Re: Python shows error on line 15 that i cant fix
On Saturday, September 21, 2019 at 2:46:15 PM UTC-4, boB Stepp wrote: > On Sat, Sep 21, 2019 at 1:01 PM Dave Martin wrote: > > > > On Saturday, September 21, 2019 at 1:33:12 PM UTC-4, Terry Reedy wrote: > > > On 9/21/2019 11:53 AM, Dave Martin wrote: > [...] > > > > #get the combined data and load the fits files > > > > > > > > fits_filename="Gaia_DR2/gaiadr2_100pc.fits" > > > > df=pd.DataFrame() > > > > with fits.open(fits_filename) as data: > > > > df=pd.DataFrame(data[1].data) > > > > > > A 'with' statement is a compound statement. It must be followed by a > > > 'suite', which usually consists of an indented block of statements. > > > This is line 17 from the first non-blank line you posted. > [...] > > > Can you provide an example of how to use the suite feature. Thank you. > > Dave, you seem to have some expectation that you should be given the > answer. That is not how help is given in this forum. You are > expected to be doing the needed to work before being helped further. > You have been referred to the tutorial multiple times. Please read > it! Indentation is so fundamental to structuring Python code that it > is clear that you need grounding in Python fundamentals. Otherwise > you are essentially Easter-egging through a code sample that you have > no true understanding of. > > If you must continue to Easter-egg Python instead of reading the > tutorial (or something equivalent) then check the section of the > tutorial on files. You will find examples of the use of "with" there. > > > -- > boB Bob, You seem to have the expectation that you know more about coding than me and that you can insult me without me retaliating. If I were you, I would leave this forum and never respond to another person question again, if you think that you can rudely ransack your way through what is supposed to be a helpful tool. -Dave -- https://mail.python.org/mailman/listinfo/python-list
Re: Python shows error on line 15 that i cant fix
On Saturday, September 21, 2019 at 1:33:12 PM UTC-4, Terry Reedy wrote: > On 9/21/2019 11:53 AM, Dave Martin wrote: > > > > # starAbsMags=df['radial_velocity'] > > > > #GaiaPandasEscapeVelocityCode > > > > import pandas as pd > > import numpy as np > > from astropy.io import fits > > import astropy > > import matplotlib.pyplot as plt > > > > > > #get the combined data and load the fits files > > > > fits_filename="Gaia_DR2/gaiadr2_100pc.fits" > > df=pd.DataFrame() > > with fits.open(fits_filename) as data: > > df=pd.DataFrame(data[1].data) > > A 'with' statement is a compound statement. It must be followed by a > 'suite', which usually consists of an indented block of statements. > This is line 17 from the first non-blank line you posted. > > Please stop spamming the list with multiple posts. Do spend a few hours > reading the tutorial until you understand my answer. > https://docs.python.org/3/tutorial/index.html Also read > https://stackoverflow.com/help/minimal-reproducible-example > so you can ask better questions. > > I presume you got "SyntaxError: expected an indented block". > A minimal example getting this error is, for instance, > > while True: > a = 1 > > -- > Terry Jan Reedy Can you provide an example of how to use the suite feature. Thank you. -- https://mail.python.org/mailman/listinfo/python-list
Re: python is bugging
On Saturday, September 21, 2019 at 12:44:27 PM UTC-4, Brian Oney wrote: > On Sat, 2019-09-21 at 08:57 -0700, Dave Martin wrote: > > On Saturday, September 21, 2019 at 11:55:29 AM UTC-4, Dave Martin > > wrote: > > > what does expected an indented block > > > > *what does an indented block mean? > > It means that the line of code belongs to a certain body as defined > above its position. > > Please follow the tutorial. > > https://docs.python.org/3/tutorial/index.html df.to_csv(r"faststars.csv", index=None,header=True) # starAbsMags=df['radial_velocity'] #GaiaPandasEscapeVelocityCode import pandas as pd import numpy as np from astropy.io import fits import astropy import matplotlib.pyplot as plt #get the combined data and load the fits files fits_filename="Gaia_DR2/gaiadr2_100pc.fits" df=pd.DataFrame() with fits.open(fits_filename) as data: df=pd.DataFrame(data[1].data) df.columns=[c.lower() for c in df.columns] print("Columns.") print(df.columns.values) print("n/n") #print out some data meta info to see what we're working with print("Number of stars:") nstars=len(df) print(nstars) distances = (df['parallax']/1000) starAbsMags =df['phot_g_mean_mag'] df = df[(df.parallax_over_error > 10 ) ] print("Left after filter: " +str(len(df)/float(nstars)*100)+" %") df.hist(column='radial_velocity') #fastdf=df[(df.radial_velocity > 200) | (df.radial_velocity < -200)] fastdf=df[(df.radial_velocity > 550)|(df.radial_velocity<-550)] print(len(fastdf)) #print(fastdf)# starTemps=df['astrometric_weight_al'] # df.plot.scatter("radial_velocity", "astrometric_weight_al", s=1, c="radial_velocity", colormap="plasma") # #df=df[(df.radial_velocity>=-550)] # #plt.axis([0,400,-800,-550]) # #plt.axis([0,400,550,800]) # plt.xlabel('weight(Au)') # plt.ylabel('Speed') # plt.title('Gaia Speed vs Weight') this is my code the error is on line 15 -- https://mail.python.org/mailman/listinfo/python-list
Re: python is bugging
On Saturday, September 21, 2019 at 11:55:29 AM UTC-4, Dave Martin wrote: > what does expected an indented block *what does an indented block mean? -- https://mail.python.org/mailman/listinfo/python-list
python is bugging
what does expected an indented block -- https://mail.python.org/mailman/listinfo/python-list
Python shows error on line 15 that i cant fix
# starAbsMags=df['radial_velocity'] #GaiaPandasEscapeVelocityCode import pandas as pd import numpy as np from astropy.io import fits import astropy import matplotlib.pyplot as plt #get the combined data and load the fits files fits_filename="Gaia_DR2/gaiadr2_100pc.fits" df=pd.DataFrame() with fits.open(fits_filename) as data: df=pd.DataFrame(data[1].data) df.columns=[c.lower() for c in df.columns] print("Columns.") print(df.columns.values) print("n/n") #print out some data meta info to see what we're working with print("Number of stars:") nstars=len(df) print(nstars) distances = (df['parallax']/1000) starAbsMags =df['phot_g_mean_mag'] df = df[(df.parallax_over_error > 10 ) ] print("Left after filter: " +str(len(df)/float(nstars)*100)+" %") df.hist(column='radial_velocity') #fastdf=df[(df.radial_velocity > 200) | (df.radial_velocity < -200)] fastdf=df[(df.radial_velocity > 550)|(df.radial_velocity<-550)] print(len(fastdf)) #print(fastdf)# starTemps=df['astrometric_weight_al'] # df.plot.scatter("radial_velocity", "astrometric_weight_al", s=1, c="radial_velocity", colormap="plasma") # #df=df[(df.radial_velocity>=-550)] # #plt.axis([0,400,-800,-550]) # #plt.axis([0,400,550,800]) # plt.xlabel('weight(Au)') # plt.ylabel('Speed') # plt.title('Gaia Speed vs Weight') -- https://mail.python.org/mailman/listinfo/python-list
Re: Formatting floating point
On 9/4/19 1:38 PM, Rhodri James wrote: On 04/09/2019 18:12, Dave via Python-list wrote: My question is why, and where do I find a reliable source of information on formatting numbers? Not interested in replacement values like '{} {}'.format(1, 2). Here: https://docs.python.org/3/library/string.html#format-specification-mini-language I suspect the thing you were overlooking was that format() expects to be given a format specification, and you gave it a format string. Instead of format(num, "{0:.1f}"), you wanted format(num, ".1f"). If you had tried "{0:.1f}".format(num) instead, you would have found that worked too. Thanks Rhodri Dave, -- https://mail.python.org/mailman/listinfo/python-list
Re: Formatting floating point
On 9/4/19 1:25 PM, Chris Angelico wrote: On Thu, Sep 5, 2019 at 3:16 AM Dave via Python-list wrote: All, I have been going in circles trying to format a floating point number so there is only 1 decimal place. In reading all of the gobble-gook that passes for Python advice, it looked like I should have done this: numStr = '3.14159' num = float(numstr) # OK so far numFmt = format(num, '{0:.1f}') # Errors on format string # --- Alternative that also does not work numFmt = float("{0:.1f}".format(numStr)) # --- numFmt = format(num, '0.1f')# Does work Let's start by eliminating a few possibilities here. Don't try formatting the original string, and don't call float() on the result afterwards; just start with a floating-point value, and then create a formatted string. If you think about starting with a value (which in this case is a number) and the need to make a displayable version (which implies that it's a string), your options basically look like this: num = 3.14159 num_fmt = format(num, ".1f") num_fmt = "{0:.1f}".format(num) num_fmt = f"{num:.1f}" All of these will give you back the string "3.1". All of them involve a format string of ".1f", and they differ only in how they're choosing which value to put there. Hopefully that will clear things up a bit. ChrisA That helps! Thanks Chris. Dave, -- https://mail.python.org/mailman/listinfo/python-list
Formatting floating point
All, I have been going in circles trying to format a floating point number so there is only 1 decimal place. In reading all of the gobble-gook that passes for Python advice, it looked like I should have done this: numStr = '3.14159' num = float(numstr) # OK so far numFmt = format(num, '{0:.1f}') # Errors on format string # --- Alternative that also does not work numFmt = float("{0:.1f}".format(numStr)) # --- numFmt = format(num, '0.1f')# Does work My question is why, and where do I find a reliable source of information on formatting numbers? Not interested in replacement values like '{} {}'.format(1, 2). Thanks, Dave -- https://mail.python.org/mailman/listinfo/python-list
Re: Application Preferences
On 8/19/19 1:53 PM, Barry Scott wrote: On 19 Aug 2019, at 13:43, Dave via Python-list wrote: The plan for an app that I'm doing was to use SQLite for data and to hold the preference settings as some apps do. The plan was changed last week to allow the user to select the location of the data files (SQLite) rather than putting it where the OS would dictate. Ok with that, but it brings up some questions. First, I will need to have a file that points to the location of the data file since that can't be hard coded. Second, if I have to have a file that is likely part of the application group of files, would it make more sense to use a more traditional preferences file? How have other Python app developers done in this case? There are expected locations for config files and data files on each OS. On macOS you would use ~/Library/Preferences/ and put a file or a folder of files in there. The convention is use your website name as the base name of the file or folder. For example for scm-workbench I use: org.barrys-emacs.scm-workbench as the folder name for all the scm-workbench files. On Windows you can use a file or folder in %APPDATA% that is named after your app. You should find the folder by doing a win32 API call to get the value. See getPreferencesDir() in https://github.com/barry-scott/scm-workbench/blob/master/Source/Common/wb_platform_win32_specific.py <https://github.com/barry-scott/scm-workbench/blob/master/Source/Common/wb_platform_win32_specific.py> for how to get the value. On Linux the XDG spec says that you should put config files in ~/.config/ and data files in ~/.local/share/. Doing XDG to the spec is a little involved. I have some experimental code that implements the logic for config the XdgConfigPath class in: https://github.com/barry-scott/CLI-tools/blob/master/Source/smart_find/__init__.py <https://github.com/barry-scott/CLI-tools/blob/master/Source/smart_find/__init__.py> Putting a file directly in the $HOME folder is no longer recommended. The format of the config data you are free to choose. I have been using JSON files recently as it allow for structured data. Barry Barry, and all, I agree that various OS's have a favorite place to put things. Python has a library that will help. However, there are valid reasons to let the customer choose. Perhaps the drive/folder is a journaling one, or one that is backed up multiple times per day. My take is to start with the OS solution, but let the customer decide. How did this thread show up in the SQLite mailing list anyway? Really has nothing to do with SQLite that I can see. Dave, -- https://mail.python.org/mailman/listinfo/python-list
Re: Application Preferences
On 8/19/19 9:22 AM, Malcolm Greene wrote: Hi Dave, The plan for an app that I'm doing was to use SQLite for data and to hold the preference settings as some apps do. The plan was changed last week to allow the user to select the location of the data files (SQLite) rather than putting it where the OS would dictate. Ok with that, but it brings up some questions. First, I will need to have a file that points to the location of the data file since that can't be hard coded. Second, if I have to have a file that is likely part of the application group of files, would it make more sense to use a more traditional preferences file? How have other Python app developers done in this case? We handle the "where is my config file" question by defaulting to script's current directory, then a script-specific folder within their home directory. Users can override that behavior by setting a script specific environment variable or by using a command line switch to point to a different location or config file. We store our preferences in an INI style config file which we've found easier to support when there's problems. Malcolm Malcolm, Thanks for the reply. I agree that a traditional INI file is the easiest way, especially since Python supports them. So if I understand you, your apps look like this: -App Dir | +-App Code Folder | +-(File to direct to home folder) -Home Folder (the default location, but user can select other locations) | +-App INI Folder | +-App INI file -- https://mail.python.org/mailman/listinfo/python-list
Application Preferences
The plan for an app that I'm doing was to use SQLite for data and to hold the preference settings as some apps do. The plan was changed last week to allow the user to select the location of the data files (SQLite) rather than putting it where the OS would dictate. Ok with that, but it brings up some questions. First, I will need to have a file that points to the location of the data file since that can't be hard coded. Second, if I have to have a file that is likely part of the application group of files, would it make more sense to use a more traditional preferences file? How have other Python app developers done in this case? Thanks, Dave -- https://mail.python.org/mailman/listinfo/python-list
Re: Create multiple sqlite tables, many-to-many design
On 8/13/19 5:46 PM, Rich Shepard wrote: On Tue, 13 Aug 2019, Rich Shepard wrote: Read Joe Celko's books, starting with his SQL Programming Guide, then SQL That should be SQL Programming Style Rich Rich, On my next trip to BN I'll see if they have them. That is long term though. Right now I just need to know how to populate the join table and anything else that has escaped me. SQL is cool. SQL + Python (or C or C++ or Java) is more cool. Lot easier to understand than pointer math in C. Dave, -- https://mail.python.org/mailman/listinfo/python-list
Re: Create multiple sqlite tables, many-to-many design
On 8/13/19 2:59 PM, Chris Angelico wrote: On Wed, Aug 14, 2019 at 4:50 AM Dave via Python-list wrote: Some of the tables are related. For example: Hiking_Table Trails_TableJoining_Table -- hike_id PK trail_id PKhike_id FK hike_date TEXT trail_name TEXTtrail_id FK hike_destination TEXTtrail_rating REAL hike_rating REALtrail_comments TEXT hike_comments TEXT So far, so good. I know how to create the tables. What I am struggling with is how do I insert data into the joining table or don"t I? If so, do I need to query the other two tables to get the auto-number ID's? Some things I have read suggest that the joining table just contains references, so there is no actual insert. A pointer to information how to do this would be appreciated. As for queries, I think I use joins, but a pointer on how to do this would also be appreciated. The joining table is a real thing, and will have real inserts. It might be easier to think of this as two separate one-to-many relationships; for the sake of demonstration, I'm going to add another column to your joining table. hike_sections ==> hike_id references hikes, trail_id references trails, companion_name You've decided to have someone with you for some sections of your hike. As such, what we have is a number of "mini-hikes" that make up a single hike (that's a one-to-many relationship between hikes and sections), and also a single trail can be a section of any number of hikes (so, another one-to-many relationship between trails and sections). For any given section, there is exactly one companion. Does this make the many-to-many relationship a bit easier to understand? It'll work exactly the same way even if you have no ancillary information in that joining table. ChrisA Chris, Thanks for the note. I get the theory of MTM and the join table. It is the implementation I don't get. Let me see if I can demonstrate my confusion using pseudo code. def dbTables_create (dbpath): sql_HikeTable = """ CREATE TABLE IF NOT EXISTS hike ( hike_id INTEGER AUTO_INCREMENT PRIMARY KEY, hike_date TEXT, hike_destination TEXT, hike_rating REAL, hike_comments TEXT ) """ sql_TrailTable = """ CREATE TABLE IF NOT EXISTS trail ( trail_id INTEGER AUTO_INCREMENT PRIMARY KEY, trail_name TEXT, trail_rating REAL, trail_comment TEXT ) """ sql_JoiningTable = """ CREATE TABLE IF NOT EXISTS hike_trail ( hike_id INTEGER trail_id INTEGER ) """ # Some more code to open connection, create cursor, execute SQL. def getUserInput (): # Code to get the user input. # The user input is: hdate = "2019-05-28" hdestination = "Top of White Face Mountain, NY." hrating = 5.0 # Rating scale 1.0 (bad) to 5.0 (perfect). hcomments "Got to do again. Better shoes needed." tname1 = "Brookside" trating1 = 4.5 tcomments1 = "Easy" tname2 = "Wilmington Trail" trating2 = 4.9 tcomments2 = "Awesome!!" def dbDataInsert(): sql_HikeInsert = """ INSERT INTO hike ( hike_date, hike_destination, hike_rating, hike_comments ) VALUES ( hdate, hdestination, hrating, hcomments ) """ sql_TrailInsert = """ NSERT INTO trail ( trail_name, trail_rating, trail_comment ) VALUES ( tname1, trating1, tcomments1 ) """ sql_TrailInsert = """ NSERT INTO trail ( trail_name, trail_rating, trail_comment ) VALUES ( tname2, trating2, tcomments2 ) """ """ ---> Now what? I need to populate the join (hike_trail) table. Do I query the tables to get the id's? Is there another way? This is the part I really don't get. """ Dave, -- https://mail.python.org/mailman/listinfo/python-list
Re: Create multiple sqlite tables, many-to-many design
On 8/13/19 4:45 PM, MRAB wrote: On 2019-08-13 19:59, Chris Angelico wrote: On Wed, Aug 14, 2019 at 4:50 AM Dave via Python-list wrote: Some of the tables are related. For example: Hiking_Table Trails_Table Joining_Table - - hike_id PK trail_id PK hike_id FK hike_date TEXT trail_name TEXT trail_id FK hike_destination TEXT trail_rating REAL hike_rating REAL trail_comments TEXT hike_comments TEXT So far, so good. I know how to create the tables. What I am struggling with is how do I insert data into the joining table or don"t I? If so, do I need to query the other two tables to get the auto-number ID's? Some things I have read suggest that the joining table just contains references, so there is no actual insert. A pointer to information how to do this would be appreciated. As for queries, I think I use joins, but a pointer on how to do this would also be appreciated. The joining table is a real thing, and will have real inserts. It might be easier to think of this as two separate one-to-many relationships; for the sake of demonstration, I'm going to add another column to your joining table. hike_sections ==> hike_id references hikes, trail_id references trails, companion_name You've decided to have someone with you for some sections of your hike. As such, what we have is a number of "mini-hikes" that make up a single hike (that's a one-to-many relationship between hikes and sections), and also a single trail can be a section of any number of hikes (so, another one-to-many relationship between trails and sections). For any given section, there is exactly one companion. Does this make the many-to-many relationship a bit easier to understand? It'll work exactly the same way even if you have no ancillary information in that joining table. Might I also suggest dropping unnecessary prefixes from the field names. For example, "hike_comments" in "Hiking_Table" can be called just "comments" because it's clear from the context that a field called "comments" in the hiking table will contain comments about hiking, if you see what I mean. I do indeed. I did that so it was easy for everyone to follow. Having started with assm. and C, I have to remind myself to be more explanatory in naming. Guess I over-did it. The actual code is different. htbl, ttbl, jtbl, etc. Too short? Dave, -- https://mail.python.org/mailman/listinfo/python-list
Create multiple sqlite tables, many-to-many design
Oops! Just posted this to the wrong newsgroup. Sorry!!! I'm doing a Python app that uses SQLite, and am stumbling on a few questions. I've read a lot of books and documentation, but two questions still allude me. Hope someone that been there done this can help. Below is a note I sent to the SQLite mailing list yesterday. So far, nothing. Need to get going, so many thanks! I'm doing an app. that uses sqlite, and has a many-to-many relationship. The areas I need some guidance are: * Best way to create multiple tables the first time the app. is started. * How to create a MTM relationship and add/modify data. I can create tables (Python) by putting the code in discrete functions for each table and passing just the path to the database. I can also create a calling function that gets a connection and passes that. What is the pro-con of each since each seems to work? Better ideas? Some of the tables are related. For example: Hiking_Table Trails_TableJoining_Table -- hike_id PK trail_id PKhike_id FK hike_date TEXT trail_name TEXTtrail_id FK hike_destination TEXTtrail_rating REAL hike_rating REALtrail_comments TEXT hike_comments TEXT So far, so good. I know how to create the tables. What I am struggling with is how do I insert data into the joining table or don"t I? If so, do I need to query the other two tables to get the auto-number ID's? Some things I have read suggest that the joining table just contains references, so there is no actual insert. A pointer to information how to do this would be appreciated. As for queries, I think I use joins, but a pointer on how to do this would also be appreciated. Thanks, Dave -- https://mail.python.org/mailman/listinfo/python-list
Python/SQLite best practices
I'm looking for some tips from experienced hands on on this subject. Some of the areas of interest are (feel free to add more): * Passing connections and cursors - good, bad indifferent? I try to avoid passing file handles unless necessary, so I view connections and cursors the same. Though that said, I'm not aware of any specific problems in doing so. For designs with multiple tables: * Better to pass an sql string to functions that create/add data/update/delete data and pass them to create, insert, update, delete functions; or have those functions for each table? Taking table creation for example, if there are five tables, and the sql string is passed, there would need to be six functions to do it, though the complexity of each function may be reduced a little. [table1create with sql and establishing a cursor, to table5create and then a function that executes the sql]. Best way to establish the connection and cursor, as well as close them? I have seen many ways to do this, and know that the with block can be used to create a connection and close it automatically, but the same is not true of the cursor. Also, using only a with block does not handle any errors as well as a try/with. For example: | try: | # Use with block to create connection – it will close self. | with sqlite3.connect(path) as conn: | cur = conn.cursor() | cur.execute(sql_ProjectsTable) | cur.close() | except Error as e: | print(e) What else? Dave, -- https://mail.python.org/mailman/listinfo/python-list
Re: Python best practice instantiating classes in app
On 4/29/19 3:26 PM, Terry Reedy wrote: On 4/29/2019 1:38 PM, Dave wrote: As apps get more complex we add modules, or Python files, to organize things. One problem I have is a couple of data classes (list of dictionary objects) in a few modules that are used in a number of the other modules. For example a list of meter reading dictionaries in one module is used by the user interface module to get the data from the user, a report module to display the data, and a file module to save and retrieve the data to/from file. All the modules need to use the same instance of the list classes. There are a number of ways to do this. One is a module that creates the objects, then import that module into all of the others. Works well, You can have one *or more* such modules. Perhaps you already do. but may not be the best way to do the job. In what way do you consider it unsatisfactory. It is not that I consider it unsatisfactory as much as I'm looking for the best way. I am constantly amazed at the thought that has been given to this language (with the exception of access modifiers - perhaps, and lack of a case statement), and often find that there is a better way of doing everything. A slight variation is to do this in the main module, but the main module has to be imported into the others. Avoid import loops unless really necessary. They often work, but when they don't ... its a pain. Since I use the main module as a calling module to load data, start the user interface, and to close things down, it may not be the best place to also create the classes. Another way to do this is have a line in each module to check the name. If it is the module name, then create the class and then import these modules in all the others. A tad messy and maybe a little confusing. Right. -- https://mail.python.org/mailman/listinfo/python-list
Python best practice instantiating classes in app
As apps get more complex we add modules, or Python files, to organize things. One problem I have is a couple of data classes (list of dictionary objects) in a few modules that are used in a number of the other modules. For example a list of meter reading dictionaries in one module is used by the user interface module to get the data from the user, a report module to display the data, and a file module to save and retrieve the data to/from file. All the modules need to use the same instance of the list classes. There are a number of ways to do this. One is a module that creates the objects, then import that module into all of the others. Works well, but may not be the best way to do the job. A slight variation is to do this in the main module, but the main module has to be imported into the others. Since I use the main module as a calling module to load data, start the user interface, and to close things down, it may not be the best place to also create the classes. Another way to do this is have a line in each module to check the name. If it is the module name, then create the class and then import these modules in all the others. A tad messy and maybe a little confusing. So what are the suggestions from people that have been down this road before? Thanks, Dave -- https://mail.python.org/mailman/listinfo/python-list
Re: How call method from a method in same class?
On 4/1/19 10:29 PM, Cameron Simpson wrote: On 01Apr2019 22:02, Dave wrote: As classes get more complex, it is good to call a function to do some of the processing, and make the code easier to follow. My question is how to do that? I've attached some silly code to illustrate the point. The error is: name 'validScale' is not defined. Well, yes it is, but maybe not the correct way. Suggestions? It is and it isn't. See below: class TempConverter(): """ Temperature Converter converts a tempeature from one scale to another scale. For example: 32, F, C will return 0 degrees C """ [...] def validScale(self, scaleName): if scaleName.upper == 'F' or 'C' or 'K': return True else: return False def convertTemp(self): """ Converts temperature scale if scales valid.""" if validScale(self.scale): scaleValid = True [...] It is an instance method, so: if self.validScale(self.scale) would resolve the name. However, there are several things worth discussing here. First up, validScale itself returns a Boolean, so just return the test result. Change: if scaleName.upper == 'F' or 'C' or 'K': return True else: return False into: return scaleName.upper == 'F' or 'C' or 'K' Second, the condition is buggy. You want this: return scaleName.upper() in ('F', 'C', 'K') i.e. you need to call (the "()") the .upper method, and you need to check if the result is in your collection of valid results. This expression: value == A or B or C means: True if value == A, otherwise B if B is true, otherwise C. The next thing to observe is that you're testing whether self.scale is valid. Normal practice would be to make that test in __init__, and raise a ValueError if it is not so: def __init__(self, .scale...): if scale.upper() not in ('F', 'C', 'K'): raise ValueError("invalid scale %r: expected one of F, C or K" % (scale,)) why recite the scale in the message? Because it makes the offending value obvious. In particular, if for example you called this incorrectly and had the temperature in there instead of the scale that will be trivial to debug from the message. Of course, you actually want to be able to test any scal evalue for validity, not just the one stuffed into your instance (.scale). So lets revisit the validScale method: def validScale(self, scale): return scaleName.upper() in ('F', 'C', 'K') You'll notice that it doesn't depend in "self". Or, for that matter, the class. So this is a "static" method: a function defined in the class for conceptual clarity, but not with any dependence on the class itself or a particular class instance. So: @staticmethod def validScale(scale): return scaleName.upper() in ('F', 'C', 'K') In __init__, and elsewhere, you can still call this from the instance: def __init__(self, .scale...): if not self.validScale(scale): raise ValueError("invalid scale %r: expected one of F, C or K" % (scale,)) You can also call this from _outside_ the class, for example for other validation: scale = input("Enter a temperate scale name (F, C or K): ") if not TempConverter.validScale(scale): print("Bad! Bad user!") newScaleValid = True Again, validScale returns a Boolean. So you could have just gone: newScaleValid = self.validScale(newScale) if scaleValid and newScaleValid: print('Scale converted') else: msg = "There was and error with the scales entered.\n" msg = msg + "You entered: " + self.scale msg = msg + ' ' 'and' + self.newScale print(msg) if __name__ == "__main__": myclass = TempConverter(32, 'f', 'c') myclass.convertTemp() My personal inclination would be do define a Temperature class with a convert function to be used like this: temp = Temperature(32, 'f') tempC = temp.convert('c') This reduces the complexity of the class and IMO makes it easier to use elsewhere. BTW, you get an instance back from tempConverter(...), not a class. So don't call it "myclass". Cheers, Cameron Simpson Cameron, I'm going to need a while to work through this. As I mentioned, this was quick and dirty code just to illustrate a point - not intended to be good code. So I'll take a close read tomorrow. Thanks again!! Dave, -- https://mail.python.org/mailman/listinfo/python-list
Re: How call method from a method in same class?
On 4/1/19 10:02 PM, Dave wrote: As classes get more complex, it is good to call a function to do some of the processing, and make the code easier to follow. My question is how to do that? I've attached some silly code to illustrate the point. The error is: name 'validScale' is not defined. Well, yes it is, but maybe not the correct way. Suggestions? Dave, class TempConverter(): """ Temperature Converter converts a tempeature from one scale to another scale. For example: 32, F, C will return 0 degrees C """ def __init__(self, temperature, scale, newScale): self.temperature = temperature self.scale = scale self.newScale = newScale def validScale(self, scaleName): if scaleName.upper == 'F' or 'C' or 'K': return True else: return False def convertTemp(self): """ Converts temperature scale if scales valid.""" if validScale(self.scale): scaleValid = True if validScale(self.newScale): newScaleValid = True if scaleValid and newScaleValid: print('Scale converted') else: msg = "There was and error with the scales entered.\n" msg = msg + "You entered: " + self.scale msg = msg + ' ' 'and' + self.newScale print(msg) if __name__ == "__main__": myclass = TempConverter(32, 'f', 'c') myclass.convertTemp() Thanks all for your (ready, wait for it) self-lessness help (get it?) Dave (laughing) -- https://mail.python.org/mailman/listinfo/python-list
Re: How call method from a method in same class?
On 4/1/19 10:12 PM, Irv Kalb wrote: On Apr 1, 2019, at 7:02 PM, Dave wrote: As classes get more complex, it is good to call a function to do some of the processing, and make the code easier to follow. My question is how to do that? I've attached some silly code to illustrate the point. The error is: name 'validScale' is not defined. Well, yes it is, but maybe not the correct way. Suggestions? Dave, class TempConverter(): """ Temperature Converter converts a tempeature from one scale to another scale. For example: 32, F, C will return 0 degrees C """ def __init__(self, temperature, scale, newScale): self.temperature = temperature self.scale = scale self.newScale = newScale def validScale(self, scaleName): if scaleName.upper == 'F' or 'C' or 'K': return True else: return False def convertTemp(self): """ Converts temperature scale if scales valid.""" if validScale(self.scale): scaleValid = True if validScale(self.newScale): newScaleValid = True if scaleValid and newScaleValid: print('Scale converted') else: msg = "There was and error with the scales entered.\n" msg = msg + "You entered: " + self.scale msg = msg + ' ' 'and' + self.newScale print(msg) if __name__ == "__main__": myclass = TempConverter(32, 'f', 'c') myclass.convertTemp() -- https://mail.python.org/mailman/listinfo/python-list To answer your specific question, you call a method in the same class by calling: self.methodName For example: self.validScale However, once you fix that, you wind find that the if statement in that method is not built correctly. Also, since the variable self.scale is already set in your __init__ method, there is no need to pass it into your function. You could just use self.scale inside that method. Irv Irv, Thanks for the response! I realize the code is junk - just done to illustrate the problem. Dave, -- https://mail.python.org/mailman/listinfo/python-list
How call method from a method in same class?
As classes get more complex, it is good to call a function to do some of the processing, and make the code easier to follow. My question is how to do that? I've attached some silly code to illustrate the point. The error is: name 'validScale' is not defined. Well, yes it is, but maybe not the correct way. Suggestions? Dave, class TempConverter(): """ Temperature Converter converts a tempeature from one scale to another scale. For example: 32, F, C will return 0 degrees C """ def __init__(self, temperature, scale, newScale): self.temperature = temperature self.scale = scale self.newScale = newScale def validScale(self, scaleName): if scaleName.upper == 'F' or 'C' or 'K': return True else: return False def convertTemp(self): """ Converts temperature scale if scales valid.""" if validScale(self.scale): scaleValid = True if validScale(self.newScale): newScaleValid = True if scaleValid and newScaleValid: print('Scale converted') else: msg = "There was and error with the scales entered.\n" msg = msg + "You entered: " + self.scale msg = msg + ' ' 'and' + self.newScale print(msg) if __name__ == "__main__": myclass = TempConverter(32, 'f', 'c') myclass.convertTemp() -- https://mail.python.org/mailman/listinfo/python-list
Re: configparser - which one?
On 3/26/19 4:29 AM, Terry Reedy wrote: On 3/25/2019 8:10 PM, Dave wrote: I use Python3 3, and expected learning how to use configparser would be no big deal. Well! Seems there is configparser, stdconfigparser, and configparser is what IDLE uses. I would read the extra or deleted features of the others and see if they apply to your client's project. safeconfigparser, and multiple ways to set the section and entries to the section. A little confusing. I want to future-proof may code, so what should I be using? As for setting the sections and entries, the following both work. from configparser import ConfigParser # Python 3 syntax parser = ConfigParser() parser['DEFAULT'] = {'Language': 'English', 'Units': 'English', 'UseDefaults': 'True', 'NumberRidesDisplay': '30', 'Pi': '3.14'} The dict interface is newer but I doubt that the older one will go away. (IDLE uses it because it predates the dict interface. Since this code is pretty static, I do not currently see a payoff for conversion.) parser.add_section('Default') parser.set('default', 'language', 'english') parser.set('default', 'units_measure', 'english') parser.set('default', 'background_color', 'white') parser.set('default', 'useDefaults', 'true') parser.set('default', 'numToDisp', '12') parser.set('default', 'pi', '3.14') The advantage of the former is that it will handle 'DEFAULT', while the last one won't. I like the former, but not sure if it is the future. We do not remove things and break backwards compatibility lightly. Thanks everyone. So, I'll use configparser, but I do like the dictionary API as it makes the code a little easier as I can pass as arguments a section name and a dictionary with the contents to a function to write the complete section. Dave, -- https://mail.python.org/mailman/listinfo/python-list
Re: configparser - which one?
On 3/25/19 10:58 PM, DL Neil wrote: Dave, On 26/03/19 1:10 PM, Dave wrote: I use Python3 3, and expected learning how to use configparser would be no big deal. Well! Seems there is configparser, stdconfigparser, and safeconfigparser, and multiple ways to set the section and entries to the section. A little confusing. I want to future-proof may code, so what should I be using? (with apologies for not answering the question directly) After striking this problem, I was encouraged to take a look at JSON, and thence YAML. Once there, as they say, didn't look back! - multi-dimensional possibilities, cf .ini - similarity/correspondence with Python data structures - convenient PSL - easily adopted by (power-)users, cf Python code WebRefs: - similar Q: https://stackoverflow.com/questions/5055042/whats-the-best-practice-using-a-settings-file-in-python - article: https://martin-thoma.com/configuration-files-in-python/ - similar discussion: https://stackoverflow.com/questions/3085029/pros-and-cons-for-different-configuration-formats Wish I could do that. Customer wants .ini. I would need to sell them on an alternative. The issue is human readable - .ini is easier for people to understand. Dave, -- https://mail.python.org/mailman/listinfo/python-list
configparser - which one?
I use Python3 3, and expected learning how to use configparser would be no big deal. Well! Seems there is configparser, stdconfigparser, and safeconfigparser, and multiple ways to set the section and entries to the section. A little confusing. I want to future-proof may code, so what should I be using? As for setting the sections and entries, the following both work. from configparser import ConfigParser # Python 3 syntax parser = ConfigParser() parser['DEFAULT'] = {'Language': 'English', 'Units': 'English', 'UseDefaults': 'True', 'NumberRidesDisplay': '30', 'Pi': '3.14'} parser.add_section('Default') parser.set('default', 'language', 'english') parser.set('default', 'units_measure', 'english') parser.set('default', 'background_color', 'white') parser.set('default', 'useDefaults', 'true') parser.set('default', 'numToDisp', '12') parser.set('default', 'pi', '3.14') The advantage of the former is that it will handle 'DEFAULT', while the last one won't. I like the former, but not sure if it is the future. Thanks, Dave -- https://mail.python.org/mailman/listinfo/python-list
Re: ANN: Creating GUI Applications with wxPython
On 2/27/19 11:38 AM, Rhodri James wrote: On 27/02/2019 15:37, Dave wrote: * GUI must support all desktops with a native look and feel. Kivy fails this one. Will have mobile apps later in the year, so it would be nice if one GUI fits all, but am ok with 2 gui's if needed. This requirement will cause you endless pain, particularly when mobiles enter the picture. I'm not convinced it's a completely good idea; a sensible UI for a desktop probably won't be sensible for a phone and vice versa Agreed - that is why I'm open to two GUI kits. Dave -- https://mail.python.org/mailman/listinfo/python-list
Re: ANN: Creating GUI Applications with wxPython
Sorry about the duplicate messages - bad hair day! Dave, On 2/27/19 10:38 AM, Dave wrote: On 1/14/19 2:08 PM, Mike Driscoll wrote: Hi, I just thought I would let you all know that I am working on my 2nd wxPython book, "Creating GUI Applications with wxPython". This one will be about actually creating small runnable applications instead of just recipes like my Cookbook did. I hope to have 8-10 working applications included with the book. You can read more about it here if you are interested: https://www.blog.pythonlibrary.org/2019/01/14/creating-gui-applications-with-wxpython-kickstarter/ Feel free to ask me questions about it too. Thanks, Mike Mike, I have two Python 3 (3.6) apps that will get the full GUI treatment very soon. I'm in the process of choosing a GUI, and that may be where you/your book can help. Seems this is not a trivial effort (wishing that Python was like VB6 from the 90's). Anyway, here is what I am looking for - hopefully it helps guide you. * GUI relatively easy to understand and implement. easyGUI is truly easy in all areas, but fails some of my other requirements. The QT/PyQT/PySide2 situation is a mess - which one to use, why, any implementation differences, etc. * Performance is very good. Users hate to wait - for anything! * Lots of widgets! I'll need a spreadsheet-like widget, a form widget to enter information on parts, activities, etc., splash screen that the code can talk to while the app is loading, and the big one - a cross-platform printer widget that works with Windows and Mac/Unix/CUPS. A network widget may also be good. * A GUI designer may be good. Currently there is Glade for GTK, and QT-Designer for QT. * GUI must support all desktops with a native look and feel. Kivy fails this one. Will have mobile apps later in the year, so it would be nice if one GUI fits all, but am ok with 2 gui's if needed. * A great book taking me from beginner to expert. Dave, -- https://mail.python.org/mailman/listinfo/python-list
Re: ANN: Creating GUI Applications with wxPython
On 1/14/19 2:08 PM, Mike Driscoll wrote: Hi, I just thought I would let you all know that I am working on my 2nd wxPython book, "Creating GUI Applications with wxPython". This one will be about actually creating small runnable applications instead of just recipes like my Cookbook did. I hope to have 8-10 working applications included with the book. You can read more about it here if you are interested: https://www.blog.pythonlibrary.org/2019/01/14/creating-gui-applications-with-wxpython-kickstarter/ Feel free to ask me questions about it too. Thanks, Mike Mike, I have two Python 3 (3.6) apps that will get the full GUI treatment very soon. I'm in the process of choosing a GUI, and that may be where you/your book can help. Seems this is not a trivial effort (wishing that Python was like VB6 from the 90's). Anyway, here is what I am looking for - hopefully it helps guide you. * GUI relatively easy to understand and implement. easyGUI is truly easy in all areas, but fails some of my other requirements. The QT/PyQT/PySide2 situation is a mess - which one to use, why, any implementation differences, etc. * Performance is very good. Users hate to wait - for anything! * Lots of widgets! I'll need a spreadsheet-like widget, a form widget to enter information on parts, activities, etc., splash screen that the code can talk to while the app is loading, and the big one - a cross-platform printer widget that works with Windows and Mac/Unix/CUPS. A network widget may also be good. * A GUI designer may be good. Currently there is Glade for GTK, and QT-Designer for QT. * GUI must support all desktops with a native look and feel. Kivy fails this one. Will have mobile apps later in the year, so it would be nice if one GUI fits all, but am ok with 2 gui's if needed. * A great book taking me from beginner to expert. Dave, -- https://mail.python.org/mailman/listinfo/python-list
Re: ANN: Creating GUI Applications with wxPython
On 1/14/19 2:08 PM, Mike Driscoll wrote: Hi, I just thought I would let you all know that I am working on my 2nd wxPython book, "Creating GUI Applications with wxPython". This one will be about actually creating small runnable applications instead of just recipes like my Cookbook did. I hope to have 8-10 working applications included with the book. You can read more about it here if you are interested: https://www.blog.pythonlibrary.org/2019/01/14/creating-gui-applications-with-wxpython-kickstarter/ Feel free to ask me questions about it too. Thanks, Mike Mike, I have two Python 3 (3.6) apps that will get the full GUI treatment very soon. I'm in the process of choosing a GUI, and that may be where you/your book can help. Seems this is not a trivial effort (wishing that Python was like VB6 from the 90's). Anyway, here is what I am looking for - hopefully it helps guide you. * GUI relatively easy to understand and implement. easyGUI is truly easy in all areas, but fails some of my other requirements. The QT/PyQT/PySide2 situation is a mess - which one to use, why, any implementation differences, etc. * Performance is very good. Users hate to wait - for anything! * Lots of widgets! I'll need a spreadsheet-like widget, a form widget to enter information on parts, activities, etc., splash screen that the code can talk to while the app is loading, and the big one - a cross-platform printer widget that works with Windows and Mac/Unix/CUPS. A network widget may also be good. * A GUI designer may be good. Currently there is Glade for GTK, and QT-Designer for QT. * GUI must support all desktops with a native look and feel. Kivy fails this one. Will have mobile apps later in the year, so it would be nice if one GUI fits all, but am ok with 2 gui's if needed. * A great book taking me from beginner to expert. Dave, -- https://mail.python.org/mailman/listinfo/python-list
Re: ANN: Creating GUI Applications with wxPython
On 1/14/19 2:08 PM, Mike Driscoll wrote: Hi, I just thought I would let you all know that I am working on my 2nd wxPython book, "Creating GUI Applications with wxPython". This one will be about actually creating small runnable applications instead of just recipes like my Cookbook did. I hope to have 8-10 working applications included with the book. You can read more about it here if you are interested: https://www.blog.pythonlibrary.org/2019/01/14/creating-gui-applications-with-wxpython-kickstarter/ Feel free to ask me questions about it too. Thanks, Mike Mike, I have two Python 3 (3.6) apps that will get the full GUI treatment very soon. I'm in the process of choosing a GUI, and that may be where you/your book can help. Seems this is not a trivial effort (wishing that Python was like VB6 from the 90's). Anyway, here is what I am looking for - hopefully it helps guide you. * GUI relatively easy to understand and implement. easyGUI is truly easy in all areas, but fails some of my other requirements. The QT/PyQT/PySide2 situation is a mess - which one to use, why, any implementation differences, etc. * Performance is very good. Users hate to wait - for anything! * Lots of widgets! I'll need a spreadsheet-like widget, a form widget to enter information on parts, activities, etc., splash screen that the code can talk to while the app is loading, and the big one - a cross-platform printer widget that works with Windows and Mac/Unix/CUPS. * GUI must support all desktops with a native look and feel. Kivy fails this one. Will have mobile apps later in the year, so it would be nice if one GUI fits all, but am ok with 2 gui's if needed. * A great book taking me from beginner to expert. Dave, -- https://mail.python.org/mailman/listinfo/python-list
preferences file
I'm doing a small application and want to add user preferences. Did some googling to see if there are standard Python ways/tools, but it seems not so much. My specific questions are: 1. Best practices for a user preference file/system? 2. File format favored and why - ini, JSON, etc? 3. File location? I'm using Ubuntu and I believe that the correct location would be home/.config/ . What about Mac and Windows? Would like to find a Python library that handles all of this, but so far... Thanks, Dave -- https://mail.python.org/mailman/listinfo/python-list
System printer object
I need to print to one or both of my system printers. I have not found a printer object in Python or in Tkinter. This needs to work with Linux, Window, and Mac. Can someone point me in the right direction? Ultimately, I want to have a File/Print in the menu that lets me select the printer and properties. Thanks, Dave -- https://mail.python.org/mailman/listinfo/python-list
Re: Kivy native GUI examples
On 1/7/19 11:14 AM, Thomas Jollans wrote: On 07/01/2019 15.51, Dave wrote: I need to select a Python GUI. It needs to cover all of the desktops (Linux, Windows, Apple) and hopefully mobile (Android and Ios). I'm looking at Kivy, but have yet to find an example app. that has a native looking GUI (Windows, Mac, Linux/Gnome/KDE). Is that possible and anyone know of some examples? AFAIK looking like a native app is quite simply not something Kivy helps you with. If that's important, you should look into other options such as Qt (PyQt5 or PySide2). -- Thomas Thanks Thomas. -- https://mail.python.org/mailman/listinfo/python-list
Kivy native GUI examples
I need to select a Python GUI. It needs to cover all of the desktops (Linux, Windows, Apple) and hopefully mobile (Android and Ios). I'm looking at Kivy, but have yet to find an example app. that has a native looking GUI (Windows, Mac, Linux/Gnome/KDE). Is that possible and anyone know of some examples? Thanks, Dave -- https://mail.python.org/mailman/listinfo/python-list
Re: Appending data to a json file
On 04/04/2017 01:50 PM, Rob Gaddi wrote: On 04/04/2017 10:23 AM, Dave wrote: I don't care for the idea of replacing the data file for every save. My preference would to append to the existing data file - makes more sense. However, that is not how json works. So, I'm considering other alternatives for a data file structure. Paired data (key and value) is not really required, but my feeling is that it makes the data file more robust. A database seems a little over the top for this situation since there is no querying of data - just load and save. Dave, Valid. That said, the database implementation (especially if you just use Sqlite) is written, done, and works. There are reasons that a lot of programs use it just to store things like user settings. Having a backend that's already ACID takes a lot of stress out of things like what I'm assuming you don't like about full data file replacement: what happens if you get a powerfail midway through. I'm not saying it's the right answer, but it's not nearly so much flyswatting with a sledgehammer as you may think. I'll take a look at it. Thanks! Dave, -- https://mail.python.org/mailman/listinfo/python-list
Re: Appending data to a json file
On 04/04/2017 10:17 AM, Michael Torrie wrote: On 04/03/2017 11:31 PM, dieter wrote: Dave writes: I created a python program that gets data from a user, stores the data as a dictionary in a list of dictionaries. When the program quits, it saves the data file. My desire is to append the new data to the existing data file as is done with purely text files. Usually, you cannot do that: "JSON" stands for "JavaScript Object Notation": That's assuming he's using JSON; he never specified what he's using to represent data as plain text. Though I suspect you're correct, for all we know he could just be writing data using his own text representation or writing to an ini file. And in his case it sounds like JSON is not an ideal method for saving his data since he's wanting to only append data, not read it in his program. In the future, Dave, please provide all the information pertaining to the problem so we can give accurate advice. Don't make us guess or assume we can all infer this information. I did. Please see the subject - it is json, not some bastardized version of it. While I didn't explicitly say that the data is read back in, it is - when the program starts. The user can enter more data, then save the data to the list (append). Then, like any other program, they can save the data to file. I don't care for the idea of replacing the data file for every save. My preference would to append to the existing data file - makes more sense. However, that is not how json works. So, I'm considering other alternatives for a data file structure. Paired data (key and value) is not really required, but my feeling is that it makes the data file more robust. A database seems a little over the top for this situation since there is no querying of data - just load and save. Dave, -- https://mail.python.org/mailman/listinfo/python-list
Appending data to a json file
I created a python program that gets data from a user, stores the data as a dictionary in a list of dictionaries. When the program quits, it saves the data file. My desire is to append the new data to the existing data file as is done with purely text files. However, I can't find a way to do that. The advice I have seen on the web is to load the data when the program starts, append the new user input to the list, then re-write the data file. Is that the best way, or is there a better way? Thanks, Dave -- https://mail.python.org/mailman/listinfo/python-list
where is it
I am trying to associate the .py file extension with idle...where IS idle? Can you make it a bit more difficult to load/use your software please. -- https://mail.python.org/mailman/listinfo/python-list
Re: exit from Tkinter mainloop Python 2.7
kevind0...@gmail.com wrote: >from Tkinter import * > >def butContinue(): >root1.destroy() As Christian said, you're destroying the root window and its children, so instead use root1.quit() here. > ... > >root1.mainloop() > >print entryName.get("1.0", "end-1c" ) >print entryPWord.get("1.0", "end-1c" ) And your root1.destroy() goes here instead. (The root window would normally be destroyed on the script exit, but some IDE debuggers will leave it open.) -- https://mail.python.org/mailman/listinfo/python-list
Re: [newbie] Problem with matplotlib
Dave Farrance wrote: >It occurs to me now that the trackback might misidentify the module in >use, if say, you'd named a file "numbers.py" then got rid of it later >leaving a "numbers.pyc" somewhere. If so, see where it is: > >import numbers >print numbers.__file__ I seem to have "numbers" on the brain. Replace with "decimal", of course. -- https://mail.python.org/mailman/listinfo/python-list
Re: [newbie] Problem with matplotlib
It occurs to me now that the trackback might misidentify the module in use, if say, you'd named a file "numbers.py" then got rid of it later leaving a "numbers.pyc" somewhere. If so, see where it is: import numbers print numbers.__file__ -- https://mail.python.org/mailman/listinfo/python-list
Re: [newbie] Problem with matplotlib
jenswaelk...@gmail.com wrote: > File "/usr/lib/python2.7/decimal.py", line 3744, in >_numbers.Number.register(Decimal) >AttributeError: 'module' object has no attribute 'Number' Your decimal module seems broken. Confirm that in the Python shell: import numbers print numbers.Number I'm guessing you'll get: AttributeError: 'module' object has no attribute 'Number' It appears to be the usual decimal module of the current linux system python 2.7, so a corrupt hard disk? -- https://mail.python.org/mailman/listinfo/python-list
Re: Tkinter problem: TclError> couldn't connect to display ":0
gemjack...@gmail.com wrote: >This fixed my problem with thkinter. sudo cp ~/.Xauthority ~root/ Which means that you were creating a GUI window with Python as root, which is to be avoided if you can. If you can't avoid it and you're running it with sudo in a bash console, rather than a root console, then I'd suggest adding the line... XAUTHORITY=$HOME/.Xauthority ...to the root's .bashrc which avoids putting a specific user's xauthority file in the root directory. -- https://mail.python.org/mailman/listinfo/python-list
Please Unsubscribe
-- https://mail.python.org/mailman/listinfo/python-list
Re: Install Numba on Debian
Dave Farrance wrote: >I'd like to install Numba on Debian Jessie to work with the system >Python 2.7.9 (rather than installing Anaconda). OK, never mind. Fixed. By Googling the first error code, finding a suggested fix for that, running again, Googling the new error, and several repeats of that, and I've now got a working solution. This recipe that somebody put on Github overcomes the main hurdle: https://gist.github.com/sshillo/62955e46cb05e2b47ad3 The main issue seems to be that contrary to the instructions on the Numba website, it's now a requirement to have LLVM 3.6 installed, not LLVM 3.5 which is in the Debian repository, and not LLVM 3.7 which is the latest release at llvm.org. Fortunately, a prebuilt LLVM 3.6 is available at llvm.org. Also I needed to install this lot from the Debian repository: python-pip python-setuptools build-essential python-enum34 libedit-dev python-dev -- https://mail.python.org/mailman/listinfo/python-list
Install Numba on Debian
I'd like to install Numba on Debian Jessie to work with the system Python 2.7.9 (rather than installing Anaconda). When I follow the instructions at https://github.com/numba/numba#custom-python-environments ...I get errors when trying to install Numba either with the git clone method or installing it with pip. I'll put the error log on Pastebin since its so large: http://pastebin.com/gbrj0iHw I've Googled for recipes for installing numba on Debian, installed every Debian package suggested as a possible dependency, and still no luck. Anybody know a working method for installing Numba on Debian Jessie without Anaconda? -- https://mail.python.org/mailman/listinfo/python-list
Re: help
sam Rogers wrote: > I have downloaded python 2.7 with no problem. It works. I am trying to get >pyserial to work. I have tried many different solutions. I am not sure if it >works or not. How can I be sure? I am using windows 7. I did not see any help >at python.org. Can you help? >PS my goal is make this adafruit project work. >https://learn.adafruit.com/arduino-lesson-17-email-sending-movement-detector/overview Before using Python, have you verified that the IDE talks on the serial port OK -- and that you can upload the simple blink sketch from its provided examples and that you can change the blink rate of the LED? Having done that, can you establish 2 way communication with Python? What happens if you try the simple test script below? You will need to change the "dev" line to whichever port you're using. // Arduino sketch to echo serial port strings char buf[81]; // max 80 chars + null int siz = 0; // size of input string void setup(){ Serial.begin(9600); Serial.setTimeout(100); } void loop(){ siz = Serial.readBytesUntil('\n',buf,80); // get input string if (siz == 0) return; // if timeout, loop again Serial.print("I heard: "); // reply with some text and buf[siz] = 0; // must add null terminator Serial.println(buf); // return original string } #!/usr/bin/env python2 import serial,time # LINUX PORT -- change to "COM1" or whatever for Windows dev = "/dev/ttyACM0" ser = serial.Serial(dev, 9600, timeout=1) time.sleep(2) # Arduino starts in ~1.6s while True: mystr = raw_input("Enter text max 80 chars: ") if mystr == '': break # terminate prog with ser.flushInput() # flush input just in case ser.write(mystr + '\n') # send newline-terminated string txt = ser.readline(80)# read newline-terminated string print len(txt),"chars: ",txt, # \r\n included so add final comma ser.close() # close port -- https://mail.python.org/mailman/listinfo/python-list
Re: Turtle
Stallone Carl wrote: >I am currently using python 3.5.0 and I have been trying to write a program >using turtle but is not seem to be working. I have followed all tutarial on >the web and when i compare it with my code my am duing everything the same >way but it still don't seems to be working I tryed repairen python but >still no difference. Please help me. OK. Which tutorial? What did you try? What went wrong? Was there an error message? If there was, what was it? When learning something on a computer, start with the simplest possible example. Only when that's working do you move on to more complex stuff. So with turtle graphics, start by writing a program that draws just one line. -- https://mail.python.org/mailman/listinfo/python-list
Re: Unicode failure (Solved)
"D'Arcy J.M. Cain" wrote: >On Fri, 4 Dec 2015 18:28:22 -0500 >Terry Reedy wrote: >> Tk widgets, and hence IDLE windows, will print any character from >> \u to \u without raising, even if the result is blank or ?. >> Higher codepoints fail, but allowing the entire BMP is better than >> any Windows codepage. > >Thanks to all. Following up on the various posts brought me to >information that solved my problem. Basicall I added "export >PYTHONIOENCODING=utf8" to my environment and "SetEnv PYTHONIOENCODING >utf8" in my Apache config and now things are working as they should. > >Thanks all. Hmmm. I hadn't seen this post before replying to the original because my newsreader put this post in a later thread because: (a) The subject header was changed (b) The reference header is for a post that's not present in Usenet That raises another question. I'm seeing a number of broken threads because people reply to posts that are not present in Usenet. It's not just my main news-server because my newreader can gather posts from several Usenet servers and those posts are nowhere on Usenet. Case in point: The post by Terry Reedy quoted above, reference . I presume that it's on the list server even though it's not on Usenet. Anybody know what's going on? -- https://mail.python.org/mailman/listinfo/python-list
Re: Unicode failure
I was taking it for granted that you knew how to set environment variables, but just in case you don't: In the shell, (are you using BASH?), put this: export PYTHONIOENCODING=UTF-8 ...then run your script. Remember that this is *not* a permanent fix. -- https://mail.python.org/mailman/listinfo/python-list
Re: Unicode failure
"D'Arcy J.M. Cain" wrote: >... >utf-8 >Traceback (most recent call last): > File "./g", line 5, in >print(u"\N{TRADE MARK SIGN}") >UnicodeEncodeError: 'ascii' codec can't encode character '\u2122' in >position 0: ordinal not in range(128) I *presume* that you're using Linux since you've got a hashbang, so... You can *check* that it's the local environment that's the issue with the *test* of setting the PYTHONIOENCODING environment variable. But if that works, then it tells you must then fix the underlying environment's character encoding to give a permanent fix. $ PYTHONIOENCODING=UTF-8 python3 -c 'print(u"\u00A9")' © $ PYTHONIOENCODING=ascii python3 -c 'print(u"\u00A9")' Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'ascii' codec can't encode character '\xa9' in position 0: ordinal not in range(128) -- https://mail.python.org/mailman/listinfo/python-list
Re: Object identity has no necessary connection to memory location (was: What is a function parameter =[] for?)
Ben Finney wrote: >Dave Farrance writes: > >> Marko Rauhamaa wrote: >> >> >Dave Farrance : >> > >> >> (Conversely, I see that unlike CPython, all PyPy's numbers have >> >> unchanging ids, even after exiting PyPy and restarting, so it seems >> >> that PyPy's numerical ids are "faked".) >> > >> >What's a faked id? >> >> You can figure out what I'm getting at -- i.e. I presume that the ids >> are not pointers to stored numbers in memory (as with CPython) but are >> a translation of the numerical variable's value. > >Why refer to that as “faked”? That's what I can't figure out about what >you're getting at. Perhaps Marko shares my uncomprehension. Hence https://en.wikipedia.org/wiki/Scare_quotes -- https://mail.python.org/mailman/listinfo/python-list
Re: What is a function parameter =[] for?
Marko Rauhamaa wrote: >Dave Farrance : > >> (Conversely, I see that unlike CPython, all PyPy's numbers have >> unchanging ids, even after exiting PyPy and restarting, so it seems >> that PyPy's numerical ids are "faked".) > >What's a faked id? You can figure out what I'm getting at -- i.e. I presume that the ids are not pointers to stored numbers in memory (as with CPython) but are a translation of the numerical variable's value. -- https://mail.python.org/mailman/listinfo/python-list
Re: Help needed with compiling python
Cecil Westerhof wrote: >On Wednesday 25 Nov 2015 23:58 CET, Laura Creighton wrote: >> >> Your Suse system probably wants to use python for something. If your >> system python is damaged, you badly need to fix that, using the >> system package managers tools, before Suse does some sort of update >> on you, using the broken python, which damages more of your system. > >I tried that. But it installs only things in /usr/lib and /usr/lib64, >nothing in /usr/bin, but at the same time it is adamant that it >installed python. I wanted a quick fix, but it looks like that is not >going to work. :'-( I'll have to find a way to get things fixed. A complete reinstall of Suse (after saving your home directory and work) might be quickest if you're in the dark about what's broken. But you might be able to fix it. If you can figure out which packages contain the damaged files, then do forced reinstalls of those. I've not used Suse, but a quick Google tells me that the syntax is: zypper in -f So you'll want to try package names like "python" and "python2.7". -- https://mail.python.org/mailman/listinfo/python-list
Re: What is a function parameter =[] for?
Alan Bawden wrote: >Chris Angelico writes: > ... >> Python 2.7.8 (2.4.0+dfsg-3, Dec 20 2014, 13:30:46) >> [PyPy 2.4.0 with GCC 4.9.2] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >> tuple([]) is tuple([]) >> False > >I said I wouldn't be suprised if it was always true, but that doesn't >imply that I need to be suprised if it is sometimes false! > >Having said that, I _am_ curious whether that remains False for various >other variant expressions. "tuple([])" is actually a rather perverse >way to obtain an empty tuple. How about plain "() is ()"? ... Still false in PyPy it seems [PyPy 2.6.1 with GCC 4.9.2] on linux2 id(()) 139836165383760L id(()) 139836165383776L (Conversely, I see that unlike CPython, all PyPy's numbers have unchanging ids, even after exiting PyPy and restarting, so it seems that PyPy's numerical ids are "faked".) [PyPy 2.6.1 with GCC 4.9.2] on linux2 id(1+2j) 679900119843984469027190799480815353863L [PyPy 2.6.1 with GCC 4.9.2] on linux2 id(1+2j) 679900119843984469027190799480815353863L -- https://mail.python.org/mailman/listinfo/python-list
Re: Is there any reason to introduce this intermediate variable (sz)?
fl wrote: >Hi, >I find the following code snippet, which is useful in my project: > ... >correctly. Could you see something useful with variable 'sz'? So that's example code in "An Introduction to the Kalman Filter" by Greg Welch and Gary Bishop, and no, that construct was unnecessary. As you've figured out, you can use the integer directly. It's the usual problem that people get when they switch from using Octave/Matlab to numpy/scipy/matplotlib. The former are better in an interactive maths-oriented environment, but people then often then switch to Python for more complex algorithms to take advantage of the features of an advanced general-purpose programming language. The problem that people then run into is that although there are equivalents in the Python libraries for most of the Matlab functions, this happens to be an area where the documentation is particularly uneven. "Pylab" is a project that attempted to be a Python equivalent of Matlab, but has now become a depreciated appendix to matplotlib. There have been attempts to restart it as a feature of Ipython, but although it mostly works, the documentation is almost nonexistent. The only way to figure out what it can do is to try it yourself with a lot of trial and error. Anyway, don't be surprised if you see unnecessary elaborations in maths/science Python code because it's what you expect when people are arriving at code that works from reading poor documentation, trial and error, and Googling other peoples code snippets. Just try it yourself and save yourself time rather than asking for hand-holding. -- https://mail.python.org/mailman/listinfo/python-list
Re: Problems using struct pack/unpack in files, and reading them.
Steven D'Aprano wrote: >On Mon, 16 Nov 2015 05:15 pm, Gregory Ewing wrote: > >> Ints are not the only thing that // can be applied to: >> >> >>> 1.0//0.01 >> 99.0 > >Good catch! Hmmm. I see that the float for 0.01 _is_ slightly larger than 0.01 >>> Decimal(0.01) Decimal('0.0120816681711721685132943093776702880859375') But it seems that 1.0 // 0.01 is not directly equivalent to: >>> int(1.0 / 0.01) 100 And I see that: >>> Decimal(1.0 / 0.01) Decimal('100') >>> floor(1.0 / 0.01) 100 >>> 0.01 * 100.0 - 1.0 0.0 So I guess that the // operator is _very_ strict in its "floor division" of floats, but that the "/" operator returns the nearest float value. -- https://mail.python.org/mailman/listinfo/python-list
Re: What is '@' for
fl wrote: >I read the following code snippet. A question is here about '@'. >I don't find the answer online yet. I recommend this: "Understanding Python Decorators in 12 Easy Steps!" http://simeonfranklin.com/blog/2012/jul/1/python-decorators-in-12-steps/ -- https://mail.python.org/mailman/listinfo/python-list
Re: don't understand matrix-multiplication should be reversed in python?
PythonDude wrote: >On Thursday, 12 November 2015 22:57:21 UTC+1, Robert Kern wrote: >> He simply instantiated the two vectors as row-vectors instead of >> column-vectors, >> which he could have easily done, so he had to flip the matrix expression. > >Thank you very much Robert - I just had to be sure about it :-) Yep, he's evidently used to the Matlab/Octave way of defining "vectors" which is somewhat easier for a math-oriented interactive environment. It's just a *bit* more laborious to append columns in numpy. >>> from numpy import * >>> v1=vstack([0,1,2]) >>> v2=vstack([3,4,5]) >>> c_[v1,v2] array([[0, 3], [1, 4], [2, 5]]) >>> append(v1,v2,axis=1) array([[0, 3], [1, 4], [2, 5]]) >>> v3=mat('4;5;6') >>> v4=mat('7;8;9') >>> c_[v3,v4] matrix([[4, 7], [5, 8], [6, 9]]) -- https://mail.python.org/mailman/listinfo/python-list
Re: Unbuffered stderr in Python 3
Random832 wrote: >The opposite of line buffering is not no buffering, but full >(i.e. block) buffering, that doesn't get flushed until it runs >out of space. TextIOWrapper has its own internal buffer, and its >design apparently doesn't contemplate the possibility of using >it with a raw FileIO object (which may mean that the posted code >isn't guaranteed to work) or disabling buffering. Hmmm. That even seems to cause trouble for sys.stderr.write (in Python3 with a non-tty e.g. a piped output): $ python2 -c 'import sys;sys.stderr.write("1\n");print("2")' 2>&1 | tee 1 2 $ python3 -c 'import sys;sys.stderr.write("1\n");print("2")' 2>&1 | tee 2 1 -- https://mail.python.org/mailman/listinfo/python-list
Re: python doesn't install
Tim Golden wrote: >I'm afraid you've been bitten by the fact that we no longer support >Windows XP and haven't communicated this very well. We have a new >version of the installer almost ready for release which indicates this >much earlier (and more obviously). I'm afraid if you're on XP you're >limited to Python 3.4 and earlier, all of which are perfectly usable I'm >happy to say! I've been reading the comments about Python and XP on this group -- and I must say that I'm thinking: Doesn't pretty much every other Windows software package tell you the minimum requirements -- because that's the first thing you'd want to know? So I've Googled for "python 3.5 minimum requirements": 1st hit: "Using Python on Windows -- Python 3.5.0 documentation" and a few paragraphs down that page there's: "Python on XP -- 7 Minutes to Hello World by Richard Dooling, 2006" which says how easy it is to install on XP. 2nd hit: "Download Python -- Python.org" There's download links but nothing about XP, but there's a link for "Information about specific ports" -- so click on "Windows" and no information actually, just more download links. 3rd hit: "Welcome to Python.org" There's download links and no info about minimum requirements. And so on down the page of Google hits. Yes, I've read the justifications. Why list all the non-supported OSs? And the explanation about each version of Python being supported just for the supported versions of Windows upon its release is in the documentation -- somewhere. But it still seems to me that stating the minimum requirements in a place that people would tend to look for it is a... minimum requirement. If the developers really are determined not to mention specific versions of Windows (If it was me, I'd have probably mentioned that the most recent version required Vista somewhere on the download page), then maybe adding the comment about matching the release date of Python to the supported versions of Windows to the download pages would give people some sort of clue as to what's going on. -- https://mail.python.org/mailman/listinfo/python-list
Re: Pyserial and Ubuntu Linux kernel 3.13.0-65-generic
Rob Gaddi wrote: >So, this is odd. I'm running Ubuntu 14.04, and my system did a kernel >upgrade from the repository from 3.13.0-63-generic to 3.13.0-65-generic. >And pyserial (2.7, installed through pip) stopped working. When KDE's "Plasma 5" appeared with Kubuntu 15.04, I found it to be too new and have too many dysfunctions, so I reverted to Kubuntu 14.04 LTS. Now this problem. Looking at the Ubuntu 14.04 repository, I found that it contained a backported version of the kernel used in 15.04. So... Remove "meta" packages that have latest 3.13 kernel as dependencies: sudo apt-get purge linux-generic linux-signed-generic Install meta packages that pull in the latest 3.19 kernel: sudo apt-get install linux-generic-lts-vivid linux-signed-generic-lts-vivid Serial now works fine. The later kernel introduces no functional changes in (K)ubuntu 14.04 that I can discern. I presume that since it is a "backported" version of the 3.19 kernel, that its video drivers have been matched to Ubuntu 14.04's version of X.Org, and so on. Anyway, that's what works for me. I could've put a "hold" on the 3.13.0-63 kernel, but this seems a better fix. -- https://mail.python.org/mailman/listinfo/python-list
Re: matplotlib timer
Laura Creighton wrote: >In a message of Thu, 01 Oct 2015 20:03:26 +0100, Dave Farrance writes: >>Laura Creighton wrote: >> >>>In a message of Thu, 01 Oct 2015 18:45:06 +0100, Dave Farrance writes: >>>>Yet the documentation says that it's mandatory for the GUI backend base >>>>to implement stop() but that single_shot is optional. Ho hum. >>> >>>report as a bug. its a doc bug at least, but I think its a real bug, >>>and your code should have worked. >>> >>>https://github.com/matplotlib/matplotlib/issues >> >>OK, done. >> > >Thank you. > >Can you add how you got it to work, and the doc you read >that seems wrong? OK. -- https://mail.python.org/mailman/listinfo/python-list
Re: matplotlib timer
Laura Creighton wrote: >In a message of Thu, 01 Oct 2015 18:45:06 +0100, Dave Farrance writes: >>Yet the documentation says that it's mandatory for the GUI backend base >>to implement stop() but that single_shot is optional. Ho hum. > >report as a bug. its a doc bug at least, but I think its a real bug, >and your code should have worked. > >https://github.com/matplotlib/matplotlib/issues OK, done. https://github.com/matplotlib/matplotlib/issues/5163 -- https://mail.python.org/mailman/listinfo/python-list
Re: matplotlib timer
Laura Creighton wrote: >In a message of Thu, 01 Oct 2015 17:36:50 +0100, Dave Farrance writes: >>I'm trying to set up the basics of a timer-scheduled function in >>matplotlib and I can't figure out how to stop the timer. Maybe the >>stop() method is dysfunctional in Ubuntu 14.04 or maybe I'm getting the >>syntax wrong. >> >>If anybody's got matplotlib installed, can you try this code and tell me >>if it stops after one tick as it should -- or does it continue printing >>every second without stopping as mine does? >> >>#!/usr/bin/env python >>import matplotlib.pyplot as P >>def fn(): >> timer.stop() >> print("tick") >>fig, ax = P.subplots() >>timer = fig.canvas.new_timer(interval=1000) >>timer.add_callback(fn) >>timer.start() >>P.show() >> > >debian unstable >Python 3.4.3+ (default, Jul 28 2015, 13:17:50) > >mine ticks forever, too. Thanks. I've just figured out how to stop the timer. replace "timer.stop()" with timer.single_shot = True Yet the documentation says that it's mandatory for the GUI backend base to implement stop() but that single_shot is optional. Ho hum. http://matplotlib.org/api/backend_bases_api.html#matplotlib.backend_bases.TimerBase -- https://mail.python.org/mailman/listinfo/python-list
matplotlib timer
I'm trying to set up the basics of a timer-scheduled function in matplotlib and I can't figure out how to stop the timer. Maybe the stop() method is dysfunctional in Ubuntu 14.04 or maybe I'm getting the syntax wrong. If anybody's got matplotlib installed, can you try this code and tell me if it stops after one tick as it should -- or does it continue printing every second without stopping as mine does? #!/usr/bin/env python import matplotlib.pyplot as P def fn(): timer.stop() print("tick") fig, ax = P.subplots() timer = fig.canvas.new_timer(interval=1000) timer.add_callback(fn) timer.start() P.show() -- https://mail.python.org/mailman/listinfo/python-list
Re: pygame basic question
"ast" wrote: >DISPLAYSURF = pygame.display.set_mode((400, 300)) >pygame.display.set_caption('Hello World!') > >The first line opens a 400x300 pygame window. >The second one writes "Hello World" on top of it. > >I am just wondering how function set_caption finds the windows >since the window's name DISPLAYSURF is not passed as >an argument https://www.pygame.org/docs/ref/display.html As it says, there is only *one* display surface, and any non-displayed surface must be blitted (copied) onto the display surface for visibility. So all "pygame.display" methods refer to that one display surface. Non displayed surfaces, on the other hand, do need to be instantiated with "pygame.Surface" -- https://mail.python.org/mailman/listinfo/python-list
Re: "no module named kivy" import error in ubuntu 14.04
shiva upreti wrote: >Hi >I am new to linux. I tried various things in attempt to install kivy. I >installed python 2.7.10 Just to make clear what others have said -- replacing Ubuntu 14.04's system Python 2.7.6 is a bad idea and will break stuff, so if you really must have the latest version of Python2, then you install it separately, leaving the system Python in place. That in turn means that you can no longer use Ubuntu's normal method of installing libraries via its own software management. > Then i downloaded kivy from > https://pypi.python.org/packages/source/K/Kivy/Kivy-1.9.0.tar.gz I suggest that you DON'T install from tarfiles unless your understanding of Python is of near python-developer level. You really need to know what you're doing regarding dependencies and the search path for modules. If you do want to install a separate instance of the latest version of Python, then the PIP package management is best, and use it to install the libraries separately, NOT in the /usr/ directory -- see the other posts. -- https://mail.python.org/mailman/listinfo/python-list
Re: I'm a newbie and I'm still stumped...
Dwight GoldWinde wrote: >Here are the results I got below, showing the same error. The first line >says, >"2.7.6 (default, Sep 9 2014, 15:04:36)”. Does that mean I am running the >old Python? How could that be since I am SURE I downloaded 3.4.3 (it even >gives the folder name as “Python 3.4” in the Applications folder on my Mac. Yes, that's Python2. I've never used MAC OS, but I understand that it has the BASH shell, so you can use "which" try to figure out where python is being found on the path: $ echo $PATH $ which python Use the above to also check for the position of python2 and python3. You can check for aliases and links with the "type" and "file" commands. Do this for python, python2 and python3: $ type $(which python) $ file $(which python) -- https://mail.python.org/mailman/listinfo/python-list
Re: How to Calculate NPV?
ryguy7272 wrote: >PERFECT!! SO SIMPLE!! >I don't know why the author didn't do that in the book. The book is evidently giving you code snippets to enter into Python's own interactive interpreter, i.e., you enter "python" at the command line, then you manually type each command which immediately displays any returned value. I assume that the book shows each command with three chevrons ">>>" in front of them. If you're using Spyder then you need to enter the commands into its interactive interpreter (which I think is bottom right). It sounds, instead, as though you're using Spyder's text editor to create a file containing the commands, and then using the "run" icon to run the file -- which is maybe skipping ahead because the book hasn't told you how to do that yet (?). If you do skip ahead, the book probably has a forthcoming chapter called "writing programs with a text editor" or something. I'd guess from the code snippets that you've shown us that the book is finance oriented, and the author seems to be more interested in introducing the features useful for finance than teaching the basics of Python. Maybe you should search out a simple Python primer on the web, work through that, and only then return to your book. -- https://mail.python.org/mailman/listinfo/python-list