Re: [Tutor] Union
On 8/12/19 4:12 PM, Mats Wichmann wrote: On 8/12/19 2:50 PM, Jim wrote: I was reading the docs for PySimpbleGUI here: https://pysimplegui.readthedocs.io/en/latest/#building-custom-windows In the table of parameters for the Window() function for example the icon parameter the meaning is Union[str, str] Can be either a filename or Base64 value. What is the usage of "Union". I don't recall seeing anything like it before. it's type annotation. Search here: https://docs.python.org/3/library/typing.html OK, thanks. Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Union
I was reading the docs for PySimpbleGUI here: https://pysimplegui.readthedocs.io/en/latest/#building-custom-windows In the table of parameters for the Window() function for example the icon parameter the meaning is Union[str, str] Can be either a filename or Base64 value. What is the usage of "Union". I don't recall seeing anything like it before. Thanks, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Impersonation
On 7/15/19 9:36 PM, Jim wrote: Mats, Hopefully you recognize my email address as someone you have given advice concerning Python. Over the last month or so I have received at least 3 emails supposedly coming from you that I am sure you did not send. The from line is: Mats Wichmann The body is: On Monday, July 15, 2019 10:36 AM, Mats Wichmann wrote: Hope you are well. Just wanted to share something with you http://www.bt6q.lnhaxf.info/ I just wanted you to know that it seems someone is trying to impersonate you. Regards, Jim My apologies. I intended that this message go only to Mats. Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Impersonation
Mats, Hopefully you recognize my email address as someone you have given advice concerning Python. Over the last month or so I have received at least 3 emails supposedly coming from you that I am sure you did not send. The from line is: Mats Wichmann The body is: On Monday, July 15, 2019 10:36 AM, Mats Wichmann wrote: Hope you are well. Just wanted to share something with you http://www.bt6q.lnhaxf.info/ I just wanted you to know that it seems someone is trying to impersonate you. Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Consequences of removing python3-venv
My Linux mint18 system recently wanted to up date python 3.6. When I clicked install I got the following message: The following 2 packages will be removed: python3-dev python3-venv I have 2 virtual environments installed: python 3.5.2 & 3.6.7. Listing the various pythons I have installed shows: jfb@jims-mint18 ~ $ ls -ls /usr/bin/python* 0 lrwxrwxrwx 1 root root 9 Nov 23 2017 /usr/bin/python -> python2.7 0 lrwxrwxrwx 1 root root 9 Nov 23 2017 /usr/bin/python2 -> python2.7 3412 -rwxr-xr-x 1 root root 3492656 Nov 12 13:46 /usr/bin/python2.7 0 lrwxrwxrwx 1 root root 9 Jan 9 2017 /usr/bin/python3 -> python3.5 4360 -rwxr-xr-x 2 root root 4464368 Nov 12 10:27 /usr/bin/python3.5 0 lrwxrwxrwx 1 root root 33 Nov 12 10:27 /usr/bin/python3.5-config -> x86_64-linux-gnu-python3.5-config 4360 -rwxr-xr-x 2 root root 4464368 Nov 12 10:27 /usr/bin/python3.5m 0 lrwxrwxrwx 1 root root 34 Nov 12 10:27 /usr/bin/python3.5m-config -> x86_64-linux-gnu-python3.5m-config 4500 -rwxr-xr-x 2 root root 4604416 Oct 25 2018 /usr/bin/python3.6 0 lrwxrwxrwx 1 root root 33 Oct 25 2018 /usr/bin/python3.6-config -> x86_64-linux-gnu-python3.6-config 4500 -rwxr-xr-x 2 root root 4604416 Oct 25 2018 /usr/bin/python3.6m 0 lrwxrwxrwx 1 root root 34 Oct 25 2018 /usr/bin/python3.6m-config -> x86_64-linux-gnu-python3.6m-config 0 lrwxrwxrwx 1 root root 16 Mar 23 2016 /usr/bin/python3-config -> python3.5-config 0 lrwxrwxrwx 1 root root 10 Jan 9 2017 /usr/bin/python3m -> python3.5m 0 lrwxrwxrwx 1 root root 17 Mar 23 2016 /usr/bin/python3m-config -> python3.5m-config So will allowing the update harm my virtual environments? I really don't want to reinstall them. thanks, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python 3.6 update?
On 10/25/18 5:30 PM, Mats Wichmann wrote: On 10/25/2018 03:07 PM, Jim wrote: Mint 18.1 Default python3 = 3.5 Python 3.6 installed for use by a virtual environment. Update manager just informed me of an update for python 3.6 to 3.6.7-1. When I started to install it, I got a dialog saying: this upgrade will trigger additional changes. The following 2 packages will be removed python3-dev & python3-venv. I am wondering what will happen to the virtual environment I have installed that uses python 3.6. Will the 2 packages be replaced and the virtual environment continue to work or is there some other steps I will need to take. Regards, Jim we can't tell that from here. Not sure whose bright idea it was to package venv separately, since it's supposed to be a "standard" part of Python 3 since 3.3 (I guess it's "batteries included, but you still have to install the batteries" :). But removing the package doesn't affect a created virtual environment. What can affect a created virtual environment is how it was created - there are a few options, some combinations of which could leave things going missing from underneath if the Python it's created from is upgraded. venv has an upgrade option that might help with that. Mint forums (and probably Ubuntu forums) could be further help... usually somebody's been through it before. Asked on ubuntu forumn. thanks, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Python 3.6 update?
Mint 18.1 Default python3 = 3.5 Python 3.6 installed for use by a virtual environment. Update manager just informed me of an update for python 3.6 to 3.6.7-1. When I started to install it, I got a dialog saying: this upgrade will trigger additional changes. The following 2 packages will be removed python3-dev & python3-venv. I am wondering what will happen to the virtual environment I have installed that uses python 3.6. Will the 2 packages be replaced and the virtual environment continue to work or is there some other steps I will need to take. Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] No module named uno in virtual environment
On 09/09/2018 01:29 PM, Mats Wichmann wrote: On 09/09/2018 10:49 AM, Jim wrote: ok, awkward naming issue. try openoffice-python instead? Unfortunately it produces the same result, no module uno found. I think all of the packages on pipy need the uno module to be installed to function. When I installed python3-uno using apt it was installed at /usr/lib/python3/dist-packages/uno.py. I have python 3.5 installed in a virtual environment and it can load the uno module. I have python 3.6 installed in virtual environment and it cannot load the uno module. Ok, I think I have solved it. Looking at the site-packages folder in the 3.5 virtual environment shows uno.py and unohelper.py. In the 3.6 virtual environment they are missing. Simply putting a copy of them in the python3.6 site-packages folder allows me to import uno and run a program that depends on importing uno. I don't know if they should have been put there when I installed the 3.6 virtual environment or if I did something wrong when I installed it, but now it works. Mats, thanks for all your help. Glad it works, but you've left me curious now. On a Fedora system these two files come from libreoffice-pyuno: /usr/lib64/python3.6/site-packages/uno.py /usr/lib64/python3.6/site-packages/unohelper.py and I don't presently see any way they are going to make it into a virtualenv that is *not* set up to grab the system site-packages (that is, created with the --system-site-packages option), I'm not finding anything in PyPi that looks like it can provide this. The package I mentioned above certainly doesn't. uno.py imports the binary (shared object) pyuno module, which is fine, that one is located wherever the {open,libre}office install puts it - on my system just before the import it has done: sys.path.append('/usr/lib64/libreoffice/program') maybe your 3.5 virtualenv was created differently than your 3.6 one and that's why you have it there? meanwhile, this is looking to my untrained eye like a small hole. I am puzzled also. My memory isn't what it used to be but I think I created them the same way. Looking at the config files I see. home = /usr/bin include-system-site-packages = false version = 3.5.2 and home = /usr/bin include-system-site-packages = false version = 3.6.3 I don't know if it makes a difference or not, but python3.5 is the system default python3 and python3.6 was installed from LP-PPA-jonathonf-python-3.6/now and LP_PPA-jonathonf-python-3.6/xenial. Maybe the install script malfunctioned or was lacking some step. I may email jonathon to see if he has any ideas. Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] No module named uno in virtual environment
On 09/08/2018 08:35 PM, Mats Wichmann wrote: On September 8, 2018 5:46:46 PM MDT, Jim wrote: On 09/08/2018 05:26 PM, Mats Wichmann wrote: On 09/07/2018 03:10 PM, Jim wrote: Mint 18.1 System python3 3.5.2 Python3-uno is available to the system python3. How can I make it available to python 3.6.5 in a virtual environment I installed using venv? with your virtualenv activated, just install it. python -m pip install uno My bad, I did not explain what python3-uno does. It is a system package that lets python interact with libreoffice. The uno that pip installs is a html generator. I used apt to install python3-uno on my system. System python3 can use it and the python 3.5 in one of my virtual environments can use it. Python 3.6 in my other virtual environment cannot access it. So to re-phrase my question. Python3-uno is installed on my system what do I need to do to get python 3.6 in a virtual environment to use it? Maybe I am missing something obvious. With all the advice given to use virtual environments I would think that this problem has come up, but googling did not produce a solution. Regards, Jim python ok, awkward naming issue. try openoffice-python instead? Unfortunately it produces the same result, no module uno found. I think all of the packages on pipy need the uno module to be installed to function. When I installed python3-uno using apt it was installed at /usr/lib/python3/dist-packages/uno.py. I have python 3.5 installed in a virtual environment and it can load the uno module. I have python 3.6 installed in virtual environment and it cannot load the uno module. Ok, I think I have solved it. Looking at the site-packages folder in the 3.5 virtual environment shows uno.py and unohelper.py. In the 3.6 virtual environment they are missing. Simply putting a copy of them in the python3.6 site-packages folder allows me to import uno and run a program that depends on importing uno. I don't know if they should have been put there when I installed the 3.6 virtual environment or if I did something wrong when I installed it, but now it works. Mats, thanks for all your help. Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] No module named uno in virtual environment
On 09/08/2018 05:26 PM, Mats Wichmann wrote: On 09/07/2018 03:10 PM, Jim wrote: Mint 18.1 System python3 3.5.2 Python3-uno is available to the system python3. How can I make it available to python 3.6.5 in a virtual environment I installed using venv? with your virtualenv activated, just install it. python -m pip install uno My bad, I did not explain what python3-uno does. It is a system package that lets python interact with libreoffice. The uno that pip installs is a html generator. I used apt to install python3-uno on my system. System python3 can use it and the python 3.5 in one of my virtual environments can use it. Python 3.6 in my other virtual environment cannot access it. So to re-phrase my question. Python3-uno is installed on my system what do I need to do to get python 3.6 in a virtual environment to use it? Maybe I am missing something obvious. With all the advice given to use virtual environments I would think that this problem has come up, but googling did not produce a solution. Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] No module named uno in virtual environment
Mint 18.1 System python3 3.5.2 Python3-uno is available to the system python3. How can I make it available to python 3.6.5 in a virtual environment I installed using venv? (env36) jfb@jims-mint18 ~ $ python Python 3.6.5 (default, May 3 2018, 10:08:28) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import oosheet Traceback (most recent call last): File "", line 1, in File "/home/jfb/EVs/env36/lib/python3.6/site-packages/oosheet/__init__.py", line 38, in import uno, re, zipfile, types, inspect, tempfile, shutil, subprocess ModuleNotFoundError: No module named 'uno' Thanks, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How can I find a group of characters in a list of strings?
On 07/25/2018 07:29 PM, Martin A. Brown wrote: I have a list of strings that contains slightly more than a million items. Each item is a string of 8 capital letters like so: ['MIBMMCCO', 'YOWHHOY', ...] I need to check and see if the letters 'OFHCMLIP' are one of the items in the list but there is no way to tell in what order the letters will appear. So I can't just search for the string 'OFHCMLIP'. I just need to locate any strings that are made up of those letters no matter their order. I suppose I could loop over the list and loop over each item using a bunch of if statements exiting the inner loop as soon as I find a letter is not in the string, but there must be a better way. I'd appreciate hearing about a better way to attack this. thanks, Jim If I only had to do this once, over only a million items (given today's CPU power), so I'd probably do something like the below using sets. I couldn't tell from your text whether you wanted to see all of the entries in 'OFHCMLIP' in each entry or if you wanted to see only that some subset were present. So, here's a script that will produce a partial match and exact match. Note, I made a 9-character string, too because you had a 7-character string as your second sample -- mostly to point out that the 9-character string satisfies an exact match although it sports an extra character. Sorry, that was a typo, they are all 8 characters in length. farm = ['MIBMMCCO', 'YOWHHOY', 'OFHCMLIP', 'OFHCMLIPZ', 'FHCMLIP', 'NEGBQJKR'] needle = set('OFHCMLIP') for haystack in farm: partial = needle.intersection(haystack) exact = needle.intersection(haystack) == needle print(haystack, exact, ''.join(sorted(partial))) On the other hand, there are probably lots of papers on how to do this much more efficiently. -Martin Thanks for your help. Steven came up with a solution that works well for me. Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How can I find a group of characters in a list of strings?
On 07/25/2018 07:43 PM, Steven D'Aprano wrote: On Wed, Jul 25, 2018 at 06:50:56PM -0500, Jim wrote: [...] I need to check and see if the letters 'OFHCMLIP' are one of the items in the list but there is no way to tell in what order the letters will appear. So I can't just search for the string 'OFHCMLIP'. I just need to locate any strings that are made up of those letters no matter their order. data = ['MIBMMCCO', 'YOWHHOY', 'ABCDEFG', 'HCMLIPOF', 'TUVWXYZ'] target = sorted('OFHCMLIP') for pos, item in enumerate(data): if sorted(item) == target: print("found", pos, item) break Stephen, Perfect, thank you. I did remove the break because I thought I would get more than one hit. I got 196, more that I hoped for but now I have a better idea of what I am working with. Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] How can I find a group of characters in a list of strings?
Linux mint 18 and python 3.6 I have a list of strings that contains slightly more than a million items. Each item is a string of 8 capital letters like so: ['MIBMMCCO', 'YOWHHOY', ...] I need to check and see if the letters 'OFHCMLIP' are one of the items in the list but there is no way to tell in what order the letters will appear. So I can't just search for the string 'OFHCMLIP'. I just need to locate any strings that are made up of those letters no matter their order. I suppose I could loop over the list and loop over each item using a bunch of if statements exiting the inner loop as soon as I find a letter is not in the string, but there must be a better way. I'd appreciate hearing about a better way to attack this. thanks, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Wish to upgrade Python 3.6.5 to Python 3.6.6 for Linux Mint 19
On 07/14/2018 06:42 PM, Alan Gauld via Tutor wrote: On 14/07/18 22:51, boB Stepp wrote: Linux Mint 19 comes with Python 3.6.5 pre-installed. However, my son and I are working on a couple of things together, and decided to use the latest bugfix releases of Python 3.6 for them. I would not think that upgrading from 3.6.5 to 3.6.6 would break anything in my system Probably not but do you really need that last dot release? Do you know for sure there is anything in it that will affect your code? If not I'd just stay on 3.6.5 Personally, although I have 3.6.5 installed, my default v3 is 3.5.4. If you really need 3.6.6 then your best bet is to locate a deb package that somebody has created, otherwise building from source is about the only option. Bob, If you look you might find a PPA that has packaged it. I installed python 3.6.5 (no help to you) on Mint 18 from here: https://launchpad.net/~jonathonf/+archive/ubuntu/python-3.6'. Maybe you can find one that does 3.6.6 or ask Jonathon if he intends to package 3.6.6. Whatever you do I would suggest you install it in a virtual environment, especially if you are going to be experimenting with a lot of libraries. If you use a virtual environment you don't have to worry about breaking your system python. regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Need help combining elements of a list of lists
On 07/10/2018 11:03 PM, Mats Wichmann wrote: On 07/10/2018 09:09 PM, Steven D'Aprano wrote: On Tue, Jul 10, 2018 at 09:46:57PM -0500, Jim wrote: Say I have a list like ltrs and I want to print out all the possible 3 letter combinations. I want to combine letters from each inner list but not combine any letters within the inner list itself. So ACF and ADF would be ok but ABC would not. I can lay it out manually and see the pattern, I cannot figure out how to do it programically. Just in case this looks like homework it is not. It's a small test case I devised to try to figure it out so I can apply it to a bigger real world problem I am working on. ltrs = [['A', 'B'], ['C', 'D', 'E'], ['F', 'G', 'H', 'I']] If you know that there are just three sublists, then you can do this: for a in ltrs[0]: for b in ltrs[1]: for c in ltrs[2]: print(a + b + c) I trust that's easy enough to understand. But here's a more general technique, where you don't need to know up front how many nested lists there are: from itertools import product # short for "Cartesian Product" for s in product(*ltrs): print(''.join(s)) This is one of those cases where: if it's homework, getting the nested loops right is almost certainly the way to go. If it isn't, then itertools (that is, "using an available library solution") is almost certainly the way to go :) If the eventual case is not just "letters", and a list of combined lists is the eventual goal, then the concise stanza is: prods = list(product(*ltrs)) print(prods) then gives you: [('a', 'c', 'f'), ('a', 'c', 'g'), ('a', 'c', 'h'), ('a', 'c', 'i'), ('a', 'd', 'f'), ('a', 'd', 'g'), ('a', 'd', 'h'), ('a', 'd', 'i'), ('a', 'e', 'f'), ('a', 'e', 'g'), ('a', 'e', 'h'), ('a', 'e', 'i'), ('b', 'c', 'f'), ('b', 'c', 'g'), ('b', 'c', 'h'), ('b', 'c', 'i'), ('b', 'd', 'f'), ('b', 'd', 'g'), ('b', 'd', 'h'), ('b', 'd', 'i'), ('b', 'e', 'f'), ('b', 'e', 'g'), ('b', 'e', 'h'), ('b', 'e', 'i')] if you want them concatenated, then of course join is the way to do that. Steven & Mats thanks for your replies. It is more that just letters. I was reading Al Sweigart's book Cracking Codes with Python. I got to the chapter on substitution cyphers and wondered if his program could solve the daily Crypto Quips in the newspaper. Turns out it did not do a very good job because the quips were to short. It did produce a dictionary where the keys are the letters of the alphabet and the items are a list of possible letters to substitute. If a key has no possible letters it is ignored, if a key has only one possible letter it considered a solution and plugged into the cypher. the keys with multiple possible letters are ones I am interested in. I know you cannot brute force a substitution cypher but maybe I could loop over and combine the possible substitution letters and crack it that way. That's why I made up the letter problem, I wanted to see how to do it on a simple data set before attempting much more complex one. It looks like the library solution is the way for me to try. Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Need help combining elements of a list of lists
On 07/10/2018 10:09 PM, David Rock wrote: On Jul 10, 2018, at 22:04, David Rock wrote: On Jul 10, 2018, at 21:46, Jim wrote: ltrs = [['A', 'B'], ['C', 'D', 'E'], ['F', 'G', 'H', 'I']] A fairly straightforward way is to use nested loops: for l in ltrs[0]: ... for j in ltrs[1]: ... for k in ltrs[2]: ... print l,j,k Sorry, let’s try to make that a little cleaner-looking for x in ltrs[0]: for y in ltrs[1]: for z in ltrs[2]: print x,y,z Seeing it in front of me it does look straight forward, I was having difficulty visualizing how to solve it. thanks, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Need help combining elements of a list of lists
Say I have a list like ltrs and I want to print out all the possible 3 letter combinations. I want to combine letters from each inner list but not combine any letters within the inner list itself. So ACF and ADF would be ok but ABC would not. I can lay it out manually and see the pattern, I cannot figure out how to do it programically. Just in case this looks like homework it is not. It's a small test case I devised to try to figure it out so I can apply it to a bigger real world problem I am working on. ltrs = [['A', 'B'], ['C', 'D', 'E'], ['F', 'G', 'H', 'I']] print(ltrs[0][0]+ltrs[1][0]+ltrs[2][0]) #ACF print(ltrs[0][0]+ltrs[1][1]+ltrs[2][0]) #ADF print(ltrs[0][0]+ltrs[1][2]+ltrs[2][0]) #AEF print(ltrs[0][0]+ltrs[1][0]+ltrs[2][1]) #ACG print(ltrs[0][0]+ltrs[1][1]+ltrs[2][1]) #ADG print(ltrs[0][0]+ltrs[1][2]+ltrs[2][1]) #AEG . . . print(ltrs[0][1]+ltrs[1][2]+ltrs[2][3]) #BEI thanks, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Using pip
On 07/05/2018 11:03 AM, Hlavin, Matthew (GSFC-5460)[GSFC INTERNS] wrote: I just downloaded Python to work on a project at work. I'm writing a pretty simple program for data collection for an experiment. In order to get the data, though I need to install PyVISA. The website for PyVISA says I can install the library using the line: $ pip install -U pyvisa When I type this line, I get a syntax error for using the $, and when I remove the $, I get a syntax error for using the word install. I even tried just using the word pip and an error said 'pip' is not defined. I'm not sure if I'm not using some syntax wrong, or if its a completely different issue. Thanks for any help and insight Matt Hlavin It sounds like you are trying to install it from inside python. First make sure that pip is installed on your OS. Then install PyVISA from your commandline/terminal (which ever your OS provides). Also depending on which version of python you are using (2 or 3) you may have to type pip3 instead of just pip. regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Virtual environment can't find uno
On 06/14/2018 10:51 AM, Mats Wichmann wrote: On 06/13/2018 06:55 PM, Jim wrote: Running Linux Mint 18. I have python 3.6 running in a virtual environment. I want to use a package called oosheet to work with libreoffice calc. When I try to import it I get the following error: import oosheet Traceback (most recent call last): File "", line 1, in File "/home/jfb/EVs/env36/lib/python3.6/site-packages/oosheet/__init__.py", line 38, in import uno, re, zipfile, types, inspect, tempfile, shutil, subprocess ModuleNotFoundError: No module named 'uno' If I do the same thing in the system installed python3 it imports and runs with no errors. python3-uno was installed using apt-get. How do I get python 3.6 in the virtual environment to find uno? You should be able to pip install uno in the virtualenv, which might be best. After all, once you're using a virtualenv, you've already started down the road of picking depends from upstream, so why not :) Is it available for a pip install? I looked on pypi and didn't see it. It may be incompatible with 3.6. I was looking at the dependencies with synaptic and found. Depends Python3(>= 3.5~), Depends Python3(<= 3.6). Anyway I had forgotten I have a virtual environment with 3.5 in it, so I tried that and it works. Thanks, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Virtual environment can't find uno
Running Linux Mint 18. I have python 3.6 running in a virtual environment. I want to use a package called oosheet to work with libreoffice calc. When I try to import it I get the following error: >>> import oosheet Traceback (most recent call last): File "", line 1, in File "/home/jfb/EVs/env36/lib/python3.6/site-packages/oosheet/__init__.py", line 38, in import uno, re, zipfile, types, inspect, tempfile, shutil, subprocess ModuleNotFoundError: No module named 'uno' If I do the same thing in the system installed python3 it imports and runs with no errors. python3-uno was installed using apt-get. How do I get python 3.6 in the virtual environment to find uno? Thanks, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Need help with a virtual environment mess
On 05/07/2018 12:02 PM, Mats Wichmann wrote: On 05/07/2018 10:16 AM, Jim wrote: My understanding of VE's, based on some feedback from here, is you install install the python you want on the system then use it to install your VE. Then you install what ever you need to the VE. In my case I had a working VE based on python 3.5 then I received an upgrade to the python version 3.6 I had installed. After that I had problems with the 3.5 VE that had been working. yes, this happens. the default behavior for virtualenv is to make links when creating the VE, which saves copying things but is vulnerable to breakage if the Python it's linking to receives major changes. In the case of a distribution upgrading the Python version, a VE constructed against the old version will break if the links are version-specific. Looking at one virtualenv I have, {VEPATH}/lib/python3.6 is full of such symlinks, e.g.: lrwxrwxrwx. 1 mats mats26 Aug 17 2017 re.py -> /usr/lib64/python3.6/re.py Virtualenvs are cheap to recreate, so one approach is to just throw away the old one and make a new one. My problem is right now the default python3 for my system is also affected. If I type python3 I will see python version 3.5.2 and I cannot import tkinter there either. you can also give virtualenv an option (--always-copy) to cause the created virtualenv to be more self-contained, at a cost of some space and tiem. There are plenty of tools for managing python versions and virtualenv. The python community changed directions a little bit recently, 'venv' is now the recommended approach: https://docs.python.org/3/library/venv.html That is what I used to setup my VE's. pyenv can manage different Python versions if you're interested in that. I am going to see if I can find some log file that would give me a clue about what happened during the update. Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Need help with a virtual environment mess
On 05/06/2018 05:16 PM, boB Stepp wrote: On Sun, May 6, 2018 at 11:05 AM, Jim wrote: In a prior thread you guys helped me fix a problem with pip after I upgraded an installed version of python 3.6 on my Mint 18 system. Pip would not run in my python 3.6 virtual environment. The fix was to use synaptic to install python3-distutils. I thought everything was ok until I tried to run a old script from a different VE using python 3.5 which could not import tkinter. I have 4 versions of python on this system: system Python2 = 2.7.12 (default) system Python3 = 3.5.2 (default) a VE called env = 3.5.2 a Ve called env36 = 3.6.5 This is the error I get trying to import tkinter in env, I also get the same error if I try to import it in system python3. jfb@jims-mint18 ~ $ source /home/jfb/EVs/env/bin/activate (env) jfb@jims-mint18 ~ $ python Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. import tkinter as tk Traceback (most recent call last): File "/usr/lib/python3.5/tkinter/__init__.py", line 36, in import _tkinter ImportError: No module named '_tkinter' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "", line 1, in File "/usr/lib/python3.5/tkinter/__init__.py", line 38, in raise ImportError(str(msg) + ', please install the python3-tk package') ImportError: No module named '_tkinter', please install the python3-tk package If I go to synaptic and install the python3-tk it installs version 3.6.5 of the package and I can still not import tkinter in env with python 3.5.2, but I can in env36 with python 3.6.5. As I have not yet tried to play around with virtual environments, I may be about to do more harm than help, but I will plow ahead anyway! ~(:>)) My primitive understanding of installing Python versions that are different from the system Python version into a virtual environment, is that you have to install all dependencies you need from within that virtual environment you created. If I am correct about this then your error messages suggest you need to install the tkinter stuff from within that virtual environment using that virtual environment's pip. Hopefully I am too far off from the truth here, but in any event, I hope this helps you in your problem! My understanding of VE's, based on some feedback from here, is you install install the python you want on the system then use it to install your VE. Then you install what ever you need to the VE. In my case I had a working VE based on python 3.5 then I received an upgrade to the python version 3.6 I had installed. After that I had problems with the 3.5 VE that had been working. Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Need help with a virtual environment mess
In a prior thread you guys helped me fix a problem with pip after I upgraded an installed version of python 3.6 on my Mint 18 system. Pip would not run in my python 3.6 virtual environment. The fix was to use synaptic to install python3-distutils. I thought everything was ok until I tried to run a old script from a different VE using python 3.5 which could not import tkinter. I have 4 versions of python on this system: system Python2 = 2.7.12 (default) system Python3 = 3.5.2 (default) a VE called env = 3.5.2 a Ve called env36 = 3.6.5 This is the error I get trying to import tkinter in env, I also get the same error if I try to import it in system python3. jfb@jims-mint18 ~ $ source /home/jfb/EVs/env/bin/activate (env) jfb@jims-mint18 ~ $ python Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import tkinter as tk Traceback (most recent call last): File "/usr/lib/python3.5/tkinter/__init__.py", line 36, in import _tkinter ImportError: No module named '_tkinter' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "", line 1, in File "/usr/lib/python3.5/tkinter/__init__.py", line 38, in raise ImportError(str(msg) + ', please install the python3-tk package') ImportError: No module named '_tkinter', please install the python3-tk package >>> If I go to synaptic and install the python3-tk it installs version 3.6.5 of the package and I can still not import tkinter in env with python 3.5.2, but I can in env36 with python 3.6.5. I don't know if it makes a difference but I installed python3.6 from LP-PPA-jonathonf-python-3.6/now. Thanks, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] pip stopped working gives error
On 05/03/2018 03:48 PM, Mats Wichmann wrote: On 05/03/2018 02:27 PM, Jim wrote: I heard distutils may have been split out... see if you have a package python3-distutils and if not installed, can you install it? I have: //usr/lib/python3.5/distutils and //usr/lib/python3.6/distutils, but no python3-distutils. Checking in Synaptic there is no python3-distutils but there is a python3-distutils-extra. it was a guess... this change seems to have just happened in Ubuntu (bionic/18.04 only), perhaps that's not the thing affecting you in Mint (yet). $ dpkg -l python3-distutils Desired=Unknown/Install/Remove/Purge/Hold | Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend |/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad) ||/ Name Version ArchitectureDescription +++--===-===-= ii python3-distutils3.6.5-3 all distutils package for Python 3.x $ dpkg -L python3 | grep sysconfig $ dpkg -L python3-distutils | grep sysconfig /usr/lib/python3.6/distutils/sysconfig.py /usr/lib/python3.7/distutils/sysconfig.py $ I don't know if I missed it or a late update pulled it in but I just did sudo apt install python3-distutils and now my problem is fixed. Thanks to you and Zachary for helping me out. Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] pip stopped working gives error
On 05/03/2018 03:40 PM, Zachary Ware wrote: On Thu, May 3, 2018 at 2:10 PM, Jim wrote: I have python 3.6 installed in a virtual environment on Mint 18. Today I wanted to use pip and got this error when I tried to use it. (env36) jfb@jims-mint18 ~ $ pip help Traceback (most recent call last): File "/home/jfb/EVs/env36/bin/pip", line 7, in from pip import main File "/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/__init__.py", line 43, in from pip.utils import get_installed_distributions, get_prog File "/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/utils/__init__.py", line 23, in from pip.locations import ( File "/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/locations.py", line 9, in from distutils import sysconfig ImportError: cannot import name 'sysconfig' I searched for sysconfig and found this: /home/jfb/EVs/env36/lib/python3.6/site-packages/pip/_vendor/distlib/_backport/__pycache__/sysconfig.cpython-36.pyc /home/jfb/EVs/env36/lib/python3.6/site-packages/pip/_vendor/distlib/_backport/sysconfig.cfg /home/jfb/EVs/env36/lib/python3.6/site-packages/pip/_vendor/distlib/_backport/sysconfig.py The results seem to be the same as when I searched a python 3.5 virtual environment I have setup. It has worked in the past as I have installed pylint and pykeyboard with it. As I type this I just remembered Mint updated python 3.6 earlier today. So now I suspect the update is involved. Has anyone else experienced this and know how to fix it? First, try a clean venv (python3.6 -m venv venv && ./venv/bin/pip help). Ok, I just tried this and got this error. jfb@jims-mint18 ~ $ python3.6 -m venv /home/jfb/EVs/env365 && ./venv/bin/pip help The virtual environment was not created successfully because ensurepip is not available. On Debian/Ubuntu systems, you need to install the python3-venv package using the following command. apt-get install python3-venv You may need to use sudo with that command. After installing the python3-venv package, recreate your virtual environment. Failing command: ['/home/jfb/EVs/env365/bin/python3.6', '-Im', 'ensurepip', '--upgrade', '--default-pip'] Couple of things troubling about this message. I just checked and python3-venv is installed, in fact I used it to install the python3.6 environment I'm having problems with. I did a search and ensurepip is on my system at //usr/lib/python3.6/ensurepip. Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] pip stopped working gives error
On 05/03/2018 02:42 PM, Mats Wichmann wrote: On 05/03/2018 01:10 PM, Jim wrote: I have python 3.6 installed in a virtual environment on Mint 18. Today I wanted to use pip and got this error when I tried to use it. (env36) jfb@jims-mint18 ~ $ pip help Traceback (most recent call last): File "/home/jfb/EVs/env36/bin/pip", line 7, in from pip import main File "/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/__init__.py", line 43, in from pip.utils import get_installed_distributions, get_prog File "/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/utils/__init__.py", line 23, in from pip.locations import ( File "/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/locations.py", line 9, in from distutils import sysconfig ImportError: cannot import name 'sysconfig' I searched for sysconfig and found this: /home/jfb/EVs/env36/lib/python3.6/site-packages/pip/_vendor/distlib/_backport/__pycache__/sysconfig.cpython-36.pyc /home/jfb/EVs/env36/lib/python3.6/site-packages/pip/_vendor/distlib/_backport/sysconfig.cfg /home/jfb/EVs/env36/lib/python3.6/site-packages/pip/_vendor/distlib/_backport/sysconfig.py The results seem to be the same as when I searched a python 3.5 virtual environment I have setup. It has worked in the past as I have installed pylint and pykeyboard with it. As I type this I just remembered Mint updated python 3.6 earlier today. So now I suspect the update is involved. Has anyone else experienced this and know how to fix it? I heard distutils may have been split out... see if you have a package python3-distutils and if not installed, can you install it? I have: //usr/lib/python3.5/distutils and //usr/lib/python3.6/distutils, but no python3-distutils. Checking in Synaptic there is no python3-distutils but there is a python3-distutils-extra. Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] pip stopped working gives error
I have python 3.6 installed in a virtual environment on Mint 18. Today I wanted to use pip and got this error when I tried to use it. (env36) jfb@jims-mint18 ~ $ pip help Traceback (most recent call last): File "/home/jfb/EVs/env36/bin/pip", line 7, in from pip import main File "/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/__init__.py", line 43, in from pip.utils import get_installed_distributions, get_prog File "/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/utils/__init__.py", line 23, in from pip.locations import ( File "/home/jfb/EVs/env36/lib/python3.6/site-packages/pip/locations.py", line 9, in from distutils import sysconfig ImportError: cannot import name 'sysconfig' I searched for sysconfig and found this: /home/jfb/EVs/env36/lib/python3.6/site-packages/pip/_vendor/distlib/_backport/__pycache__/sysconfig.cpython-36.pyc /home/jfb/EVs/env36/lib/python3.6/site-packages/pip/_vendor/distlib/_backport/sysconfig.cfg /home/jfb/EVs/env36/lib/python3.6/site-packages/pip/_vendor/distlib/_backport/sysconfig.py The results seem to be the same as when I searched a python 3.5 virtual environment I have setup. It has worked in the past as I have installed pylint and pykeyboard with it. As I type this I just remembered Mint updated python 3.6 earlier today. So now I suspect the update is involved. Has anyone else experienced this and know how to fix it? Thanks, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Need help with FileNotFoundError
On 04/26/2018 03:27 PM, Danny Yoo wrote: copy('~/Documents/Courses/ModernBootcamp/story.txt', '~/Documents/Courses/ModernBootcamp/story_copy.txt') Hi Jim, You may need to use os.path.expanduser, as "tilde expansion" isn't something that's done automatically. This is referenced in the docs when they say: "Unlike a unix shell, Python does not do any automatic path expansions. Functions such as expanduser() and expandvars() can be invoked explicitly when an application desires shell-like path expansion. (See also the glob module.)" https://docs.python.org/3/library/os.path.html#module-os.path Try adding a call to os.path.expanduser() https://docs.python.org/3/library/os.path.html#os.path.expanduser on that tilde-prefixed path string. Hope this helps! Danny, Thanks for pointing me in the right direction. I had tried replacing the ~ with home/jfb/... now I realize it should have been /home/jfb/... Working now. Thanks, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Need help with FileNotFoundError
Been working my way through an online Python course. Up until now I have had no problems writing and running the programs using Python 3.6 in a virtual environment and then pasting them into the courses editor. When I run this program on my system I get the following error. # file_io.py def copy(file, new_file): with open(file) as data: text = data.read() with open(new_file, 'w') as new_text: new_text.write(text) copy('~/Documents/Courses/ModernBootcamp/story.txt', '~/Documents/Courses/ModernBootcamp/story_copy.txt') (env36) jfb@jims-mint18 ~ $ python '/home/jfb/Documents/Courses/ModernBootcamp/file_io.py' Traceback (most recent call last): File "/home/jfb/Documents/Courses/ModernBootcamp/file_io.py", line 11, in copy('~/Documents/Courses/ModernBootcamp/story.txt', '~/Documents/Courses/ModernBootcamp/story_copy.txt') File "/home/jfb/Documents/Courses/ModernBootcamp/file_io.py", line 4, in copy with open(file) as data: FileNotFoundError: [Errno 2] No such file or directory: '~/Documents/Courses/ModernBootcamp/story.txt' The file is there. jfb@jims-mint18 ~/Documents/Courses/ModernBootcamp $ ls adding_to_lists.py errors.py functionsII.pyhelpers.py modules.py stop_copying.py animals exercise.py functions.py iteration.py oop.py story.txt decorators.py file_io.pygenerators.py list_comps.py __pycache__ unlucky_numbers.py dictionarys.py FirstProgram guessing_game.py list_methods.py smiley_faces.py while_loop.py I must be doing something wrong path-wise, but I can't seem to figure it out. Any help appreciated. Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Virtual environment question
On 03/12/2018 08:44 PM, eryk sun wrote: On Tue, Mar 13, 2018 at 1:31 AM, Jim wrote: On 03/12/2018 04:04 AM, eryk sun wrote: On Mon, Mar 12, 2018 at 12:44 AM, Jim wrote: home = /usr/bin include-system-site-packages = false [...] resp = opener.open(request, timeout=self._timeout) File "/usr/lib/python3.5/urllib/request.py", line 466, in open This is normal. Virtual environments are not isolated from the standard library. Interesting. All I know about virtual environments is what I read on the net. I always see them recommended as a way to keep from messing up the default python, so I thought isolation was their purpose. You're thinking of isolating packages that are installed in site-packages, not the standard library. There's no point in copying and recompiling the entire standard library in every virtual environment. Just curious. So do they share parts of the standard libray? What happens if the version of python I have in a virtual environment is totally different than any python available from the os? Say version 3 vs version 2 in the os. Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Virtual environment question
On 03/12/2018 04:04 AM, eryk sun wrote: On Mon, Mar 12, 2018 at 12:44 AM, Jim wrote: home = /usr/bin include-system-site-packages = false [...] resp = opener.open(request, timeout=self._timeout) File "/usr/lib/python3.5/urllib/request.py", line 466, in open This is normal. Virtual environments are not isolated from the standard library. Interesting. All I know about virtual environments is what I read on the net. I always see them recommended as a way to keep from messing up the default python, so I thought isolation was their purpose. Thanks, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Virtual environment question
On 03/11/2018 05:54 PM, Cameron Simpson wrote: Note: This message came straight to me and I haven't seen it on the list yet. Hopefully this reply will make it to the list. On 11Mar2018 15:52, jim wrote: It was my understanding that using a virtual environment kept everything isolated in that environment. So I was surprised when I got the following error message. (env) jfb@jims-mint18 ~ $ File "/home/jfb/EVs/env/lib/python3.5/site-packages/selenium/webdriver/remote/remote_connection.py", line 528, in _request resp = opener.open(request, timeout=self._timeout) File "/usr/lib/python3.5/urllib/request.py", line 466, in open response = self._open(req, data) I snipped most of the error msg because for the purpose of this question I am not interested in them. I tried something that I did not think would work and it did not. I am wondering why the path for the first line and every line above it is /home/jfb/EVs/env and the second line and everything after is is /usr/lib/. I didn't think anything from my system python would be involved if I started from a virtual environment. It is possible to make a virtualenv which references the osurce python's library. These days the default is isolation, but older virtualenvs used to hook to the original python by default. This is controlled by virtualenv's --system-site-packages and --no-site-packages. Maybe you should build the env again using --no-site-packages explicitly and see if the behaviour changes. If you're not using the "virtualenv" command to make the environment, please tell use exactly how it was made (there are other tools for the same purpose). In fact, tell us regardless. It aids debugging. Cheers, Cameron Simpson (formerly c...@zip.com.au) I installed pyvenv in Jan 17 using synaptic on Mint 18. Here are the contents of the pyvenv cfg file: home = /usr/bin include-system-site-packages = false version = 3.5.2 It's been awhile so I don't remember that much about the installation. I really don't know that much about virtual environments so I am guessing I accepted the defaults for the installation. Just to be complete here is the entire error msg: Traceback (most recent call last): File "/home/jfb/MyProgs/Scripts/login_af.py", line 36, in driver = webdriver.Remote(desired_capabilities=caps) File "/home/jfb/EVs/env/lib/python3.5/site-packages/selenium/webdriver/remote/webdriver.py", line 154, in __init__ self.start_session(desired_capabilities, browser_profile) File "/home/jfb/EVs/env/lib/python3.5/site-packages/selenium/webdriver/remote/webdriver.py", line 243, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "/home/jfb/EVs/env/lib/python3.5/site-packages/selenium/webdriver/remote/webdriver.py", line 310, in execute response = self.command_executor.execute(driver_command, params) File "/home/jfb/EVs/env/lib/python3.5/site-packages/selenium/webdriver/remote/remote_connection.py", line 466, in execute return self._request(command_info[0], url, body=data) File "/home/jfb/EVs/env/lib/python3.5/site-packages/selenium/webdriver/remote/remote_connection.py", line 528, in _request resp = opener.open(request, timeout=self._timeout) File "/usr/lib/python3.5/urllib/request.py", line 466, in open response = self._open(req, data) File "/usr/lib/python3.5/urllib/request.py", line 484, in _open '_open', req) File "/usr/lib/python3.5/urllib/request.py", line 444, in _call_chain result = func(*args) File "/usr/lib/python3.5/urllib/request.py", line 1282, in http_open return self.do_open(http.client.HTTPConnection, req) File "/usr/lib/python3.5/urllib/request.py", line 1256, in do_open raise URLError(err) urllib.error.URLError: If you tell me where to look, I'd be happy to provide any more info you need. Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Virtual environment question
It was my understanding that using a virtual environment kept everything isolated in that environment. So I was surprised when I got the following error message. (env) jfb@jims-mint18 ~ $ File "/home/jfb/EVs/env/lib/python3.5/site-packages/selenium/webdriver/remote/remote_connection.py", line 528, in _request resp = opener.open(request, timeout=self._timeout) File "/usr/lib/python3.5/urllib/request.py", line 466, in open response = self._open(req, data) I snipped most of the error msg because for the purpose of this question I am not interested in them. I tried something that I did not think would work and it did not. I am wondering why the path for the first line and every line above it is /home/jfb/EVs/env and the second line and everything after is is /usr/lib/. I didn't think anything from my system python would be involved if I started from a virtual environment. Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] When to use classes
On 08/20/2017 03:12 AM, Alan Gauld via Tutor wrote: On 20/08/17 02:47, Steven D'Aprano wrote: since then feels like going back to the Dark Ages. Having to care about low-level details like creating buttons, installing callbacks and so forth just feels wrong. To be fair most GUI frameworks come with a GUI builder that remove the manual coding for things like that. Even Tk (upon which Tkinter is based) has a couple of them, but for some reason the Python implementation has never had one that worked well. The bigger industrial grade GUI builders for Java(Swing/JFX), .NET(VS), and even Gnome/Qt on Linux are all very easy to use to build quite complex GUIs. There is an alternative to callback based GUI frameworks, and that is an message-passing, event-driven language. The framework handles the events for you, and fires off messages to objects. If the object doesn't handle the event, it is sent to the next object in the message-passing heirarchy. Again, that's how pretty much every modern GUI works. The callback bit is just a manual exposure of what the GUI builder does under the covers. Most casual GUI programmers never create or specify a call back they just click the widget in the GUI builder and are taken to the pre-written empty function body. The language was Hypertalk, the scripting language of Apple's Hypercard application in the mid to late eighties. There was(is?) a project on Sourcefoirge to build a Python equivalent to Hypercard. I played with it a long time ago but it wasn't really ready for serious use in my view. I don't know if its still running or how far it has progressed. And there are several GUI builders for Python beyond Tk although I haven't had much success with any of them. I suspect because Python is so high level as a language that the effort they save is much less than when using Java or C++. By today's standards it is woefully primitive: only a single window, of a fixed size, black and white graphics, and only a fixed set of pre-defined GUI widgets and no way to create your own. But it is remarkable just how much power there is in just two widgets, text fields and buttons, especially since the buttons can be specialised into push buttons, radio buttons and checkbox buttons. Borland tried a similar trick on Windows with a tool called TurboVision(Or ObjectVision? my memory fails me) which was an entirely graphical tool with even the code being built using graphical code blocks. Scratch does the same thing today for beginning programmers. But all of these tools run into the same issues - eventually you will need to create something more complex which the tool can't handle. stack (Hypercard document) consisted of at least one shared background used by at least one card. Cards inherited their look, state and behaviour from their background, but could override any part of that. I think that was Hypercard's USP. The idea of an inherited look 'n feel was quite powerful and I'm surprised that nobody else has picked that up, at least as an option, for a new window/screen/frame. The Hypercard application managed the GUI event loop for you. It tracked the mouse and the keyboard, and other events, and each time it noticed an event, it sent a message to the appropriate object (a widget, card, background or stack). That object could either handle the message, or ignore it. If it ignored the message, it passed on to the next object in the heirachy. Again that's pretty much how every GUI framework operates. Its just that Tkinter etc make it explicit by forcing you to pass the parent object and event handler(s) into the widget at creation time. A GUI builder does that for you. If this looks a tiny bit like Javascript, that's because Javascript borrowed the idea and language of handlers from Hypertalk and Hypercard. Most OO GUI frameworks borrowed these ideas from Hypercard (and indeed the Object Pascal MacApp framework that Hypercard was built on). The MaCapp framework was a huge step up from the older procedural frameworks such as X Windows and MS Windows etc that had gone before. To call a handler in another object, you sent your own message, and the Hypercard application would manage the details: send "print" to field "Address" of card "George" That message would be sent via the same message path as any other event, Again that's pretty much how any GUI framework works today (although they also allow direct message passing between code objects too). They all have some kind of event posting service. Hypercard's legacy is alive and well in the GUI frameworks we all use today. The tools used to make that accessible are not so simple however, and in the end, the ability to create powerful, full featured GUIs has trumped the easy to use, but ultimately limited, scope of Hypercard. In one sense Hypercard is still alive. Check out Livecode at livecod
Re: [Tutor] Using venv
On 05/29/2017 08:09 PM, Ben Finney wrote: You should probably disregard this message as I have since solved the problem I was asking about. I originally wrote this message on 01/27/17, how it make it back to the list I don't know. Regards, Jim Jim writes: It has been suggested to me that I should use a virtual environment and venv would be a good choice. I've read through PEP405 and this link [1]. One possible confusion is the terminology. You have “a virtual environment” when you create one. The ‘venv’ module is not itself a virtual environment; it is what you use to create one :-) Though some of it seems a little confusing to me, I'm sure I can get it up and running. This question seems a little dumb and maybe I am being a little dense, but then what? * In each shell where you want to be working in that virtual Python environment, activate the virtualenv (by running the commands from its corresponding ‘activate’ script; e.g. ‘source $VENV/bin/activate’). * Do things requiring Python. Your program/script is done how do you run it? Do you always have to activate your venv and run it from there? To get the benefits of that particular virtualenv, yes. I like to run Tkinter programs from a launcher. Would that be possible and what would the command look like? How are the programs installed? Can you customise how they're launched? Lately I have been writing some Libreoffice calc macros and evaluating pyspread for it's macro capability. Would modules installed in my venv be available to the spreadsheet programs? The trick is that the environment variables for a process need to be set either when the program starts, or within the program; it can't be done externally. That isn't special to Python, it is how processes work. The virtualenv is activated by setting particular shell environment variables to specific values. If you can do that, the answer is yes. The ‘source $VENV/bin/activate’ command just runs shell commands to set those environment variables. It's not the only way to set those environment variables. Other Python-bundled programs, like LibreOffice or Blender, will likely have their own ways of activating a virtualenv; or at least you'll probably find people in those communities discussing how to do it. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] No file or directory error using subprocess and Popen
On 05/15/2017 08:33 PM, Jim wrote: On 05/15/2017 02:48 AM, Steven D'Aprano wrote: On Sun, May 14, 2017 at 10:57:57PM -0500, Jim wrote: I am running this on Mint 18. This is the third script I have written to open and position windows in workspaces. The first two work, but trying to open ebook-viewe r (calibre) with a specific book produces the following error. If I run the same command in the terminal it works without an error. I think your problem is that you're telling subprocess to run a command called: ebook-viewer /home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub with no arguments. What you want is a command called: ebook-viewer and a single argument: /home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub I think (but haven't tried it) that the simplest way to fix that is to change the entry in self.programs from: self.programs = ['jedit', 'google-chrome', 'doublecmd', 'ebook-viewer /home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub'] to: path_to_file = '/home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub' self.programs = ['jedit', 'google-chrome', 'doublecmd', ['ebook-viewer', path_to_file], ] I made the changes you suggested. def __init__(self): path_to_book = '/home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub' self.programs = ['jedit', 'google-chrome', 'doublecmd', ['ebook-viewer', path_to_book ]] self.classname = {'jedit' : 'sun-awt-X11-XFramePeer', 'google-chrome':'google-chrome', 'doublecmd':'doublecmd', 'calibre-ebook-viewer': 'libprs500'} self.open_and_move() I noticed you have a , between the last two ]],s. I don't think you meant that but I tried it both ways just incase. and see if that fixes it. (It may not be enough, or the right approach, but at least you'll get a different error if it is wrong :-) Unfortunately you are correct, I did get a different error message. Exception in thread Thread-4: Traceback (most recent call last): File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner self.run() File "/usr/lib/python3.5/threading.py", line 862, in run self._target(*self._args, **self._kwargs) File "/home/jfb/MyProgs/Scripts/place_windows_OO_WS3.py", line 24, in open_it subprocess.call([self.program]) File "/usr/lib/python3.5/subprocess.py", line 557, in call with Popen(*popenargs, **kwargs) as p: File "/usr/lib/python3.5/subprocess.py", line 947, in __init__ restore_signals, start_new_session) File "/usr/lib/python3.5/subprocess.py", line 1474, in _execute_child executable = os.fsencode(executable) File "/usr/lib/python3.5/os.py", line 862, in fsencode raise TypeError("expect bytes or str, not %s" % type(filename).__name__) TypeError: expect bytes or str, not list Traceback (most recent call last): File "/home/jfb/MyProgs/Scripts/place_windows_OO_WS3.py", line 78, in Place() File "/home/jfb/MyProgs/Scripts/place_windows_OO_WS3.py", line 21, in __init__ self.open_and_move() File "/home/jfb/MyProgs/Scripts/place_windows_OO_WS3.py", line 31, in open_and_move p = Popen(['xdotool', 'search', '--classname', self.classname[self.program]], stdout=subprocess.PIPE) TypeError: unhashable type: 'list' Regards, Jim Replying to myself to report that I got it working. I changed open_it to: def open_it(self): if self.program == 'ebook-viewer': subprocess.call([self.program, self.path_to_book]) else: subprocess.call([self.program]) After looking at it, I realized I should be providing the path when I was actually opening the file in open_it not further down in open_and_move where I was positioning the windows. Also I realize open_and_move is a poor name and needs to be changed to move_it or something. I still get the following error but it does not seem to effect the programs operation. So for now I am just glad it is working. Traceback (most recent call last): File "/home/jfb/MyProgs/Scripts/place_windows_OO_WS3.py", line 84, in Place() File "/home/jfb/MyProgs/Scripts/place_windows_OO_WS3.py", line 21, in __init__ self.open_and_move() File "/home/jfb/MyProgs/Scripts/place_windows_OO_WS3.py", line 37, in open_and_move p = Popen(['xdotool', 'search', '--classname', self.classname[self.program]], stdout=subprocess.PIPE) KeyError: 'ebook-viewer' Thanks for everyones help, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] No file or directory error using subprocess and Popen
On 05/15/2017 07:03 AM, Peter Otten wrote: Jim wrote: I am running this on Mint 18. This is the third script I have written to open and position windows in workspaces. The first two work, but trying to open ebook-viewe r (calibre) with a specific book produces the following error. If I run the same command in the terminal it works without an error. Exception in thread Thread-4: Traceback (most recent call last): File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner self.run() File "/usr/lib/python3.5/threading.py", line 862, in run self._target(*self._args, **self._kwargs) File "/home/jfb/MyProgs/Scripts/place_windows_OO_WS3.py", line 24, in open_it subprocess.call([self.program]) File "/usr/lib/python3.5/subprocess.py", line 557, in call with Popen(*popenargs, **kwargs) as p: File "/usr/lib/python3.5/subprocess.py", line 947, in __init__ restore_signals, start_new_session) File "/usr/lib/python3.5/subprocess.py", line 1551, in _execute_child raise child_exception_type(errno_num, err_msg) FileNotFoundError: [Errno 2] No such file or directory: 'ebook-viewer /home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub' Code: # place_windows_OO_WS3.py import subprocess from subprocess import Popen,PIPE import threading import time class Place(): def __init__(self): self.programs = ['jedit', 'google-chrome', 'doublecmd', 'ebook-viewer /home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub'] self.classname = {'jedit' : 'sun-awt-X11-XFramePeer', 'google-chrome':'google-chrome', 'doublecmd':'doublecmd', 'calibre-ebook-viewer': 'libprs500'} self.open_and_move() def open_it(self): subprocess.call([self.program]) def open_and_move(self): for self.program in self.programs: opener = threading.Thread(target=self.open_it) opener.start() time.sleep(2) p = Popen(['xdotool', 'search', '--classname', self.classname[self.program]], stdout=subprocess.PIPE) if self.classname[self.program] == 'sun-awt-X11-XFramePeer': wid = str(p.stdout.read()) wid = wid[len(wid) - 11 : len(wid) - 3] x = '0' y = '0' print('***jedit***') elif self.classname[self.program] == 'google-chrome': wid = str(p.stdout.read()) wid = wid[len(wid) - 11 : len(wid) - 3] x = '1924' y = '0' print('***google***') elif self.classname[self.program] == 'doublecmd': wid = str(p.stdout.read()) wid = wid[len(wid) - 11 : len(wid) - 3] x = '1924' y = '537' print('***double***') else: wid = str(p.stdout.read()) wid = wid[len(wid) - 11 : len(wid) - 3] x = '2540' #'1924' y = '537' print('***calibre***') subprocess.call(['xdotool', 'windowmove', str(wid), x, y]) I did some googling and it seems that subprocess does not have a length limit in linux. Could someone tell me how to correct the above error. Not directly related to your question, but I think you should have one instance of your Place class per program. That way you keep related information together and avoid the need to look it up in a dict or find it with a long chain of if ... elif ... tests. For example: # untested import subprocess import threading import time DELAY = 3.0 # seconds class Place: def __init__(self, cmd, classname=None, name=None, x=0, y=0): if classname is None: classname = cmd[0] if name is None: name = cmd[0] self.cmd = cmd self.classname = classname self.name = name self.x = x self.y = y def open_it(self): subprocess.call(self.cmd) def open_and_move(self): opener = threading.Thread(target=self.open_it) opener.start() time.sleep(DELAY) output = subprocess.Popen( ['xdotool', 'search', '--classname', self.classname], stdout=subprocess.PIPE ).communicate()[0] wid = output.split()[-1].decode() subprocess.call( [ '
Re: [Tutor] No file or directory error using subprocess and Popen
On 05/14/2017 11:19 PM, boB Stepp wrote: On Sun, May 14, 2017 at 10:57 PM, Jim wrote: I am running this on Mint 18. This is the third script I have written to open and position windows in workspaces. The first two work, but trying to open ebook-viewe r (calibre) with a specific book produces the following error. If I run the same command in the terminal it works without an error. Exception in thread Thread-4: Traceback (most recent call last): File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner self.run() File "/usr/lib/python3.5/threading.py", line 862, in run self._target(*self._args, **self._kwargs) File "/home/jfb/MyProgs/Scripts/place_windows_OO_WS3.py", line 24, in open_it subprocess.call([self.program]) File "/usr/lib/python3.5/subprocess.py", line 557, in call with Popen(*popenargs, **kwargs) as p: File "/usr/lib/python3.5/subprocess.py", line 947, in __init__ restore_signals, start_new_session) File "/usr/lib/python3.5/subprocess.py", line 1551, in _execute_child raise child_exception_type(errno_num, err_msg) FileNotFoundError: [Errno 2] No such file or directory: 'ebook-viewer /home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub' Code: # place_windows_OO_WS3.py import subprocess from subprocess import Popen,PIPE import threading import time class Place(): def __init__(self): self.programs = ['jedit', 'google-chrome', 'doublecmd', 'ebook-viewer /home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub'] self.classname = {'jedit' : 'sun-awt-X11-XFramePeer', 'google-chrome':'google-chrome', 'doublecmd':'doublecmd', 'calibre-ebook-viewer': 'libprs500'} self.open_and_move() def open_it(self): subprocess.call([self.program]) I'm not very familiar with using the subprocess module yet, but when the above call to "subprocess.call([self.program])" occurs, isn't subprocess.call() expecting a list like ['ebook-viewer', '/home/jfb ...'] ? Hope I am not off-track here. boB Bob, I thought you were on to something, especially since Steven suggested about the same thing. See my reply to Steven. It seems to be looking for a str or byte not a list. Thanks, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] No file or directory error using subprocess and Popen
On 05/15/2017 02:48 AM, Steven D'Aprano wrote: On Sun, May 14, 2017 at 10:57:57PM -0500, Jim wrote: I am running this on Mint 18. This is the third script I have written to open and position windows in workspaces. The first two work, but trying to open ebook-viewe r (calibre) with a specific book produces the following error. If I run the same command in the terminal it works without an error. I think your problem is that you're telling subprocess to run a command called: ebook-viewer /home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub with no arguments. What you want is a command called: ebook-viewer and a single argument: /home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub I think (but haven't tried it) that the simplest way to fix that is to change the entry in self.programs from: self.programs = ['jedit', 'google-chrome', 'doublecmd', 'ebook-viewer /home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub'] to: path_to_file = '/home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub' self.programs = ['jedit', 'google-chrome', 'doublecmd', ['ebook-viewer', path_to_file], ] I made the changes you suggested. def __init__(self): path_to_book = '/home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub' self.programs = ['jedit', 'google-chrome', 'doublecmd', ['ebook-viewer', path_to_book ]] self.classname = {'jedit' : 'sun-awt-X11-XFramePeer', 'google-chrome':'google-chrome', 'doublecmd':'doublecmd', 'calibre-ebook-viewer': 'libprs500'} self.open_and_move() I noticed you have a , between the last two ]],s. I don't think you meant that but I tried it both ways just incase. and see if that fixes it. (It may not be enough, or the right approach, but at least you'll get a different error if it is wrong :-) Unfortunately you are correct, I did get a different error message. Exception in thread Thread-4: Traceback (most recent call last): File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner self.run() File "/usr/lib/python3.5/threading.py", line 862, in run self._target(*self._args, **self._kwargs) File "/home/jfb/MyProgs/Scripts/place_windows_OO_WS3.py", line 24, in open_it subprocess.call([self.program]) File "/usr/lib/python3.5/subprocess.py", line 557, in call with Popen(*popenargs, **kwargs) as p: File "/usr/lib/python3.5/subprocess.py", line 947, in __init__ restore_signals, start_new_session) File "/usr/lib/python3.5/subprocess.py", line 1474, in _execute_child executable = os.fsencode(executable) File "/usr/lib/python3.5/os.py", line 862, in fsencode raise TypeError("expect bytes or str, not %s" % type(filename).__name__) TypeError: expect bytes or str, not list Traceback (most recent call last): File "/home/jfb/MyProgs/Scripts/place_windows_OO_WS3.py", line 78, in Place() File "/home/jfb/MyProgs/Scripts/place_windows_OO_WS3.py", line 21, in __init__ self.open_and_move() File "/home/jfb/MyProgs/Scripts/place_windows_OO_WS3.py", line 31, in open_and_move p = Popen(['xdotool', 'search', '--classname', self.classname[self.program]], stdout=subprocess.PIPE) TypeError: unhashable type: 'list' Regards, Jim The difference is that the shell automatically splits things on spaces, so it sees the space between ebook-viewer and the long path, and treats the first word as the executable and the second as an argument. But Python treats the whole string, spaces and quotes included, as the executable. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] No file or directory error using subprocess and Popen
I am running this on Mint 18. This is the third script I have written to open and position windows in workspaces. The first two work, but trying to open ebook-viewe r (calibre) with a specific book produces the following error. If I run the same command in the terminal it works without an error. Exception in thread Thread-4: Traceback (most recent call last): File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner self.run() File "/usr/lib/python3.5/threading.py", line 862, in run self._target(*self._args, **self._kwargs) File "/home/jfb/MyProgs/Scripts/place_windows_OO_WS3.py", line 24, in open_it subprocess.call([self.program]) File "/usr/lib/python3.5/subprocess.py", line 557, in call with Popen(*popenargs, **kwargs) as p: File "/usr/lib/python3.5/subprocess.py", line 947, in __init__ restore_signals, start_new_session) File "/usr/lib/python3.5/subprocess.py", line 1551, in _execute_child raise child_exception_type(errno_num, err_msg) FileNotFoundError: [Errno 2] No such file or directory: 'ebook-viewer /home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub' Code: # place_windows_OO_WS3.py import subprocess from subprocess import Popen,PIPE import threading import time class Place(): def __init__(self): self.programs = ['jedit', 'google-chrome', 'doublecmd', 'ebook-viewer /home/jfb/Documents/eBooks/Javascript/GOOGLE_SHEETS/googlespreadsheetprogramming.epub'] self.classname = {'jedit' : 'sun-awt-X11-XFramePeer', 'google-chrome':'google-chrome', 'doublecmd':'doublecmd', 'calibre-ebook-viewer': 'libprs500'} self.open_and_move() def open_it(self): subprocess.call([self.program]) def open_and_move(self): for self.program in self.programs: opener = threading.Thread(target=self.open_it) opener.start() time.sleep(2) p = Popen(['xdotool', 'search', '--classname', self.classname[self.program]], stdout=subprocess.PIPE) if self.classname[self.program] == 'sun-awt-X11-XFramePeer': wid = str(p.stdout.read()) wid = wid[len(wid) - 11 : len(wid) - 3] x = '0' y = '0' print('***jedit***') elif self.classname[self.program] == 'google-chrome': wid = str(p.stdout.read()) wid = wid[len(wid) - 11 : len(wid) - 3] x = '1924' y = '0' print('***google***') elif self.classname[self.program] == 'doublecmd': wid = str(p.stdout.read()) wid = wid[len(wid) - 11 : len(wid) - 3] x = '1924' y = '537' print('***double***') else: wid = str(p.stdout.read()) wid = wid[len(wid) - 11 : len(wid) - 3] x = '2540' #'1924' y = '537' print('***calibre***') subprocess.call(['xdotool', 'windowmove', str(wid), x, y]) I did some googling and it seems that subprocess does not have a length limit in linux. Could someone tell me how to correct the above error. Thanks, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] General question rgrd. usage of libraries
On 05/05/2017 08:45 AM, Rafael Knuth wrote: Hi there, I just recently learned how to build a basic web scraper with Python 3.5 (I am learning Python for data analytics purposes). Being new to coding, I have a question: How do I know which libraries I need to perform a certain task? For example, in case of this web scraper (which I built with help of a tutorial on YouTube) I need to have urrlib and Beautiful Soup import urllib import urllib.request from bs4 import BeautifulSoup theurl = "https://twitter.com/rafaelknuth"; thepage = urllib.request.urlopen(theurl) soup = BeautifulSoup(thepage, "html.parser") print(soup.title.text) i = 1 for tweets in soup.findAll("div",{"class":"content"}): print(i) print(tweets.find("p").text) i = i + 1 Is there a way I can figure out which libraries I need when drafting my code? Can you share your experiences? Right now, if I wanted for example to populate a Google Sheet with my scraped web content - how would I know which libraries I would need to actually make this happen? I am trying wondering if there is a process to figure out what I exactly need library-wise. There is a Python API to google sheets but when I had a look, it seemed fairly complex. I haven't tried it yet but depending on what you need to do this library may be what you need: https://pypi.python.org/pypi/gspread. Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Can a virtual environment be renamed?
On 04/16/2017 11:24 AM, Chris Warrick wrote: On 16 April 2017 at 18:16, Jim wrote: On 04/16/2017 10:10 AM, Chris Warrick wrote: On 16 April 2017 at 16:45, Jim wrote: My system python is 2.7.12 so I created a virtual environment using venu to run 3.5.2. I put it in /home/jfb/EVs/env. Now I would like to try 3.6 and put it in env36. Is it possible to change env to env35 for 3.5.2 without breaking things? No. You need to delete your existing virtualenv and create a new one. You can just use `pip freeze > requirements.txt` in the old one and run `pip install -r requirements.txt` in the new one to ”move” all the packages you had. Thanks Chris. I thought that would be the answer but wanted to check before I spent a lot of time trying to do something that was not possible. Virtual environments tend to confuse me. My system is Mint 18.1 with 2.7.12 & 3.5.2 installed. So I would have to download a tar file of 3.6, then build it and then use it's version of venv to create a virtual environment to try 3.6. Is that correct? Yes, you need to install the appropriate interpreter first, and likewise a virtualenv won’t work if you uninstall an interpreter/upgrade it to a new minor version*. You might not need to use the source tarball if https://launchpad.net/~fkrull/+archive/ubuntu/deadsnakes works on Mint (and if you do use tarballs, make sure to install somewhere in /opt or whatever not to make a mess — it’s easy to break your OS if you’re not careful) * eg. 3.5 → 3.6. Won’t ever happen on Mint or other “friendly” distros, unless you do a dist-upgrade. Happens pretty often on rolling-release distros or macOS with homebrew. Chris, thanks for the confirmation and the link. Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Can a virtual environment be renamed?
On 04/16/2017 02:18 PM, Mats Wichmann wrote: On 04/16/2017 10:16 AM, Jim wrote: On 04/16/2017 10:10 AM, Chris Warrick wrote: On 16 April 2017 at 16:45, Jim wrote: My system python is 2.7.12 so I created a virtual environment using venu to run 3.5.2. I put it in /home/jfb/EVs/env. Now I would like to try 3.6 and put it in env36. Is it possible to change env to env35 for 3.5.2 without breaking things? No. You need to delete your existing virtualenv and create a new one. You can just use `pip freeze > requirements.txt` in the old one and run `pip install -r requirements.txt` in the new one to ”move” all the packages you had. Thanks Chris. I thought that would be the answer but wanted to check before I spent a lot of time trying to do something that was not possible. Virtual environments tend to confuse me. My system is Mint 18.1 with 2.7.12 & 3.5.2 installed. So I would have to download a tar file of 3.6, then build it and then use it's version of venv to create a virtual environment to try 3.6. Is that correct? Thanks, Jim It doesn't need to be terribly complicated, something called pyenv can manage the install for you (yes, it will build it if needed). pyenv install --list to show what's available to install pyenv install 3.6.0 to install a copy If you set up the shell helpers, pyenv will let you create the virtualenv and launch it: pyenv virtualenv 3.6.0 test-3.6.0 pyenv activate test-3.6.0 Thanks Mats, When I get a chance to try 3.6 this looks like the best way for me to install it. Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Can a virtual environment be renamed?
On 04/16/2017 10:10 AM, Chris Warrick wrote: On 16 April 2017 at 16:45, Jim wrote: My system python is 2.7.12 so I created a virtual environment using venu to run 3.5.2. I put it in /home/jfb/EVs/env. Now I would like to try 3.6 and put it in env36. Is it possible to change env to env35 for 3.5.2 without breaking things? No. You need to delete your existing virtualenv and create a new one. You can just use `pip freeze > requirements.txt` in the old one and run `pip install -r requirements.txt` in the new one to ”move” all the packages you had. Thanks Chris. I thought that would be the answer but wanted to check before I spent a lot of time trying to do something that was not possible. Virtual environments tend to confuse me. My system is Mint 18.1 with 2.7.12 & 3.5.2 installed. So I would have to download a tar file of 3.6, then build it and then use it's version of venv to create a virtual environment to try 3.6. Is that correct? Thanks, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Can a virtual environment be renamed?
My system python is 2.7.12 so I created a virtual environment using venu to run 3.5.2. I put it in /home/jfb/EVs/env. Now I would like to try 3.6 and put it in env36. Is it possible to change env to env35 for 3.5.2 without breaking things? Thanks, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Please explain part of this code
On 02/15/2017 04:56 PM, Alan Gauld via Tutor wrote: On 15/02/17 22:37, Jim wrote: self.choices = { "1": self.show_notes, "2": self.search_notes, "3": self.add_note, "4": self.modify_note, "5": self.quit } The author says: The action variable actually refers to a specific method and is called by appending empty brackets (since none of the methods require parameters) to the variable. I don't recall ever seeing this before. What is this technique called? Its very common, especially in GUIs and used in many languages including C, VB, Java, Javascript and Lisp. Its usually called a callback (because the stored function is called back by the event receiver). In C it is done by using a "pointer to a function". In Lisp you create a Lambda (an anonymous function) - which you can also do in Python and recent Java versions. In Smalltalk and Ruby you define a "block". In most of the other languages it's similar to Python, you just pass the name of the function. This is often referred to as the language treating functions as "first class objects", and is a core part of Functional Programming. A common FP structure is the map function which takes a function and a sequence and applies the function to each member of the sequence, returning the resultant sequence. Here is a short Python example: def double(x): return x*2 data = [1,2,3,4] result = map(double, data) # -> [2,4,6,8] print(result) HTH It does help. I have done a little bit of tkinter programing and have used callbacks, but when I looked at this code it just didn't register that way in my mind. Thanks for your explanation. Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Please explain part of this code
import sys from notebook import Notebook, Note class Menu: '''Display a menu and respond to choices when run.''' def __init__(self): self.notebook = Notebook() self.choices = { "1": self.show_notes, "2": self.search_notes, "3": self.add_note, "4": self.modify_note, "5": self.quit } def display_menu(self): print(""" Notebook Menu 1. Show all Notes 2. Search Notes 3. Add Note 4. Modify Note 5. Quit """) def run(self): '''Display the menu and respond to choices.''' while True: self.display_menu() choice = input("Enter an option: ") action = self.choices.get(choice) if action: action() else: print("{0} is not a valid choice".format(choice)) The author says: The action variable actually refers to a specific method and is called by appending empty brackets (since none of the methods require parameters) to the variable. I sort of understand what is going on with "action". All of the choices to the right of the :'s are methods defined elsewhere in the code. So I guess that will call whatever method is associated with a choice. I don't recall ever seeing this before. What is this technique called? Thanks, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to interact with the result of subprocess.call()
On 12/26/2016 04:48 AM, Peter Otten wrote: Jim Byrnes wrote: Is there a way to terminate subprocess and still keep LO open so pykeyboard can send it keystrokes from the script? In theory you can open Libre Office from another thread, wait a moment and then send it keystrokes from the main thread. I managed to do this with the script below. However, the procedure is very brittle; while experimenting I managed to "press" the control key without releasing it afterwards. The interval from doing it to realizing what was going on to "fixing" it (reboot) was an interesting experience... from contextlib import contextmanager import subprocess import threading import time import pykeyboard kb = pykeyboard.PyKeyboard() @contextmanager def press_key(key, kb=kb): kb.press_key(key) try: yield time.sleep(1) finally: kb.release_key(key) def open_it(filename): subprocess.call(["libreoffice", filename]) print("exiting libreoffice thread") LONG_ENOUGH = 15 # seconds # enter text into an existing odt file filename = "demo.odt" text = "hello and goodbye" opener = threading.Thread(target=open_it, args=(filename,)) opener.start() time.sleep(LONG_ENOUGH) # for libreoffice to start and open the file kb.type_string(text) with press_key(kb.control_key): kb.tap_key("s") with press_key(kb.alt_key): kb.tap_key(kb.function_keys[4]) print("exiting main thread") Peter, My apologies for taking so long to get back and thank you for the code. With the holidays and moving to a new computer/OS I didn't have much time to work on my little project. I was able to use your code and send the necessary keystrokes to manipulate LO. Thanks again. Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Using venv
On 01/27/2017 04:49 PM, Cameron Simpson wrote: On 27Jan2017 15:47, jim wrote: It has been suggested to me that I should use a virtual environment and venv would be a good choice. I've read through PEP405 and this link [1]. Though some of it seems a little confusing to me, I'm sure I can get it up and running. This question seems a little dumb and maybe I am being a little dense, but then what? Your program/script is done how do you run it? Do you always have to activate your venv and run it from there? I like to run Tkinter programs from a launcher. Would that be possible and what would the command look like? Lately I have been writing some Libreoffice calc macros and evaluating pyspread for it's macro capability. Would modules installed in my venv be available to the spreadsheet programs? The mere act of using the python from inside the venv invokes a python that runs off the venv, so all you really need to do is to contrive to execute that python instead of the system python where you want it. If your scripts start with something like this: #!/usr/bin/env python3 then you can simply contrive that "python3" is found from the virtualenv. You might put a symlink in your personal $HOME/bin directory, or source the venv's "activate" file from your shell's profile (this making the venv searched ahead of the system paths), etc. Or your launcher might simply invoke: $HOME/path/to/your/venv/bin/python your-tk-inter-script.py Cheers, Cameron Simpson Thank you. Got it up and running and tested it with a previously written Tkinter script, which works fine. Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Using venv
It has been suggested to me that I should use a virtual environment and venv would be a good choice. I've read through PEP405 and this link [1]. Though some of it seems a little confusing to me, I'm sure I can get it up and running. This question seems a little dumb and maybe I am being a little dense, but then what? Your program/script is done how do you run it? Do you always have to activate your venv and run it from there? I like to run Tkinter programs from a launcher. Would that be possible and what would the command look like? Lately I have been writing some Libreoffice calc macros and evaluating pyspread for it's macro capability. Would modules installed in my venv be available to the spreadsheet programs? Thanks, Jim [1] https://realpython.com/blog/python/python-virtual-environments-a-primer/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to interact with the result of subprocess.call()
On 12/24/2016 07:43 PM, Alan Gauld via Tutor wrote: On 25/12/16 01:21, Jim Byrnes wrote: I am not trying to automate libreoffice using subprocess. No, but you are trying to automate LO from within Python by sending it keystrokes and that's not easy. That's why I previously asked whether you really wanted to open the LO file directly and manipulate it from within Python - that's (slightly) easier than manipulating LO directly and much easier than manipulating LO from Python via keystrokes. message I was told that subprocess was the way to open libreoffice from a python script. Which is true if you want to bring up a LO session for your user to manipulate. But it's not the way to drive LO automatically. (One option is to start LO from Python then use macros within LO to do the automation - there may even be a command line switch to trigger a macro - I can't remember off hand) To drive LO via keystrokes your program needs to inject key/mouse events into the LO event queue. That's not easy and not very reliable either(*). There are some libraries that can help but it should be the path of last resort. (*)LO remembers its last screen setting and opens with them, if those screen settings are different than the ones you programmed for then navigation will be different and so on. That's easy to deal with for a human who can see the screen but sending keystrokes programmatically you are effectively trying to drive the system blindfolded! I don't think I need to "know where stuff is" to manipulate LO. At first I was just using Selenium to get the data from the web page, but the focus would end up in the url bar. I forget the exact details but I could not get Selenium to manipulate Chrome anymore at that point. I did some searching and found pykeyboard. Using it I was able to send Ctrl-A and then Ctrl-C to copy the page to the clipboard. My thinking is if I can get LO to accept keystrokes I can send Shift-Ctrl-V to paste special and the two enter keys to answer dialog questions and paste the info into a sheet. I would use the fact that LO reopens to where it was closed to my advantage by not having to use a macro to navigate to the proper page. Up until this point in the script I have used a combination of Selenium and pykeyboard to log on to a web site and put some info in the clipboard. Now I need to send keystrokes to libreoffice to paste from the clipboard into the spreadsheet. Or you could just open the spreadsheet file directly and insert the data directly into it from Python. I think there is a library for that - there are several for doing it in Excel (so if your spreadsheet is in Excel format it is fairly easy). Or, if you can use CSV format, its just a standard library module. I'll look into these alternatives if I can't figure out how to get keystrokes into LO using my present approach. Alternatively you can use the LO API to directly inject the data into the spreadsheet objects (like using COM in Microsoft land). I have used pyuno api to automate libreoffice in the past, but it was a time consuming and confusing process. Trust me it is nowhere near as confusing and frustrating as trying to drive LO (Or any other GUI) via keystrokes! Based on my success with pykeyboard and Chrome I thought it would be easier than diving back into Uno. However, using subprocess seems to be blocking me from sending any keystrokes to LO. I don't understand subprocess well enough to know if it is actually blocking my keystrokes. I concluded that based on the fact that when I closed LO the two enter_keys at the end of the script were executed in the terminal. Is there a way to terminate subprocess and still keep LO open so pykeyboard can send it keystrokes from the script? I was trying this approach because it looked like I could avoid the uno complexity. If there isn't a direct file manipulation library for LO spreadsheets then UNO is probably the easiest option. Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to interact with the result of subprocess.call()
On 12/24/2016 05:10 PM, Danny Yoo wrote: On Sat, Dec 24, 2016 at 2:40 PM, Jim Byrnes wrote: subprocess.call(['libreoffice', '/home/jfb/test.ods']) k.tap_key(k.enter_key) k.tap_key(k.enter_key) If I run the above code, libreoffice opens the test.ods spreadsheet then just sits there. When I close libreoffice the two enter_keys are executed in the terminal that originated the script. How can I continue to send keystrokes to libreoffice from the script once it has been opened by subprocess.call()? Hi Jim, You can not use subprocess to automate a GUI application. This approach will not work because libreoffice isn't written to pay attention to the stdin file handle of its process. That's one of the traditional reasons why GUI applications are unpopular for programmers: in general, GUI-based applications are not trivial to automate. You do have a few options: * See if the application provides a programming interface (an "API"). In the case of libreoffice, there does appear to be such an API: http://api.libreoffice.org/examples/examples.html#python_examples Accessing it is very much outside the domain of Python-tutor: you will likely need to talk with with the libreoffice folks. But if you can do this, it's probably nicer since the interface will use the terms of libreoffice, rather than in terms of keystrokes, timer delays, and mouse movement. * More general automation of GUI applications is possible. Here is a link to pyautogui, a third-party library that handles GUI automation: http://pyautogui.readthedocs.io/en/latest/ Again, you'll probably need to talk with folks who have experience with pyautogui; I don't think many of us on Tutor are very familiar with it. Good luck! Danny, I am not trying to automate libreoffice using subprocess. In an earlier message I was told that subprocess was the way to open libreoffice from a python script. It does do that but now it seems to be blocking my attempts to send keystrokes to libreoffice. Up until this point in the script I have used a combination of Selenium and pykeyboard to log on to a web site and put some info in the clipboard. Now I need to send keystrokes to libreoffice to paste from the clipboard into the spreadsheet. I have used pyuno api to automate libreoffice in the past, but it was a time consuming and confusing process. I was trying this approach because it looked like I could avoid the uno complexity. I think it would work if I could figure out how to send keystrokes to libreoffice after it is opened using subprocess or some alternative that would work better. Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] How to interact with the result of subprocess.call()
subprocess.call(['libreoffice', '/home/jfb/test.ods']) k.tap_key(k.enter_key) k.tap_key(k.enter_key) If I run the above code, libreoffice opens the test.ods spreadsheet then just sits there. When I close libreoffice the two enter_keys are executed in the terminal that originated the script. How can I continue to send keystrokes to libreoffice from the script once it has been opened by subprocess.call()? Thanks, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Open a libreoffice calc file in Python
On 12/22/2016 03:54 AM, Alan Gauld via Tutor wrote: On 22/12/16 03:37, Jim Byrnes wrote: Python 3.4 on Ubuntu If I was going to open a libreoffice calc file from the terminal I would go: libreoffice --calc /home/path/to/myfile.ods. How would I do this from Python? Others have advised how to run the Libreoffice app from within Python. If you really want to open the actual spreadsheet file in Python rather than Libreoffice then its a bit more tricky. If that is what you really meant get back to us and we can start on the options available... First thanks to everyone that responded pointing me in the right direction. Alan, I want to open Libreoffice with a particular file loaded. I started out to write a libreoffice macro in python to go to a website, get some info, copy it to the clipboard and then paste it in libreoffice calc. I started out by writing a script using Selenium that successfully did what I wanted. Once I had it working the plan was to put it in a macro. When I did that I got a large error message where both libreoffice and selenium complained. I seemed to say that the first element of the webpage I tried to manipulate was in a state that it could not be interacted with, even though outside of libreoffice the script ran fine. This got me thinking that maybe I should attack the problem from the other end, ie run the script and have it load libreoffice at the end. Hence my question. for completeness here is the error msg I received: com.sun.star.uno.RuntimeExceptionError during invoking function login in module file:///home/jfb/.config/libreoffice/4/user/Scripts/python/funds/funds.py (: Message: invalid element state: Element is not currently interactable and may not be manipulated (Session info: chrome=55.0.2883.87) (Driver info: chromedriver=2.25.426924 (649f9b868f6783ec9de71c123212b908bf3b232e),platform=Linux 4.4.0-57-generic x86_64) /usr/local/lib/python3.4/dist-packages/selenium/webdriver/remote/errorhandler.py:192 in function check_response() [raise exception_class(message, screen, stacktrace)] /usr/local/lib/python3.4/dist-packages/selenium/webdriver/remote/webdriver.py:236 in function execute() [self.error_handler.check_response(response)] /usr/local/lib/python3.4/dist-packages/selenium/webdriver/remote/webelement.py:494 in function _execute() [return self._parent.execute(command, params)] /usr/local/lib/python3.4/dist-packages/selenium/webdriver/remote/webelement.py:92 in function clear() [self._execute(Command.CLEAR_ELEMENT)] /home/jfb/.config/libreoffice/4/user/Scripts/python/funds/funds.py:29 in function login() [username.clear()] /usr/lib/libreoffice/program/pythonscript.py:869 in function invoke() [ret = self.func( *args )] ) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Open a libreoffice calc file in Python
Python 3.4 on Ubuntu If I was going to open a libreoffice calc file from the terminal I would go: libreoffice --calc /home/path/to/myfile.ods. How would I do this from Python? Thanks, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] comp.lang.python on gmane
On 10/27/2016 09:54 PM, Random832 wrote: On Thu, Oct 27, 2016, at 20:40, Jim Byrnes wrote: Is comp.lang.python available on gmane? I've googled and found references to it being on gmane but I can't find it there. I'd like to use gmane because Comcast doesn't do usenet anymore. I don't know about the current viability of gmane in general, but it's called "gmane.comp.python.general" on gmane. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor That worked. Not sure how I over looked it the other times I was trying to subscribe. Thanks much. Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] comp.lang.python on gmane
On 10/27/2016 08:09 PM, Danny Yoo wrote: On Thu, Oct 27, 2016 at 5:40 PM, Jim Byrnes wrote: Is comp.lang.python available on gmane? I've googled and found references to it being on gmane but I can't find it there. I'd like to use gmane because Comcast doesn't do usenet anymore. Hi Jim, I think Gmane is still recovering: https://lars.ingebrigtsen.no/2016/07/28/the-end-of-gmane/ I read that but had forgotten about it because up until now gmane seemed to be working normally for me. http://home.gmane.org/2016/08/29/next-steps-gmane/ It sounds like they're making good progress at recovery so far. Until then, you can still get at comp.lang.python via web interface with Google Groups: https://groups.google.com/forum/#!forum/comp.lang.python Besides those, the archive is available at: http://mail.python.org/pipermail/python-list/ I am trying to solve a problem with Selenium and googling hasn't helped. I wanted to ask a question on the list, but wanted to search back 5 or 6 months first to see it it had already been solved. I have always found the web interfaces so cumbersome to use I don't know if I can do a search like that on them. Thanks, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] comp.lang.python on gmane
Is comp.lang.python available on gmane? I've googled and found references to it being on gmane but I can't find it there. I'd like to use gmane because Comcast doesn't do usenet anymore. Thanks, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Accessing Yahoo with Python?
I realize that my question is not about the standard library. The only reason I am asking here is, if I remember correctly, a regular contributor, Danny Yoo, works at Yahoo. I am hoping he, or someone else here can help me understand what is happening. I am writing a program using the yahoo_finance module. Over the past week I have been testing and refining it. At first the only errors I was seeing were mine. Lately I have been a lot of these errors. Traceback (most recent call last): File "/usr/local/lib/python3.4/dist-packages/yahoo_finance/__init__.py", line 120, in _request _, results = response['query']['results'].popitem() KeyError: 'query' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/jfb/MyProgs/StockHistory/stock_history_oop.py", line 75, in Stocks().run() File "/home/jfb/MyProgs/StockHistory/stock_history_oop.py", line 38, in run self.get_stock_info() File "/home/jfb/MyProgs/StockHistory/stock_history_oop.py", line 53, in get_stock_info yahoo = Share(stk) File "/usr/local/lib/python3.4/dist-packages/yahoo_finance/__init__.py", line 178, in __init__ self.refresh() File "/usr/local/lib/python3.4/dist-packages/yahoo_finance/__init__.py", line 142, in refresh self.data_set = self._fetch() File "/usr/local/lib/python3.4/dist-packages/yahoo_finance/__init__.py", line 181, in _fetch data = super(Share, self)._fetch() File "/usr/local/lib/python3.4/dist-packages/yahoo_finance/__init__.py", line 134, in _fetch data = self._request(query) File "/usr/local/lib/python3.4/dist-packages/yahoo_finance/__init__.py", line 123, in _request raise YQLQueryError(response['error']['description']) yahoo_finance.YQLQueryError: Query failed with error: "'No definition found for Table yahoo.finance.quotes'". It has gotten to the point where if I run the program 10 times, 9 of them will return the above error before I get the data I want. The part of my program that retrieves the data from Yahoo has not changed in quite a while. Is it possible that I have exceeded a Yahoo limit on requests from one IP address? Test data I am using gets the historical info on 3 stocks over a 3 day period. Thanks, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] pip says no downloads for PyMedia
On 09/13/2016 04:01 PM, boB Stepp wrote: On Tue, Sep 13, 2016 at 2:17 PM, Jim Byrnes wrote: On 09/12/2016 07:59 PM, Jim Byrnes wrote: On 09/12/2016 06:06 PM, boB Stepp wrote: On Sep 10, 2016 7:20 PM, "Jim Byrnes" wrote: I am using python3 could that be the problem? I looked but couldn't find any info on what version of python is needed. I went to pymedia.org. The copyright at the bottom of the page is 2004. The "latest" news entry is February 1, 2006. So this looks to be from the Python 2 only days. I personally know nothing about PyMedia, but if 2004 should be the release date (The copyright at the bottom of their home page.), then we are looking at a version of Python prior to Py 2.4.4 which was released in October of 2006! If this is correct, then you are probably going to be unable to use PyMedia with any modern version of Python. Is there not something else more modern and compatible that can meet your needs? I am following some code in a Tkinter book I am reading. The author says he is using Windows 7 and Python 2.7.3, so I should be good with python 2.7.6. Right now I am more concerned about and trying to fix the urllib3 warnings. As a test just now I used python 2.7.3 version of pip to install pyperclip. It gave me the same urllib3 warnings as when I tried to install PyMedia, BUT it did go ahead and finish the installation. So maybe the two problems are not related but I would like to figure out and correct the urllib3 problem. Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] pip says no downloads for PyMedia
On 09/12/2016 07:59 PM, Jim Byrnes wrote: On 09/12/2016 06:06 PM, boB Stepp wrote: On Sep 10, 2016 7:20 PM, "Jim Byrnes" wrote: I am using python3 could that be the problem? I looked but couldn't find any info on what version of python is needed. I went to pymedia.org. The copyright at the bottom of the page is 2004. The "latest" news entry is February 1, 2006. So this looks to be from the Python 2 only days. boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor Thanks. I looked but did not dig as deep as you did. Regards, Jim So it looks like I need to use Python 2. On my Ubuntu 14.04 system I have vers 2.7.6. I tried that with the below result. jfb@Jims-1404:~$ pip install PyMedia Collecting PyMedia /usr/local/lib/python2.7/dist-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:318: SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform. This may cause the server to present an incorrect TLS certificate, which can cause validation failures. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#snimissingwarning. SNIMissingWarning /usr/local/lib/python2.7/dist-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:122: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. InsecurePlatformWarning Could not find a version that satisfies the requirement PyMedia (from versions: ) No matching distribution found for PyMedia jfb@Jims-1404:~$ So I went to the urllib3 address listed above. It said to do pip install urllib3[secure} to solve the problem. So I still get the errors shown above. What else do I need to do? Thanks, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] pip says no downloads for PyMedia
On 09/12/2016 06:06 PM, boB Stepp wrote: On Sep 10, 2016 7:20 PM, "Jim Byrnes" wrote: I am using python3 could that be the problem? I looked but couldn't find any info on what version of python is needed. I went to pymedia.org. The copyright at the bottom of the page is 2004. The "latest" news entry is February 1, 2006. So this looks to be from the Python 2 only days. boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor Thanks. I looked but did not dig as deep as you did. Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] pip says no downloads for PyMedia
I am working on an exercise that needs PyMedia. pypi seems to have the package but will not download it. jfb@Jims-1404:~$ pip3 search PyMedia pymediafire - A python package for MediaFire API ffmpymedia- Wrapper around the FFMPEG utility PyMedia - PyMedia is a module/library for manipulating mp3, avi, ogg, divx, mpeg, dvd media files pymedia2-pyrana - Package for simple manipulation of multimedia files pymediainfo - A Python wrapper for the mediainfo library. PyMediaRSS2Gen- A Python library for generating Media RSS 2.0 feeds. jfb@Jims-1404:~$ sudo pip3 install PyMedia [sudo] password for jfb: Downloading/unpacking PyMedia Could not find any downloads that satisfy the requirement PyMedia Cleaning up... No distributions at all found for PyMedia Storing debug log for failure in /home/jfb/.pip/pip.log jfb@Jims-1404:~$ From pip.log: /usr/bin/pip3 run on Sat Sep 10 19:04:34 2016 Downloading/unpacking PyMedia Getting page https://pypi.python.org/simple/PyMedia/ URLs to search for versions for PyMedia: * https://pypi.python.org/simple/PyMedia/ Analyzing links from page https://pypi.python.org/simple/pymedia/ Could not find any downloads that satisfy the requirement PyMedia Cleaning up... Removing temporary dir /tmp/pip_build_root... No distributions at all found for PyMedia Exception information: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/pip/basecommand.py", line 122, in main status = self.run(options, args) File "/usr/lib/python3/dist-packages/pip/commands/install.py", line 278, in run requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle) File "/usr/lib/python3/dist-packages/pip/req.py", line 1178, in prepare_files url = finder.find_requirement(req_to_install, upgrade=self.upgrade) File "/usr/lib/python3/dist-packages/pip/index.py", line 277, in find_requirement raise DistributionNotFound('No distributions at all found for %s' % req) pip.exceptions.DistributionNotFound: No distributions at all found for PyMedia I am using python3 could that be the problem? I looked but couldn't find any info on what version of python is needed. Thanks, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] tkinter/sqlite3?
On 08/26/2016 04:22 AM, Alan Gauld via Tutor wrote: On 26/08/16 02:34, Jim Byrnes wrote: Exception in Tkinter callback Traceback (most recent call last): ... File "tk_pwds.py", line 56, in fill_accounts_lb cur.execute('''SELECT Account FROM pwds WHERE Category=? ORDER BY Account COLLATE NOCASE''', category) sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 8 supplied. I cut the working statement from pythoncard and pasted it into tkinter and am curious why it works in the pythoncard version and not the tkinter version. Peter has given the solution, but just to be clear this has nothing whatsoever to do with Tkinter v Pythoncard it is entirely a Sqlite issue. (As is evidenced in the error message.) Did you use an older version of Sqlite when you wrote the Pythoncard code perhaps? You probably also used an older version of Python? The real mystery is how it worked in the Pythoncard version, unless, as Peter suggests, you just got lucky and always passed a single valued item? The pythoncard version has been in use for a while so I used a desktop launcher to started it. It wasn't until I tried to run it from a terminal to see if there were any error messages, that I realized it was using python 2.7.6 and I was working with python 3.4.3. I am guessing that the different version must have caused the problem. Finally, the string formatting solution is never a good idea for database queries since it is (a) open to injection attack and (b) liable to generate an incorrect SQL query which is hard to debug. (ie the query gets executed but returns different data to what you expected/wanted) The DB is local to my machine so I don't think I have had a problem in the past, but now that you and Peter have shown me the correct way, I will be doing it in the future. Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] tkinter/sqlite3?
On 08/26/2016 02:03 AM, Peter Otten wrote: Jim Byrnes wrote: I am working with Python 3.4.3 on Ubuntu 14.04. I am learning tkinter so I decided to rewrite a program I had written in pythoncard in tkinter. I found that a sqlite3 SELECT statement that works in pythoncard throws an error in tkinter and am wondering why? # Fill the accounts listbox from the passwords database def fill_accounts_lb(category): conn = sqlite3Connect() cur = conn.cursor() #cur.execute('''SELECT Account FROM pwds WHERE Category=? ORDER BY Account COLLATE NOCASE''', category) (1) cur.execute('''SELECT Account FROM pwds WHERE Category='%s' ORDER BY Account COLLATE NOCASE''' % category) result = [row[0] for row in cur.fetchall()] clearListbox() for account in result: lb_accounts.insert(END, account) conn.close() (1) Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python3.4/tkinter/__init__.py", line 1536, in __call__ return self.func(*args) File "tk_pwds.py", line 22, in rbCall fill_accounts_lb('WebSites') File "tk_pwds.py", line 56, in fill_accounts_lb cur.execute('''SELECT Account FROM pwds WHERE Category=? ORDER BY Account COLLATE NOCASE''', category) sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 8 supplied. I cut the working statement from pythoncard and pasted it into tkinter and am curious why it works in the pythoncard version and not the tkinter version. I'm not sure where it is coming up with the 8 bindings it said are supplied? category is probably a string with eight characters. As cursor.execute() expects a sequence as its second argument it misinterprets this string as 8 distinct arguments. If the string were of length one your code would (accidentally) work; this might have been the case in your other script. The correct fix is to put even a single value into a list or tuple: See my reply to Alan as to my guess why the pythoncard script worked. cur.execute('''SELECT Account FROM pwds WHERE Category=? ORDER BY Account COLLATE NOCASE''', [category]) If you choose the tuple remember that a one-tuple requires a trailing comma: cur.execute('''SELECT Account FROM pwds WHERE Category=? ORDER BY Account COLLATE NOCASE''', (category,)) Thanks for showing me the correct way to write that statement. Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] tkinter/sqlite3?
I am working with Python 3.4.3 on Ubuntu 14.04. I am learning tkinter so I decided to rewrite a program I had written in pythoncard in tkinter. I found that a sqlite3 SELECT statement that works in pythoncard throws an error in tkinter and am wondering why? # Fill the accounts listbox from the passwords database def fill_accounts_lb(category): conn = sqlite3Connect() cur = conn.cursor() #cur.execute('''SELECT Account FROM pwds WHERE Category=? ORDER BY Account COLLATE NOCASE''', category) (1) cur.execute('''SELECT Account FROM pwds WHERE Category='%s' ORDER BY Account COLLATE NOCASE''' % category) result = [row[0] for row in cur.fetchall()] clearListbox() for account in result: lb_accounts.insert(END, account) conn.close() (1) Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python3.4/tkinter/__init__.py", line 1536, in __call__ return self.func(*args) File "tk_pwds.py", line 22, in rbCall fill_accounts_lb('WebSites') File "tk_pwds.py", line 56, in fill_accounts_lb cur.execute('''SELECT Account FROM pwds WHERE Category=? ORDER BY Account COLLATE NOCASE''', category) sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 8 supplied. I cut the working statement from pythoncard and pasted it into tkinter and am curious why it works in the pythoncard version and not the tkinter version. I'm not sure where it is coming up with the 8 bindings it said are supplied? Thanks, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Regex/Raw String confusion
On 08/04/2016 03:27 AM, Alan Gauld via Tutor wrote: On 04/08/16 02:54, Jim Byrnes wrote: Is the second example a special case? phoneNumRegex = re.compile(r'(\(\d\d\d\)) (\d\d\d-\d\d\d\d)') I ask because it produces the same results with or without the ' r '. That's because in this specific case there are no conflicts between the regex escape codes and the Python escape codes. In other words Python does not treat '\(' or '\d' as special characters so it doesn't change the string passed to the regex. (It would be a different story if you had used, say, a '\x' or '\n' or '\b' in the regex.) In general you should proceed with caution and assume that there might be a Python escape sequence lurking in the regex and use raw just in case. Ok, thanks again. I understand what is going on now. Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Regex/Raw String confusion
On 08/03/2016 06:21 PM, Alan Gauld via Tutor wrote: On 03/08/16 20:49, Jim Byrnes wrote: Regular Expressions he talks about the python escape character being a '\' and regex using alot of backslashes. In effect there are two levels of escape character, python and the regex processor. Unfortunately they both use backslash! Python applies its level of escape first then passes the modified string to the regex engine which processes the remaining regex escapes. It is confusing and one reason you should avoid complex regexes if possible. by putting an r before the first quote of the string value, you can mark the string as a raw sting, which does not escape characters. This avoids python trying to process the escapes. The raw string is then passed to the regex which will process the backslash escapes that it recognises. A couple of pages later he talks about parentheses having special meaning in regex and what to do if they are in your text. In this case, you need to escape the ( and ) characters with a backslash. The \( and \) escape characters in the raw string passed to re.compile() will match actual parenthesis characters. These are regex escape characters. If you did not have the r in front you would need to double escape them: \\( and \\) So by using the raw string you avoid the initial layer of escaping by the python interpreter and only need to worry about the regex parser - which is more than enough for anyone to worry about! Ok thanks. The book did not mention 2 levels of escaping. With what you told me in mind I reread that section and the book may have hinted at it but I would have never realized it without knowing what you just said. Is the second example a special case? phoneNumRegex = re.compile(r'(\(\d\d\d\)) (\d\d\d-\d\d\d\d)') mo = phoneNumRegex.search('My phone number is: (415) 555-4242.') print(mo.group(1)) print() print(mo.group(2)) I ask because it produces the same results with or without the ' r '. Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Regex/Raw String confusion
I am reading Automate The Boring Stuff With Python. In the chapter on Regular Expressions he talks about the python escape character being a '\' and regex using alot of backslashes. Then he says, However, by putting an r before the first quote of the string value, you can mark the string as a raw sting, which does not escape characters. He give this example: import re phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') mo = phoneNumRegex.search('My number is 415-555-4242.') print('Phone number found: ' + mo.group()) A couple of pages later he talks about parentheses having special meaning in regex and what to do if they are in your text. In this case, you need to escape the ( and ) characters with a backslash. The \( and \) escape characters in the raw string passed to re.compile() will match actual parenthesis characters. import re phoneNumRegex = re.compile(r'(\(\d\d\d\)) (\d\d\d-\d\d\d\d)') mo = phoneNumRegex.search('My phone number is: (415) 555-4242.') print(mo.group(1)) print() print(mo.group(2)) Both examples work, but one place he says you can't escape raw strings and the other he says you can. What am I missing here? Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] OOP help needed
On 07/27/2016 04:04 AM, Alan Gauld via Tutor wrote: On 27/07/16 04:44, Jim Byrnes wrote: OOP has always driven me crazy. I read the material and follow the examples until I feel I understand them, but when I try to implement it I end up with an error filled mess. That suggests that its not the OOP concept thats confusing you but the language syntax. How to turn the concept into code? That's exactly my problem, which is why I am solving problems with OOP when it's not necessary. I wanted the practice. So I decided to give it another try. When I got to the chapter on tkinter I decided to solve all the exercises using OOP even though the book solutions did not use OOP. The first one went fine: Actually not as fine as you thought. In effect you got lucky by making a mistake that still resulted in your code doing approximately what you expected. But it didn't really do what you thought it did. import tkinter class Goodbye: def __init__(self): self.frame = tkinter.Frame(window) self.frame.pack() You are using a global variable as your parent here. It would be better to pass that in as an argument. Or better still to make the call to Tk() inside the __init__ method. That's not really an OOP thing though just a general good practice issue. It's best to avoid relying on global variables in your functions. Ok thanks. When I wrote that I was mimicking the style used in the book. I have read about avoiding globals if possible, but didn't think it through. self.goodbye_button = tkinter.Button(self.frame, text='Goodbye', #command=quit) command=lambda: quit() ) self.goodbye_button.pack() Here you assign quit to the button's command. That's OK because there is a top level built-in function called quit which exits the interpreter. It's a bit of a brutal way to exit your GUI but it works. But I guess you really wanted to call your quit method. Remember to access anything in your class you have to use the self prefix, so you should have said: command=self.quit or command=lambda: self.quit() Lambda doesn't really help in this case but it doesn't do any harm either. def quit(): self.window.destroy() When you define a method inside a class you need to explicitly include the self parameter. So this should be: def quit(self): self.window.destroy() But there's a snag, you don't store the window inside the class. So self.window will cause an error. You either need a line like self.window = window in your__init__ method or use the global window variable like def quit(): window.destroy() My preference would be to create a self.window instance variable, inside init()then access the self.window in quit(). You would also call mainloop() using self.window in your init() if __name__=='__main__': window = tkinter.Tk() myapp = Goodbye() window.mainloop() So if you took my advice this section of code would look like: if __name__=='__main__': Goodbye() and init() would look like: def __init__(self): self.window = tkinter.Tk() self.frame = tkinter.Frame(self.window) self.frame.pack() self.goodbye_button = tkinter.Button(self.frame, text='Goodbye', command=self.quit) self.goodbye_button.pack() self.window.mainloop() If you read through that and understand it, it should give you the clues as to why the second one behaved as it did. Ok thanks. I don't want to belabor the point but I basically had it that way because I didn't know any better. Now I know of a different/better way to do it. Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] OOP help needed
On 07/27/2016 03:12 AM, Peter Otten wrote: Jim Byrnes wrote: OOP has always driven me crazy. I read the material and follow the examples until I feel I understand them, but when I try to implement it I end up with an error filled mess. So I decided to give it another try. When I got to the chapter on tkinter I decided to solve all the exercises using OOP even though the book solutions did not use OOP. The first one went fine: No, it didn't. The Goodbye.quit() method is missing the self argument and uses the inexistent self.window attribute. You don't see these bugs when you run the script because there is a global quit()... let's say function... that is called instead of the method. You can put a print() into Goodbye.quit() to verify the above. OK right. I ended up concentrating on exer2 when the problem was in exer1. I should have known better than using quit() as a name. #exer1.py import tkinter class Goodbye: def __init__(self): self.frame = tkinter.Frame(window) self.frame.pack() self.goodbye_button = tkinter.Button(self.frame, text='Goodbye', #command=quit) command=lambda: quit() ) The lambda is superfluous -- command=quit will already invoke the global quit(). But what you actually intended is achieved with command=self.quit. self.quit is called "bound method". Ok, thanks. self.goodbye_button.pack() def quit(): print("you'll never see this") self.window.destroy() if __name__=='__main__': window = tkinter.Tk() myapp = Goodbye() window.mainloop() Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] OOP help needed
On 07/26/2016 11:38 PM, Ben Finney wrote: Jim Byrnes writes: So I decided to give it another try. When I got to the chapter on tkinter I decided to solve all the exercises using OOP even though the book solutions did not use OOP. Hmm, that sounds ill advised. OOP is one tool among many; trying to apply it where it's a poor fit will result in bad design and probably avoidable errors. When learning to use a hacksaw, trying to solve everything using that tool merely to learn it, would be a poor choice. With anything more complex I would agree. I am simply trying to get myself thinking about how OOP works and there aren't enough exercises in the book calling for OOP to give me much repetition. # exer2.py import tkinter class Count: def __init__(self): ''' Increment a button labeled 0, by 1 with each click ''' […] self.count_btn = tkinter.Button(self.frame, textvariable=self.label, command=lambda: self.increment(self.label )) Here you address the ‘self.increment’ name, which should work. def increment(self, label): count = int(self.label.get()) self.label.set(str(count + 1)) This is the method that an instance will address via ‘self.increment’. In exer2.py if I do command=lambda: increment(self.label) The lambda expression creates a function, and that function then behaves like any other function. Within that function, the name ‘increment’ is not defined; within the scope where the function was defined, the name ‘increment’ is also not defined. Within the global scope the name ‘increment’ is not defined. So yes, you'll get NameError from that code. Why do I get this error? The situations look the same to me The difference is that when you invoke ‘self.instance’, the lookup of ‘self’ succeeds because it's defined within the function (you defined it in the parameters of ‘__init__’, so ‘__init__’ knows that name when it is running). You never defined the name ‘increment’ within the function, nor within the global scope. And you shouldn't because there's no need: you access the instance's own method by accessing the instance first: you ask for “the ‘instance’ attribute from the ‘self’ object”: ‘self.instance’. OK thank you. Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] OOP help needed
OOP has always driven me crazy. I read the material and follow the examples until I feel I understand them, but when I try to implement it I end up with an error filled mess. So I decided to give it another try. When I got to the chapter on tkinter I decided to solve all the exercises using OOP even though the book solutions did not use OOP. The first one went fine: #exer1.py import tkinter class Goodbye: def __init__(self): self.frame = tkinter.Frame(window) self.frame.pack() self.goodbye_button = tkinter.Button(self.frame, text='Goodbye', #command=quit) command=lambda: quit() ) self.goodbye_button.pack() def quit(): self.window.destroy() if __name__=='__main__': window = tkinter.Tk() myapp = Goodbye() window.mainloop() The second one was more trouble but I finally got it to work. # exer2.py import tkinter class Count: def __init__(self): ''' Increment a button labeled 0, by 1 with each click ''' self.frame = tkinter.Frame(window) self.frame.pack() self.label = tkinter.StringVar() self.label.set('0') self.count_btn = tkinter.Button(self.frame, textvariable=self.label, command=lambda: self.increment(self.label )) self.count_btn.pack() def increment(self, label): count = int(self.label.get()) self.label.set(str(count + 1)) if __name__ == '__main__': window = tkinter.Tk() myapp = Count() window.mainloop() I am having trouble understanding the difference between the two lines that contain lambda: command= .In exer1.py I can do command=lambda: quit(). In exer2.py if I do command=lambda: increment(self.label) I get this error: Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python3.4/tkinter/__init__.py", line 1536, in __call__ return self.func(*args) File "exer2.py", line 14, in command=lambda: increment(self.label )) NameError: name 'increment' is not defined Why do I get this error? The situations look the same to me but they must be different somehow and I just don't see the difference. Thanks, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Variable in tkinter?
On 07/24/2016 02:08 PM, Alan Gauld via Tutor wrote: On 23/07/16 16:38, Jim Byrnes wrote: # the views frame = tkinter.Frame(window) frame.pack() button = tkinter.Button(frame, text='Up', command=click_up) button.pack() button = tkinter.Button(frame, text='Down', command=click_down) button.pack() that is wrong because the program does work. Could someone explain to me why it works? Others have pointed out that a hidden reference to the buttons exists. In fact Tkinter, in common with most GUIIs, works by building a tree of objects starting at the top level window and then working down thru' each lower level. Usuially in Tkinter we start with a line like top = tkinter.Tk() # create the topmost widget Then when we create subwidgets, like your frame we pass the outer widget as the parent: frame = tkinter.Frame(top) Then when you create the buttons you pass frame as the first argument which makes frame the parent of the buttons. What happens is that when you create the widget the parent object adds your new instance to its list of child widgets. And that's the hidden reference that keeps your button alive even after you overwrite the button variable. You can access the widget tree of any widget using its 'children' attribute: import tkinter as tk top = tk.Tk() f = tk.Frame(top) f.pack() tk.Label(f,text="Hello there!").pack() f.children {'140411123026128': } But it's not very user friendly so if you need to access a widget after creating it its better to use a unique variable to store a reference. Thanks Peter and Alan, After I proved to myself that it worked and I thought about it, I suspected it had to do with a reference. It's nice to have it confirmed is such a clear manner. Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Variable in tkinter?
I have been working my way through a Python 3 book and got to the chapter on tkinter. The following is a segment of a example program that works: # the views frame = tkinter.Frame(window) frame.pack() button = tkinter.Button(frame, text='Up', command=click_up) button.pack() button = tkinter.Button(frame, text='Down', command=click_down) button.pack() label = tkinter.Label(frame, textvariable=counter) label.pack() when I first looked at it I thought it would not work, thinking that the second reference to button = would over write the first one. Obviously that is wrong because the program does work. Could someone explain to me why it works? Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Using python 3 on Ubuntu 14.04
On 12/24/2015 04:03 PM, Ben Finney wrote: Jim Byrnes writes: Thanks for all the info guys. I got myself confused because I thought that python 3 was the default for Ubuntu 14.04, but it is just installed by default. Even if that were true, the ‘python’ command will likely still invoke a Python 2 interpreter. Most systems that install a Python 3 interpreter will install the command as ‘python3’. Misunderstanding that was also part of my confusion. I realize now that the modules need to be installed in the proper environment. That also remains true when Python 3 is the default. I realize that now. I know Pythoncard is not maintained any more. I have one program I wrote using it that I use often so I wanted to see it worked on 14.04. It will be a good learning experience to rewrite it for python 3 using something else. Have you considered using Python 3 and the standard Tkinter tookit? https://docs.python.org/3/library/tkinter.html> https://docs.python.org/3/library/tkinter.ttk.html> http://www.tkdocs.com/> Yes, that is something I plan to look at once I get 14.04 all set up the way I want and it becomes my default system. Thanks, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Using python 3 on Ubuntu 14.04
On 12/23/2015 07:52 PM, Alan Gauld wrote: On 23/12/15 23:15, Nnamdi Anyanwu wrote: If you're installing modules with pip, install pip3 and install the appropriate modules using pip3 instead of using regular pip. Most v3 modules are also available via the Ubuntu package system so you can install via synaptic which I tend to find more reliable than pip. YMMV, Thanks for all the info guys. I got myself confused because I thought that python 3 was the default for Ubuntu 14.04, but it is just installed by default. I realize now that the modules need to be installed in the proper environment. I know Pythoncard is not maintained any more. I have one program I wrote using it that I use often so I wanted to see it worked on 14.04. It will be a good learning experience to rewrite it for python 3 using something else. Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] OT: How to automate user interactions with GUI elements of closed-source programs?
On 12/24/2015 08:54 AM, boB Stepp wrote: My Google-fu is weak on this question. I keep getting lots of hits on web scraping, but my interest is actually as follows: I find myself doing the same boring, repetitive tasks by hand, which amounts to copying certain information from one program and putting it into other programs. None of these programs, to my knowledge, have a publicly accessible API. Are there ways to programmatically accurately click the right buttons (or check boxes, radio buttons, etc.), copy desired fields and then switch to another program and paste the desired information into the desired fields, accurately clicking all things that need to be clicked, etc.? This is mostly a Windows-based scenario, but if the techniques (if they exist) can be abstracted to any OS I can find plenty of uses elsewhere as well! TIA! Merry Christmas!!! I don't know if there is a Python solution, as I am just starting to read up on using Python on the web. Either iMarcos or GreaseMonkey could probably do what you what you want. Both are browser extensions. iMacros is available for both Firefox and Chrome, GreaseMonkey is available for Firefox, but I'm not sure about Chrome. Both also have user forums. Regards, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Using python 3 on Ubuntu 14.04
I am in the process of moving from unbutu 12.04 to 14.04. I was doing some testing and got this: jfb@Jims-1404:~$ cd MyProgs jfb@Jims-1404:~/MyProgs$ cd passwords jfb@Jims-1404:~/MyProgs/passwords$ python3 passwords.py Traceback (most recent call last): File "passwords.py", line 8, in from PythonCard import model,clipboard ImportError: No module named 'PythonCard' If I simply start it with python passwords.py it runs fine. There is no need to use python 3 on this particular program but if I wanted to write for python 3 in the future what do I need to do to run programs with it? Thanks, Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Calculation error with a simple program
Hi Alan, I'm 100 percent sure I'm wrong. :-) I verified it when I fixed the mistake. The problem was it was adding in the basePrice and the fixed rates/percentages each time. So I figured it out when Ian said something about that. Thanks for everyone's help! :-) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Calculation error with a simple program
Hi everyone. I'm reading through a beginners Python book and came up with a super simple program. I'm not getting any errors and everything runs through, but there's a logical calculation error. What the program does is take an amount and calculate a couple percentages and add a couple fees. For example, if I put in a value of 1, it will output 752.12 as the sub total and 753.12 as the grand total. It's off by 1 on sub total and 2 on grand total. Thanks in advance! Jim Gallaher # Car Salesman Calculator # User enters the base price of the car and the program adds tax, license, dealer prep, and destination charge. print("Car Sales Calculator") basePrice = int(input("Please enter in the price of the car: ")) # Misc charges to be added to the total cost of the car tax = basePrice * .07 license = basePrice * .05 dealerPrep = basePrice + 500 destinationCharge = basePrice + 250 # Add the total misc charges together subTotal = float(tax + license + dealerPrep + destinationCharge) # Add all the misic charges and include the base price grandTotal = float(subTotal + basePrice) # Display the results print("\nThe sub total is", subTotal) print("\nYour grand Total is", grandTotal) input("\nPress the enter key to close the program.") ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] method conflict?
Okay, it appears the method in a class has its own ID, but all instantiations of that method have identical IDs. But what happens if we have a huge number of instantiations trying to access the identical method at the same time? class MyClass: def setdata(self, data): self.data = data def getdata(self): print(self.data) >>> MyClass.setdata >>> id(MyClass.setdata) 40676568 >>> f = MyClass() >>> g = MyClass() >>> id(f.setdata) 43576616 >>> id(g.setdata) 43576616 >>> d = MyClass() >>> id(d.setdata) 43576616 -- Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Are the methods in a class copied or just linked to?
When an instance uses a class method, does it actually use the method that is in the class object's memory space, or is the method copied to the instance? -- Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Is there a way to use "with" across suite boundaries?
'''I was using with open...:, but I'm printing a header in one function, calling a looping function to print detail lines, then returning to the calling function to print the footer. But that didn't work since the with statement only seems to work with the lexical suite and the file wasn't open in the detail print function. Is there a way around this, other than passing the file as I have here? Also, is it a good idea to pass a file handle like that or is there a better way? Using the below csv file co2-sample.csv to print a simple HTML table (header omitted) Since this is a file there are enclosing single quotes not visible: "ANTIGUA AND BARBUDA",0,0,0,0,0 "ARGENTINA",37,35,33,36,39 "BAHAMAS, THE",1,1,1,1,1 "BAHRAIN",5,6,6,6,6 "SPANISH INQUISITION, THE, SILLY",10,33,14,2,8 Program follows (py3.4, winxp):''' htbegin = ''' htest table, td {border:2px solid black; border-collapse:collapse;} td {padding:3px; background-color:pink; text-align:right;font-family:verdana;} td.l {text-align:left} ''' htend = ''' ''' def make_lines(): co2 = open('co2-sample.csv') ht = open('output.html', 'w') linelist = [] print(htbegin, file=ht) for line in co2: newlist = line.rsplit(',', 5) # ending is regular so split it out first for token in newlist: # since split char inside quotes for nation is problematic linelist.append(token.strip('"')) # get rid of extra quotes linelist[-1] = linelist[-1].strip() fprint(linelist, ht) linelist = [] co2.close() print(htend, file=ht) ht.close() def fprint(linelist, ht): # size formatting irrelevant for HTML formatted_string = "{}{}{}{}{}{}".format(*linelist) print(formatted_string, file=ht) print('', file=ht) if __name__ == "__main__": make_lines() -- Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Getting import to use a variable name
On 20 May 2015 at 01:02, Peter Otten <__pete...@web.de> wrote: > If you start with an object dir() gives you a list of attribute names. To > get the actual attributes use > > attribute = getattr(object, attribute_name) > > Then print the attributes' docstring with > > print(attribute_name, attribute.__doc__) > Thanks. That will save a lot of scrolling - and saving scrolling and typing is half the battle ;') -- Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Getting import to use a variable name
On 19 May 2015 at 17:25, Jim Mooney Py3.4.3winXP wrote: > > If I can get dir to accept x I can parse the output to get rid of the > __xxx stuff and print it out. > By that I mean dir will give me a list of strings I can then use __doc__ on to get all useful help items. -- Jim After not doing dishes for a week and washing spoon after spoon, fork after fork, knife after knife - I suddenly understand the mathematical concept of infinity, which is just one more damn thing after another. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Getting import to use a variable name
On 19 May 2015 at 17:18, Ben Finney wrote: > You will be pleased to know of the standard library ‘importlib’ > library:: > > >>> import importlib > Yes, I already got importlib to accept a string. But I can't figure how to get dir to accept it: >>> x = 'shutil' >>> import importlib >>> importlib.__import__(x) >>> If I can get dir to accept x I can parse the output to get rid of the __xxx stuff and print it out. -- Jim After not doing dishes for a week and washing spoon after spoon, fork after fork, knife after knife - I suddenly understand the mathematical concept of infinity, which is just one more damn thing after another. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Getting import to use a variable name
I use python help() a good deal but get tired of paging through the __object__ stuff to get to what I use at my level, so I wrote the following to omit it. The problem is, I want to import it then use it as shorthelp.py for different modules so I could just type shorthelp(modulename). Only the import mechanism won't let me rename. I can only use the hardcoded imported module name, shutil in this case. If I try x = anothermodule, then import x, it doesn't work. import sys.argv[1] also doesn't work. Is there any way to get around this? I'm mostly interested in doing this from the repl rather than running from the console. Py3.4 win32 import shutil #this works to print non __xxx helpstrings for a module, but I can't substitute it. useful_helps = [] helps = dir(shutil) for helper in helps: if helper[0] == '_': continue useful_helps.append(helper) for helper in useful_helps: print(helper.upper() + ':', helper.__doc__, '\n') -- Jim After not doing dishes for a week and washing spoon after spoon, fork after fork, knife after knife - I suddenly understand the mathematical concept of infinity, which is just one more damn thing after another. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Terminology question
On 15 May 2015 at 22:45, Steven D'Aprano wrote: > > What does "didn't work" mean? Did your computer crash? Catch fire? A > completely different error got printed? Something else? I can see I was marvelously unclear ;') Here is what I meant. def make_error(): raise ZeroDivisionError('Here I am') def call_error(): try: make_error() except: print("How do I get the 'Here I am' message to print in the calling routine?") >>> call_error() How do I get the 'Here I am' message to print in the calling routine? -- Jim "What a rotten, failed experiment. I'll start over. Maybe dogs instead of monkeys this time." --God ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Terminology question
On 14 May 2015 at 16:47, Alan Gauld wrote: > Rather than printing the messages you could re-raise > the error but with the error message attached as a string. > I'm a little unclear how you catch the string you create in a raise, in the caller. I tried an example from the docs but it didn't work. Could you provide a simple example? Sometimes the docs are heavy slogging if you don't already know what's what ;') -- Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Terminology question
I noticed that if I call a function that throws an error, I can catch it from the caller, instead of catching it in the function. Is this is what is known as "errors bubbling up?" Also, is this how you're supposed to do it? *** Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit (Intel)] on win32. *** '''Print a table of random numbers, given min, max, rows, and columns''' from random import randint def make_table(minimum, maximum, rows, columns): for row in range(rows): print() for column in range(columns): print(randint(minimum, maximum), end = ' ') def get_input(): inp = input("Enter minimum, maximum, rows, and columns, separated by commas: ") inps = inp.split(',') try: minimum = int(inps[0]) maximum = int(inps[1]) rows = int(inps[2]) columns = int(inps[3]) return minimum, maximum, rows, columns except ValueError as err: print("non-integer entered", err) return None except IndexError as err: print("You didn't enter enough values.", err) return None vals = get_input() if vals: minimum, maximum, rows, columns = vals try: make_table(minimum, maximum, rows, columns) except ValueError as err: # CATCH FUNCTION ERROR HERE INSTEAD OF IN FUNCTION print("Enter min before max.") else: print('Nothing to do.') -- Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] pointer puzzlement
On 7 May 2015 at 18:42, Dave Angel wrote: > Python doesn't have pointers So what is the difference between a python name and a pointer? I'm a bit fuzzy on that. -- Jim "What a rotten, failed experiment. I'll start over. Maybe dogs instead of monkeys this time." --God ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] pointer puzzlement
On 7 May 2015 at 13:03, Emile van Sebille wrote: > Compare to: > > def testid(K=100): > K += 10 > return 'the ID is', id(K), K > Ah, thanks. I forgot small integers are saved in a table. I was looking at a demo that pointers to defaults in function parameters are persistent. It used lists so I tried ints. Although I realized persistence also works for dicts ;') def testid(newitem, K={}): K[newitem] = newitem + 'item' return 'the ID is', id(K), K >>> testid('bonk') ('the ID is', 18263656, {'bonk': 'bonkitem'}) >>> testid('clonk') ('the ID is', 18263656, {'bonk': 'bonkitem', 'clonk': 'clonkitem'}) >>> testid('spam') ('the ID is', 18263656, {'bonk': 'bonkitem', 'clonk': 'clonkitem', 'spam': 'spamitem'}) -- Jim "What a rotten, failed experiment. I'll start over. Maybe dogs instead of monkeys this time." --God ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] pointer puzzlement
I find this a bit confusing. Since the ID of K remains the same, so it's the same object, why isn't it increasing each time. i.e, 20, 30, 40,. I understand that it's immutable but doesn't that mean K is created each time in local scope so it should have a different ID each time? def testid(K=10): K += 10 return 'the ID is', id(K), K *** Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit (Intel)] on win32. *** >>> testid() ('the ID is', 505991936, 20) >>> testid() ('the ID is', 505991936, 20) >>> testid() ('the ID is', 505991936, 20) >>> -- Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] key detection
On 6 May 2015 at 14:08, Dave Angel wrote: > I don't know why you would be expecting to get a utf-8 character for the > second byte of a function key code. It's an entirely arbitrary byte > sequence, and not equivalent to anything in Unicode, encoded or not I just didn't think of accounting for function keys until I hit one - experimental learning. The program I'm working on doesn't require F keys, but I tried one just to see what would happen ;') It's worth making the error to reinforce unicode in my head. One item - once I dropped decoding for special keys, some were printed as hex codes but some as letters. i.e. F11 was b'\x85', but F9 and F10 were b'C' and b'D', so I assume the second byte of some function keys just happens to map to utf-8 letters. Sure enough, when I put in decoding again, F9 and F10 second bytes printed as C and D, but the program bailed on F11. -- Jim "What a rotten, failed experiment. I'll start over. Maybe dogs instead of monkeys this time." --God ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] key detection
On 6 May 2015 at 10:41, Jim Mooney Py3.4.3winXP wrote: > I went a further step from the recipes linked to above and got here >> https://pypi.python.org/pypi/readchar > > > I think that's the one that failed for me > Addendum. That only failed in python 3.4. It worked fine in python 2.7 - but I rarely use that. -- Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] key detection
On 5 May 2015 at 21:51, Mark Lawrence wrote: > On 06/05/2015 05:30, Jim Mooney Py3.4.3winXP wrote: > >> On 5 May 2015 at 18:32, Steven D'Aprano wrote: >> >> https://code.activestate.com/recipes/577977-get-single-keypress/ >>> >> >> >> That only has a stub for Linux, but I found one that does both. Although, >> alas, no IOS version: >> >> >> http://code.activestate.com/recipes/134892-getch-like-unbuffered-character-reading-from-stdin/ >> >> Anyway, I set up msvcrt for now until I install linux - I'm not interested >> in the program I mentioned, per se, just the error message - mainly to >> know, generally, what sort of thing it's choking on. Errors are useful to >> know. >> >> > I went a further step from the recipes linked to above and got here > https://pypi.python.org/pypi/readchar I think that's the one that failed for me but I found out why. I just wrote the simple snippet below to try msvcrt out. I can add a Linux try block when I install Linux and actually find a wifi driver for it ;') I reproduced the error that puzzled me almost immediately. It was from hitting a function key. The snippet below worked fine for letters and such, but died when I hit a function key (although not all of them). I was decoding since msvcrt sends byte strings, but there was nothing in the utf-8 map for that key. The 2> redirect is sure handy for dos console error messages - something I'll have to remember ;') from msvcrt import * while True: if kbhit(): key = getch() if key == b'\xe0' or key == b'\000': print('special key follows') key = getch() print(str(key, encoding='utf-8')) #got rid of this decode after a function key error else: print('The key is: ', str(key, encoding='utf-8')) Traceback (most recent call last): File "keyget.py", line 9, in print(str(key, encoding='utf-8')) UnicodeDecodeError: 'utf-8' codec can't decode byte 0x85 in position 0: invalid start byte -- Jim "What a rotten, failed experiment. I'll start over. Maybe dogs instead of monkeys this time." --God ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] key detection
On 5 May 2015 at 18:32, Steven D'Aprano wrote: > https://code.activestate.com/recipes/577977-get-single-keypress/ That only has a stub for Linux, but I found one that does both. Although, alas, no IOS version: http://code.activestate.com/recipes/134892-getch-like-unbuffered-character-reading-from-stdin/ Anyway, I set up msvcrt for now until I install linux - I'm not interested in the program I mentioned, per se, just the error message - mainly to know, generally, what sort of thing it's choking on. Errors are useful to know. -- Jim ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] key detection
On 5 May 2015 at 18:35, Steven D'Aprano wrote: > Is this under Linux or another Unix? If so, > only redirects stdout, not > stderr, so you need: > > python3 setup.py 2> errors.txt > > to capture the errors. > > I have no idea if Windows works the same way. > Damn, that actually worked in windows instead of using their awful screen copy. What a surprise: errors.txt Traceback (most recent call last): File "setup.py", line 39, in long_description=read_description(), File "setup.py", line 11, in read_description return fd.read() File "c:\python34\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 2468: character maps to -- Jim "What a rotten, failed experiment. I'll start over. Maybe dogs instead of monkeys this time." --God ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor