ttk.Notebook Tabs Question
I am working on a program that has a ttk.Notebook with 12 tabs. Is there a way to determine the total width of the tabs in pixels. Just to be clear I am not talking about width of the nb container. I am talking about tabs themselves that contain the text. I want the program to be resizable but I don't want to allow the window width to fall below that of the tabs which would hide them. Since I can find no way to have more than one row of tabs, this appears to be my only option. Any suggestions would be appreciated. -- GNU/Linux user #557453 May the Source be with you. -- https://mail.python.org/mailman/listinfo/python-list
Re: ttk.Notebook Tabs Question
On Fri, 15 Sep 2017 06:09:21 +0400, Abdur-Rahmaan Janhangeer wrote: > try > widget["width"] it returns string > then mult by no. of tabs Since the tabs are displaying text, I believe the width would be returned as characters or letters like a Button or Text widget. I need pixels. Another problem is that the tabs are different widths. I am going to experiment with the possibility of using images in place of the text. Then I believe the width would be returned in pixels. Thanks for the reply. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: ttk.Notebook Tabs Question
On Fri, 15 Sep 2017 20:45:20 +0100, MRAB wrote: > On 2017-09-15 16:24, Wildman via Python-list wrote: >> On Fri, 15 Sep 2017 06:09:21 +0400, Abdur-Rahmaan Janhangeer wrote: >> >>> try >>> widget["width"] it returns string >>> then mult by no. of tabs >> >> Since the tabs are displaying text, I believe the width >> would be returned as characters or letters like a Button >> or Text widget. I need pixels. >> > Why assume that the width is returned as characters? Why not try it? If I set the width of the tabs, the width is in characters so I expected it to be the same. style = ttk.Style() style.theme_create( "MyStyle", parent="alt", settings={ "TNotebook": {"configure": {"tabmargins": [2, 5, 2, 0] } }, "TNotebook.Tab": {"configure": {"padding": [0,0], "width": [7]}, }}) style.theme_use("MyStyle") Also, I tried "widget["width"] and it returns 0. Same for height. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: ttk.Notebook Tabs Question
On Sun, 17 Sep 2017 08:45:27 +0400, Abdur-Rahmaan Janhangeer wrote: > by widget["width"] i meant replace widget with your widget Yes, that is what I did. It returned 0. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: error from Popen only when run from cron
On Sat, 27 Jan 2018 10:58:36 -0500, Larry Martell wrote: > I have a script that does this: > > subprocess.Popen(['service', 'some_service', 'status'], > stdout=subprocess.PIPE, stderr=subprocess.STDOUT) > > When I run it from the command line it works fine. When I run it from > cron I get: > > subprocess.Popen(['service', 'some_service', 'status'], > stdout=subprocess.PIPE, stderr=subprocess.STDOUT) > File "/usr/lib64/python2.7/subprocess.py", line 711, in __init__ > errread, errwrite) > File "/usr/lib64/python2.7/subprocess.py", line 1327, in _execute_child > raise child_exception > OSError: [Errno 2] No such file or directory > > Anyone have any clue as to what file it's complaining about? Or how I > can debug this further? Cron provides this as $PATH: /usr/bin;/usr/sbin >From within a terminal enter: whereis service If service is not in Cron's $PATH, that is your problem. Adding the complete path to 'service' in the script should fix things. If service is in Cron's $PATH, I have no further ideas. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: Where has the practice of sending screen shots as source code come from?
On Sun, 28 Jan 2018 15:04:26 +, Steven D'Aprano wrote: > I'm seeing this annoying practice more and more often. Even for trivial > pieces of text, a few lines, people post screenshots instead of copying > the code. > > Where has this meme come from? It seems to be one which inconveniences > *everyone* involved: > > - for the sender, instead of a simple copy and paste, they have to take a > screen shot, possibly trim the image to remove any bits of the screen > they don't want to show, attach it to their email or upload it to an > image hosting site; > > - for the receiver, you are reliant on a forum which doesn't strip > attachments, or displays externally hosted images; the visually impaired > are excluded from using a screen reader; and nobody can copy or edit the > given text. > > It is as if people are deliberately inconveniencing themselves in order > to inconvenience the people they are asking to help them. > > With the exception of one *exceedingly* overrated advantage, namely the > ability to annotate the image with coloured lines and circles and > squiggles or other graphics (which most people don't bother to do), this > seems to me to be 100% counter-productive for everyone involved. Why has > it spread and why do people keep doing it? > > I don't want to be the old man yelling "Get Of My Lawn!" to the cool > kids, but is this just another sign of the downward spiral of programming > talent? Convince me that there is *some* justification for this practice. > Even a tiny one. > > (The day a programmer posts a WAV file of themselves reading their code > out aloud, is the day I turn my modem off and leave the internet forever.) I can think of no justification for it. -- GNU/Linux user #557453 May the Source be with you. -- https://mail.python.org/mailman/listinfo/python-list
Python 2 to 3 Conversion
I have a bit of code I found on the web that will return the ip address of the named network interface. The code is for Python 2 and it runs fine. But, I want to use the code with Python 3. Below is the code followed by the error message. Suggestions appreciated. #!/usr/bin/env python3 import socket import fcntl import struct def get_ip_address(ifname): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl( s.fileno(), 0x8915, # SIOCGIFADDR struct.pack('256s', ifname[:15]) )[20:24]) print(get_ip_address("eth0")) print(get_ip_address("lo")) Traceback (most recent call last): File "./test.py", line 14, in print(get_ip_address("eth0")) File "./test.py", line 12, in get_ip_address struct.pack('256s', ifname[:15]) struct.error: argument for 's' must be a bytes object -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: Python 2 to 3 Conversion
Thanks to Chris and Ben. Your suggestions were slightly different but both worked equally well, although I don't understand how that can be so. > struct.pack('256s', ifname[:15].encode('ascii')) > struct.pack('256s', ifname.encode('ascii')) I was looking for a reliable way to determine the IP addy for a given network adapter. That is what the code does but I don't understand how it does it either. Thanks again. I will continue to research and study the code in the hope I will understand it. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: Python 2 to 3 Conversion
On Sun, 18 Feb 2018 20:51:18 +1100, Chris Angelico wrote: > On Sun, Feb 18, 2018 at 4:35 AM, Wildman via Python-list > wrote: >> Thanks to Chris and Ben. Your suggestions were slightly >> different but both worked equally well, although I don't >> understand how that can be so. >> >>> struct.pack('256s', ifname[:15].encode('ascii')) >>> struct.pack('256s', ifname.encode('ascii')) > > Those two will be identical for short interface names, but the first > form will truncate a longer name before encoding. I don't know what > the ioctl will do with a really long ifname, so it's probably worth > hanging onto the [:15] slicing. Since the interfaces are named by the (Linux) system, I don't think long interface names will be a problem. Names are used like lo, eth0, wlan0, ppp0, vmnet8, etc. But, I will keep the [:15} slicing just in case. >> I was looking for a reliable way to determine the IP addy >> for a given network adapter. That is what the code does >> but I don't understand how it does it either. >> >> Thanks again. I will continue to research and study the >> code in the hope I will understand it. > > Ah, makes sense. I'd probably do something like this: > >>>> import socket >>>> s = socket.socket(type=socket.SOCK_DGRAM) >>>> s.connect(("8.8.8.8", 53)) >>>> s.getsockname()[0] > '192.168.0.19' Brief background... I am working on a project that reports Linux system info and lan is part of it. To start with I was using code similar to the above but, with the help of a few testers in some of the Linux newsgroups, I found it did not work correctly in all situations such as 'live' sessions. So I started looking for an alternative. > But that's only going to show one (uplink) address. If I needed to get > ALL addresses for ALL network adapters, I'd either look for a library, > and if one wasn't easily found, I'd shell out to the "ip" command and > parse its output. :) > > ChrisA I considered using the "ip" command but I prefer not to depend on external programs if I can get around it. I know that might be considered silly but that's just me. Thanks for your input. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: Python 2 to 3 Conversion
On Mon, 19 Feb 2018 12:32:49 +, Rhodri James wrote: > On 18/02/18 16:18, Wildman via Python-list wrote: >>> But that's only going to show one (uplink) address. If I needed to get >>> ALL addresses for ALL network adapters, I'd either look for a library, >>> and if one wasn't easily found, I'd shell out to the "ip" command and >>> parse its output.:) >>> >> I considered using the "ip" command but I prefer not to >> depend on external programs if I can get around it. I >> know that might be considered silly but that's just me. > > It's not silly at all, but for Linux networking it might be the best > idea. I believe in theory you are supposed to use libnl (in some > suitable wrapping), but my experience with that is that it is badly > documented and horrendously unreliable. It looks like libnl would do what I want but there is a problem. When finished, my program will be released in the form of a Debian (*.deb) package and used by, for the most part, 'average' Linux users. These are people that know their way around Linux but know nothing or very little about Python. Installing a package using pip by them is pretty much out of the question. The system's package manager must be able to handle the program's dependencies so third-party packages are out of the question. But thanks for the suggestion. -- GNU/Linux user #557453 "There are only 10 types of people in the world... those who understand Binary... and those who don't." -Spike -- https://mail.python.org/mailman/listinfo/python-list
Re: Python 2 to 3 Conversion
On Tue, 20 Feb 2018 02:26:19 +1100, Chris Angelico wrote: > * Opaque IOCTLs Would you mind to elaborate a little about your concerns? -- GNU/Linux user #557453 "There are only 10 types of people in the world... those who understand Binary... and those who don't." -Spike -- https://mail.python.org/mailman/listinfo/python-list
Re: Python 2 to 3 Conversion
On Tue, 20 Feb 2018 05:39:15 +1100, Chris Angelico wrote: > On Tue, Feb 20, 2018 at 3:53 AM, Wildman via Python-list > wrote: >> On Tue, 20 Feb 2018 02:26:19 +1100, Chris Angelico wrote: >> >>> * Opaque IOCTLs >> >> Would you mind to elaborate a little about your >> concerns? > > Look at your original code: it's impossible to figure out what it's > doing or whether it's doing it correctly. "Opaque" in this context > means that you can't grok the code without external help. This is a > code smell, and a strong indication that you're "fiddling" in stuff > way lower level than you normally want to be working with. It's > usable, but it's dirty and leaves everything up to you (do you know > for sure, for instance, if this is backward compatible? > Cross-platform?), and that makes it comparable to depending on an > external program. > > ChrisA I understand and I agree for the most part. It does concern me that I don't understand the code. Anytime in Linux you start poking around things at kernel level, you need your eyes to be wide open. However, to me it looks like the code is only quarying ioctl and not trying to change any- thing. If this is true, there is no problem. For the issue of backward compatibility, there are good people on a few of the Linux newsgroups that are willing to test code snippets for me. I can get a wide range of distros, desktops and kernel versions. And of course different python3 versions. I know it is impossible to write code that will be guaranteed to run on all conditions. But the test results I get will or should let me know right off if there are glaring problems. As far as cross-platform goes, that is not an issue. Every thing I do is targeted for the Linux platform. I will keep "ip" in mind as a backup plan. As a novice Python programmer, I am looking at the amount of code it will take to parse ip's output compared to the few lines of code it takes to call ioctl. I really appreciate your insight. Thank you. -- GNU/Linux user #557453 "There are only 10 types of people in the world... those who understand Binary... and those who don't." -Spike -- https://mail.python.org/mailman/listinfo/python-list
Re: Python 2 to 3 Conversion
On Tue, 20 Feb 2018 05:31:27 +1100, Chris Angelico wrote: > On Tue, Feb 20, 2018 at 3:49 AM, Wildman via Python-list > wrote: >> On Mon, 19 Feb 2018 12:32:49 +, Rhodri James wrote: >> >>> On 18/02/18 16:18, Wildman via Python-list wrote: >>>>> But that's only going to show one (uplink) address. If I needed to get >>>>> ALL addresses for ALL network adapters, I'd either look for a library, >>>>> and if one wasn't easily found, I'd shell out to the "ip" command and >>>>> parse its output.:) >>>>> >>>> I considered using the "ip" command but I prefer not to >>>> depend on external programs if I can get around it. I >>>> know that might be considered silly but that's just me. >>> >>> It's not silly at all, but for Linux networking it might be the best >>> idea. I believe in theory you are supposed to use libnl (in some >>> suitable wrapping), but my experience with that is that it is badly >>> documented and horrendously unreliable. >> >> It looks like libnl would do what I want but there is >> a problem. When finished, my program will be released >> in the form of a Debian (*.deb) package and used by, >> for the most part, 'average' Linux users. These are >> people that know their way around Linux but know >> nothing or very little about Python. Installing a >> package using pip by them is pretty much out of the >> question. The system's package manager must be able >> to handle the program's dependencies so third-party >> packages are out of the question. >> >> But thanks for the suggestion. > > If you're distributing it as a .deb, you don't want to use pip to grab > additional libraries. Ideally, you'd want the library to *also* be > available through the package manager, which would mean you can simply > record it as a dependency. If it's not... it's not gonna be easy. > > ChrisA Yes, you are correct. Third-party pip packages are always a no-no. Speaking of which, there is a library called Netifaces that will easily do exactly what I want with a few lines of code. But, it is not to be found in any Linux distro's repository that I can find. Oh well... -- GNU/Linux user #557453 "There are only 10 types of people in the world... those who understand Binary... and those who don't." -Spike -- https://mail.python.org/mailman/listinfo/python-list
Re: Python 2 to 3 Conversion
On Tue, 20 Feb 2018 10:55:28 +1100, Chris Angelico wrote: > The given homepage URL is > http://alastairs-place.net/projects/netifaces/ - is that the right > one? > > ChrisA Yes, that is the right one. Now I'm feeling a little stupid. I should have remembered that many python library package names start with python- or python3-. Problem solved. A thousand thank-you's. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: How to only get \n for newline without the single quotes?
On Sat, 24 Feb 2018 11:41:32 -0600, Peng Yu wrote: > I would like to just get the escaped string without the single quotes. > Is there a way to do so? Thanks. > x='\n' print repr(x) > '\n' Python 3.5.3 (default, Jan 19 2017, 14:11:04) [GCC 6.3.0 20170118] on linux Type "help", "copyright", "credits" or "license" for more information. >>> x='/n' >>> print(repr(x)) '/n' >>> print(repr(x).strip("'")) /n >>> Python 2.7.13 (default, Nov 24 2017, 17:33:09) [GCC 6.3.0 20170516] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> x='/n' >>> print repr(x) '/n' >>> print repr(x).strip("'") /n >>> -- GNU/Linux user #557453 "There are only 10 types of people in the world... those who understand Binary... and those who don't." -Spike -- https://mail.python.org/mailman/listinfo/python-list
Re: psutil
On Tue, 27 Feb 2018 19:29:50 -0500, Larry Martell wrote: > Trying to install psutil (with pip install psutil) on Red Hat EL 7. > It's failing with: > > Python.h: No such file or directory > > Typically that means the python devel libs are not installed, but they are: > > [root@liszt ~]# yum install python-devel > Package python-devel-2.7.5-58.el7.x86_64 already installed and latest version > Nothing to do > > Anyone have any idea what to try next? I am not familiar with Red Hat and the RPM package system but on my Debian based system it is in the repository as an installable package. The package names are python-psutil and python3-psutil. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: Problem: Need galileo running on debian wheezy
On Thu, 01 Mar 2018 13:44:27 -0500, Gene Heskett wrote: > I know its supposed to be in the debian stretch repo's. > > I've been told to get a fitbit, but they don't support linux of any > flavor, and that leaves galileo as the possible solution? > > So how should I proceed since the only stretch machine I have ATM is an > arm64, aka a rock64. > > -- > Cheers, Gene Heskett I would suggest to download it from stretch's repo and open it with gdebi. It will tell you if the depends are met. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: Does This Scare You?
On Sat, 20 Aug 2016 10:57:37 +1000, Chris Angelico wrote: > On Sat, Aug 20, 2016 at 9:42 AM, Lawrence D’Oliveiro > wrote: >> Python 3.5.2+ (default, Aug 5 2016, 08:07:14) >> [GCC 6.1.1 20160724] on linux >> Type "help", "copyright", "credits" or "license" for more information. >> >>> from pathlib import PureWindowsPath >> >>> PureWindowsPath("prn").is_reserved() >> True >> >>> PureWindowsPath("prn.doc").is_reserved() >> True >> >>> PureWindowsPath("com9.exe").is_reserved() >> True >> >>> PureWindowsPath("c:/my documents/prn.doc").is_reserved() >> True > > When was the last time you wanted to create a file with a reserved > name? Paths, drive letters, file extensions, don't matter. All that > matters is the base name. > > Not a Python issue; they're reserved by Windows. > > ChrisA Since I am fairly new to Python, I realize there is much that I still don't know but I don't understand how Windows can have reserved names on a Linux system. What am I missing? -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: Does This Scare You?
On Sat, 20 Aug 2016 11:20:44 +1000, Chris Angelico wrote: > On Sat, Aug 20, 2016 at 11:11 AM, Wildman via Python-list > wrote: >> Since I am fairly new to Python, I realize there is much that I >> still don't know but I don't understand how Windows can have >> reserved names on a Linux system. What am I missing? > > The PureWindowsPath class is specifically working with the Windows > file system rules. Those names aren't reserved under Linux, but you > can still ask the pathlib module whether or not they *would be* > reserved under Windows. This is very handy if you're planning to > create files and don't know whether they'd work or not - you don't > need to grab a Windows machine (virtual or physical) to test stuff. > > ChrisA OK. I understand. Python is after all cross-platform so that makes perfect sense. Thanks. -- GNU/Linux user #557453 The voices in my head may not be real but, they have some good ideas. -- https://mail.python.org/mailman/listinfo/python-list
Re: Does This Scare You?
On Mon, 22 Aug 2016 17:27:13 +, Jon Ribbens wrote: > On 2016-08-22, Chris Angelico wrote: >> I tried things like "con.txt" and it simply failed (no such file or >> directory), without printing anything to the console. > > I'm not sure how you got that to fail, but writing to "con.txt" > certainly does write to the console in Windows 10 - I just tried it: > > C:\>echo hello >con.txt > hello I got the same result with Windows 7, Vista, XP, 2000, NT4, 98SE and 3.11. Yes, I have a lot VM's although I don't have 8.x. I would, however, expect the same result. On Linux a file is created named con.txt that contains hello/n as expected. -- GNU/Linux user #557453 "The Constitution only gives people the right to pursue happiness. You have to catch it yourself." -Benjamin Franklin -- https://mail.python.org/mailman/listinfo/python-list
Re: saving octet-stream png file
On Mon, 22 Aug 2016 13:21:43 -0400, Larry Martell wrote: > On Fri, Aug 19, 2016 at 4:51 PM, Lawrence D’Oliveiro > wrote: >> On Saturday, August 20, 2016 at 6:03:53 AM UTC+12, Terry Reedy wrote: >>> >>> An 'octet' is a byte of 8 bits. >> >> Is there any other size of byte? > > Many, many years ago, probably c. 1982 my Dad came into my house and > saw a Byte Magazine laying on the coffee table. He asked "What is a > byte?" I replied "Half a word." He then asked "What is the other half > of the word?" I said "That is also a byte." He thought for a moment, > then said "So the full word is 'byte byte'?" LOL! Did you explain to him that a full word could also be 'nibble nibble nibble nibble' or 'bit bit bit bit bit bit bit bit bit bit bit bit bit bit bit bit'? -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: Installing python
On Mon, 05 Sep 2016 20:01:08 +, alister wrote: > On Mon, 05 Sep 2016 12:46:58 -0700, emaraiza98 wrote: > >> I installed pycharm for a computer science class I'm taking, and also >> downloaded python 3.5.2. However, my computer for some reason won't use >> 3.5.2 and my professor told me I needed to download an earlier version >> to change the project interpreter. Whenever I try to use the earlier >> version of python for pycharm it says that "the SDK" seems invalid. I >> don't know what I'm doing wrong and was hoping someone would know what >> to do. I need to have everything installed and running by Wednesday. > > Are you by any chance still on windows XP? > > You will need Python V3.4 or earlier. > Alternatively upgrade your operating system. > > Most if not all current Linux distributions should run without trouble on > your hardware. > > They will probably have Python V2.7 as the system python but Python V3 > should be available from the package manager & you will probably have a > much nicer experience than your windows class mates :-) A good many Linux distros now have Python 2.7 and 3.x installed. For Python 3.x you would use this hash-bang... #!/usr/bin/env python3 -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: Python 3 curiosity.
On Tue, 06 Sep 2016 02:51:39 -0700, wxjmfauth wrote: > It's curious to see all these apps, that were > more of less working correctly up to Python 3.2 > (included) and are now no more working at all. > > Probably something wrong somewhere... http://sebastianraschka.com/Articles/2014_python_2_3_key_diff.html -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: Python 3 curiosity.
On Wed, 07 Sep 2016 02:27:40 +1000, Chris Angelico wrote: > On Wed, Sep 7, 2016 at 2:13 AM, Wildman via Python-list > wrote: >> On Tue, 06 Sep 2016 02:51:39 -0700, wxjmfauth wrote: >> >>> It's curious to see all these apps, that were >>> more of less working correctly up to Python 3.2 >>> (included) and are now no more working at all. >>> >>> Probably something wrong somewhere... >> >> http://sebastianraschka.com/Articles/2014_python_2_3_key_diff.html > > That's jmf, and he never actually posts proof, but keeps on asserting > that Unicode handling in Python 3.3+ is "broken". Actually, it's not. > The worst criticism you can level at it is that it may be slower in > certain microbenchmarks... but only if you're comparing against a > *narrow build* of Python 3.2, which is *buggy*. In other words, Python > eliminated an endemic bug, and actually improved performance overall, > but worsened it on a very VERY few cases. > > Most of us have either killfiled him, or are reading this via the > mailing list, which doesn't carry his traffic. I suggest you do the > same. He's a crank. > > ChrisA Thanks for the heads-up. -- GNU/Linux user #557453 "Be at war with your vices, at peace with your neighbors, and let every new year find you a better man." -Benjamin Franklin -- https://mail.python.org/mailman/listinfo/python-list
Re: Why does the insert after list function fail?
On Thu, 22 Sep 2016 12:29:12 -0700, 380162267qq wrote: > A=["1","2","3"] > print(list(map(float,A)).insert(0,1)) > > I want to insert 1 at the head of the list but this gives me a surprise I am not certain about what you are doing so I might be way off here. The following will insert 1 at the head of the list... Python 3.4.2 (default, Oct 8 2014, 10:45:20) [GCC 4.9.1] on linux Type "help", "copyright", "credits" or "license" for more information. >>> A=["1","2","3"] >>> list.insert(A,0,"1") >>> print(A) ['1', '1', '2', '3'] -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: How to reduce the DRY violation in this code
On Tue, 27 Sep 2016 10:30:05 -0700, Paul Rubin wrote: > Chris Angelico writes: >> Can you elaborate on what "GoF builder" means? Presumably it's a >> special case of the builder pattern, > > I think it just means the usual builder pattern, from the Design > Patterns book by the so-called Gang of Four (GoF). http://c2.com/cgi/wiki?GangOfFour -- GNU/Linux user #557453 Keyboard not detected! Press any key to continue... -- https://mail.python.org/mailman/listinfo/python-list
Re: Scripting Help please
On Wed, 12 Oct 2016 20:48:31 +, alister wrote: > On Wed, 12 Oct 2016 13:37:23 -0700, LongHairLuke wrote: > >> Hi l am on my way to make a bot for the game Piano Tiles 2. >> But the code l have written so far saids invalid syntax at 2nd line. >> Here is my code: >> >> >> >> while True: >>If active then >> FFSnapShot(areaX, areaY + height - offsetBottom, areaX + width, >> areaY + height - offsetBottom, sid) >> For row = 0 To norows - 1 >> c = FFGetPixel(areaX + row * rowWidth + 5, areaY + height - >> offsetBottom, sid) >> cs = _ColorGetRGB(c) >> b = ( cs[0] * 0.3 ) + ( cs[1] * 0.59 ) + ( cs[2] * 0.11 ) >> If lock[row] Then >> If b < darkness Then >>ContinueLoop >> Else >>lock[row] = False >> EndIf >> EndIf If b < darkness Then >> MouseUp("Left") >> lock[row] = True MouseMove(areaX + row * rowWidth + rowWidth >> / 2, areaY + height - offsetBottom, 1) >> MouseDown("Left") >> EndIf >> Next >>EndIf >> End >> >> Can someone help me please? > > Is observation this is not Python code > it looks more like some variety of BASIC but I could easily be wrong I looks very similar to Visual Basic except I know of no instances where '[]' are used in an array, as in lock[row]. The functions that begin with 'FF' are from a pixel search library called FastFind. It works with several different programming languages so no definite clue there. I'm not sure about the Mouse functions. They could also be from a library. In VB the functions would be called like this: object.MouseUp(). I'm not sure what the code is but it definitely is not Python. -- GNU/Linux user #557453 May the Source be with you. -- https://mail.python.org/mailman/listinfo/python-list
Re: [FAQ] "Best" GUI toolkit for python
On Tue, 18 Oct 2016 00:58:42 +0200, pozz wrote: > I'm sorry, I know it is a FAQ..., but I couldn't find a good answer. > > I'm learning python and I'd like to start creating GUI applications, > mainly for Windows OS. In the past, I wrote many applications in Visual > Basic 4: it was very fast and you could create simple but effective GUIs > in Windows in some minutes. I am also learning Python so my experience is limited. I have tried pyGTK and Tkinter. GTK's concept of the hbox and vbox gave me of difficulty. I couldn't get the GUI to look the way I wanted. OTOH, Tkinter offers a way to place widgets on a window/frame in a precise way: self.widget.place(x=#, y=#) That is similar to VB's move statement. GTK may have such a feature but I was not able to find it. Anyway, my choice based on my limited experience is Tkinter. Here is a good place to start... http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/index.html This will give you several places to look for additional info... https://duckduckgo.com/?q=tkinter+tutorials&t=h_&ia=web -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Button Widget and Key Binding Problem
I am working on a program with a GUI created with Tkinter. I want to enable key bindings for the button widgets. Below is some of the code to show how the window and button widget was created. The button calls a routine that will load an image. class Window(tk.Frame): def __init__(self, master=None): tk.Frame.__init__(self, master) self.master = master root.bind("", self.load_image) root.bind("", self.load_image) self.init_window() def init_window(self): self.loadButton = tk.Button(self, text="Load Image", underline=0, width=10, command=self.load_image) def load_image(self): # code to load an image When I click the load button everything works as expected. But if I hit the hot key I get this error: Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1535, in __call__ return self.func(*args) TypeError: load_image() takes exactly 1 argument (2 given) The key binding is making the call with an extra argument. If I change the definition for the load_image routine for an additional argument, the key binding works but the button click produces this error: Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1535, in __call__ return self.func(*args) TypeError: load_image() takes exactly 2 arguments (1 given) As a workaround I changed the binding code to call a different routine named launch_load_image and that routine calls load_image: def launch_load_image(self, _): self.load_image() Both the key bindings and the button click work. My question is whether my workaround is the correct way? Could my key binding code be wrong in some way? An insight appreciated. -- GNU/Linux user #557453 May the source be with you. -- https://mail.python.org/mailman/listinfo/python-list
Re: Button Widget and Key Binding Problem
On Wed, 19 Oct 2016 04:39:03 +0100, MRAB wrote: > The 'bind' method passes an 'event' object when it calls; the 'command' > callback doesn't. > > You don't care about the 'event' object anyway, so you can just define a > single method with a default argument that you ignore: > > def load_image(self, event=None): > # code to load an image That works perfectly. Thank you. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: How to handle errors?
On Thu, 20 Oct 2016 12:48:28 -0700, SS wrote: > The following script works fine: > > #!/bin/python > > import socket > > str = raw_input("Enter a domain name: "); > print "Your domain is ", str > print socket.gethostbyname(str) > > You provide it a hostname, it provides an IP. That works fine. But I need a > way to handle errors. For example: > > [root@bart /]# ./dataman.py > Enter a domain name: aslfhafja > Your domain is aslfhafja > Traceback (most recent call last): > File "./dataman.py", line 7, in > print socket.gethostbyname(str) > socket.gaierror: [Errno -2] Name or service not known > [root@bart /]# > > I would like to be able to handle that error a bit better. Any ideas? > > TIA. #!/usr/bin/env python import socket def get_ip(url): try: ip = socket.gethostbyname(url) return ip except socket.gaierror: return "***ERROR***\nUnknown domain name!" domain = raw_input("Enter a domain name: "); print "Your domain is ", domain print get_ip(domain) -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: How to handle errors?
On Thu, 20 Oct 2016 12:48:28 -0700, SS wrote: > The following script works fine: > > #!/bin/python I meant to include this with my other post but I forgot it. Using a direct path to the Python interpreter can cause problems on some systems because it is not always installed to the same directory. On my Debian-based system Python is installed in /usr/bin. So your code as written will not run on my system. A workaround for this is to use env in the shebang/hashbang. For Python 2: #!/usr/bin/env python For Python 3: #!/usr/bin/env python3 It will not matter where Python is installed. 'env' will always know where it is. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: How to handle errors?
On Fri, 21 Oct 2016 16:14:41 +1100, Steve D'Aprano wrote: > On Fri, 21 Oct 2016 11:03 am, Wildman wrote: > >> On Thu, 20 Oct 2016 12:48:28 -0700, SS wrote: >> >>> The following script works fine: >>> >>> #!/bin/python >> >> I meant to include this with my other post but I forgot it. >> >> Using a direct path to the Python interpreter can cause problems >> on some systems because it is not always installed to the same >> directory. > > Then you change the path and fix it. You are assuming that I, the user, knows what a shebang is and what it is used for and what Python is and where the interpreter is located. If you are targeting developers none of that will be a problem but, if your program is for "average users", you may have a serious problem. Personally I would not want to distribute a program that may require the user to fix the code before it will run. >> On my Debian-based system Python is installed in >> /usr/bin. So your code as written will not run on my system. >> A workaround for this is to use env in the shebang/hashbang. > > That's not a work-around. That's a bug waiting to happen. > > One of the problems with of env is that it will use whatever python > executable appears first in the user's $PATH, regardless of whether it is > the right Python or not -- or even whether it is actually Python, or just > some random executable file called "python". For example, you might have > compiled your own experimental Python executable, and adjusted your PATH > environment variable to find it. Now your env scripts will use your > unstable, experimental Python interpreter instead of the system Python. A developer might have complied experimental versions of Python but the average user will not. Here again it depends on your target. > Another serious problem with using env in the hash-bang line is that you > cannot pass commandline options to the Python executable. Not true. I made a test script with this code: #!/usr/bin/env python import sys print sys.argv Then I ran it: ~$ python test.py argument1 argument2 ['test.py', 'argument1', 'argument2'] > Using env in this way is a hack that happens to mostly work. Its arguably an > abuse of env, and its not as portable as people often think (not all older > Unix systems even have env). If you are targeting older Unixes than yes that could be a problem. >> For Python 2: #!/usr/bin/env python >> For Python 3: #!/usr/bin/env python3 >> >> It will not matter where Python is installed. 'env' will always >> know where it is. > > That's not correct: env only searches the PATH, so if your python is not in > the path, it won't be found. Here's env on my system with the default PATH: > > [steve@ando ~]$ /usr/bin/env python -c "import sys; print(sys.version)" > 2.4.3 (#1, Jan 9 2013, 06:49:54) > [GCC 4.1.2 20080704 (Red Hat 4.1.2-54)] > > > But if I change the search path (or if I move the Python executable > somewhere off the path): > > [steve@ando ~]$ PATH="/tmp" /usr/bin/env python -c "import sys; > print(sys.version)" > /usr/bin/env: python: No such file or directory > > > Even if env finds something called "python", you can't be sure that it is > the right version of Python, or even Python at all. All you know is that it > is something called "python" on the search path. Not likely an average user is going muck around with the path in the way you describe. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: How to handle errors?
On Sat, 22 Oct 2016 15:01:46 +, John Gordon wrote: > In Wildman > writes: > >> > Another serious problem with using env in the hash-bang line is that you >> > cannot pass commandline options to the Python executable. > >> Not true. I made a test script with this code: > >> #!/usr/bin/env python >> import sys >> print sys.argv > >> Then I ran it: > >> ~$ python test.py argument1 argument2 >> ['test.py', 'argument1', 'argument2'] > > Options cannot be passed *on the hash-bang line*. OK, I misunderstood Steve's statement. I stand corrected. -- GNU/Linux user #557453 "Well, that's quite different. Never mind." -Emily Litella -- https://mail.python.org/mailman/listinfo/python-list
Re: exist loop by pressing esc
On Sun, 23 Oct 2016 14:34:29 -0700, chris alindi wrote: > simple while loop range(10) if user press esc exits loop If I understand you correctly you want to exit a while loop with the ESC key. That can be done but it depends on the platform. For Windows use this: (not tested) import msvcrt while something: if msvcrt.kbhit() and msvcrt.getch() == chr(27): break In Linux you need to install getch: https://pypi.python.org/pypi/getch Download it here: https://pypi.python.org/pypi/getch#downloads Extract the tar.gz file. A directory called getch-1.0 will be created. Open a terminal in that directory and enter this... sudo python setup.py install Here is a code example: (tested) import getch while something: if getch.getch() == '\x1b': break -- GNU/Linux user #557453 May the Source be with you. -- https://mail.python.org/mailman/listinfo/python-list
Re: How to execute "gksudo umount VirtualDVD"
On Fri, 28 Oct 2016 11:05:17 +0300, Demosthenes Koptsis wrote: > Yes it was pasted wrong... > > def umount(self): > '''unmounts VirtualDVD''' > cmd = 'gksudo umount VirtualDVD' > proc = subprocess.Popen(str(cmd), shell=True, > stdout=subprocess.PIPE).stdout.read() > print proc > > it fails silently the gksudo runs correctly. I can input the password. > > But the umount does nothing. I keep have mounted the VirtualDVD folder. > > > On 10/28/2016 12:54 AM, Ian Kelly wrote: >> On Thu, Oct 27, 2016 at 3:30 PM, Demosthenes Koptsis >> wrote: >>> I want to execute the command "gksudo umount VirtualDVD" >>> >>> My code is this but it fails: >>> >>> def umount(self): >>> '''unmounts VirtualDVD''' cmd ='gksudo umount VirtualDVD' proc = >>> subprocess.Popen(str(cmd),shell=True,stdout=subprocess.PIPE).stdout.read() >>> print proc >> It looks like your code pasted incorrectly. >> >>> It pops up the gksudo dialog, and then fails. But i don't get any stdout or >>> stderror. >> Fails how? Is there an error? Does it hang? Does nothing happen at all? >> >> My initial thought is that you might want to try using >> Popen.communicate instead of stdout.read in case you're getting >> deadlocked. See the big red warning below >> https://docs.python.org/3/library/subprocess.html#subprocess.Popen.stdout Try this: def umount(self): '''unmounts VirtualDVD''' cmd = ["gksudo", "umount", VirtualDVD p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) proc = p.communicate() print proc -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: How to execute "gksudo umount VirtualDVD"
On Fri, 28 Oct 2016 17:19:17 -0500, Wildman wrote: > On Fri, 28 Oct 2016 11:05:17 +0300, Demosthenes Koptsis wrote: > >> Yes it was pasted wrong... >> >> def umount(self): >> '''unmounts VirtualDVD''' >> cmd = 'gksudo umount VirtualDVD' >> proc = subprocess.Popen(str(cmd), shell=True, >> stdout=subprocess.PIPE).stdout.read() >> print proc >> >> it fails silently the gksudo runs correctly. I can input the password. >> >> But the umount does nothing. I keep have mounted the VirtualDVD folder. >> >> >> On 10/28/2016 12:54 AM, Ian Kelly wrote: >>> On Thu, Oct 27, 2016 at 3:30 PM, Demosthenes Koptsis >>> wrote: I want to execute the command "gksudo umount VirtualDVD" My code is this but it fails: def umount(self): '''unmounts VirtualDVD''' cmd ='gksudo umount VirtualDVD' proc = subprocess.Popen(str(cmd),shell=True,stdout=subprocess.PIPE).stdout.read() print proc >>> It looks like your code pasted incorrectly. >>> It pops up the gksudo dialog, and then fails. But i don't get any stdout or stderror. >>> Fails how? Is there an error? Does it hang? Does nothing happen at all? >>> >>> My initial thought is that you might want to try using >>> Popen.communicate instead of stdout.read in case you're getting >>> deadlocked. See the big red warning below >>> https://docs.python.org/3/library/subprocess.html#subprocess.Popen.stdout > > Try this: > > def umount(self): > '''unmounts VirtualDVD''' > cmd = ["gksudo", "umount", VirtualDVD] ^ > p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) > proc = p.communicate() > print proc Oops! -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Calling Bash Command From Python
Python 2.7.9 on Linux Here is a bash command that I want to run from a python program: sudo grep "^user\:" /etc/shadow If I enter the command directly into a terminal it works perfectly. If I run it from a python program it returns an empty string. Below is the code I am using. Suggestions appreciated. cmdlist = ["sudo", "grep", '"^$USER\:"', "/etc/shadow"] p = subprocess.Popen(cmdlist, stdout=subprocess.PIPE, stderr=subprocess.PIPE) shadow, err = p.communicate() print shadow -- GNU/Linux user #557453 -- https://mail.python.org/mailman/listinfo/python-list
Re: Calling Bash Command From Python
On Mon, 31 Oct 2016 15:31:27 +1100, Chris Angelico wrote: > On Mon, Oct 31, 2016 at 3:19 PM, Wildman via Python-list > wrote: >> Here is a bash command that I want to run from a python >> program: sudo grep "^user\:" /etc/shadow >> >> If I enter the command directly into a terminal it works >> perfectly. If I run it from a python program it returns an >> empty string. Below is the code I am using. Suggestions >> appreciated. >> >> cmdlist = ["sudo", "grep", '"^$USER\:"', "/etc/shadow"] >> p = subprocess.Popen(cmdlist, >> stdout=subprocess.PIPE, >> stderr=subprocess.PIPE) >> shadow, err = p.communicate() >> print shadow > > Are you able to run that command without a password? sudo might be > attempting to open the console, failing, and aborting the command. Is > anything being printed to stderr? > > ChrisA No. The program is run in a terminal and sudo asks for a password. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: Call a shell command from Python (was: Calling Bash Command From Python)
On Mon, 31 Oct 2016 15:44:13 +1100, Ben Finney wrote: > Wildman via Python-list writes: > >> Python 2.7.9 on Linux >> >> Here is a bash command that I want to run from a python >> program: sudo grep "^user\:" /etc/shadow > > Some points to note: > > * Those commands are not special to Bash, or any particular shell. They > invoke commands, without AFAIK any specific Bash features. So this is > asking rather to invoke a shell command. Yes, I know. I perhaps should have used the word "shell" instead of bash. However, bash is a shell. > Nothing wrong with that; but on that basis, I've changed the subject > field. > > * You're asking to invoke the ‘sudo’ command, which itself is designed > to switch to a separate user identity and run another program. Yes, I know. > * The above command is (I assume) typed into a shell, but your Python > program never invokes Bash or any other shell. The program is run in a shell so invocation is not needed. >> If I enter the command directly into a terminal it works perfectly. > > Note that ‘sudo’ is specifically designed to be invoked interactively, > seeking to verify that the current user has credentials to run the > command. > > Note further that ‘sudo’ will record when the *current user session* > last invoked ‘sudo’ and seek re-verification if that is too long in the > past. > > Both of these are security measures, and are designed to avoid > non-interactive use of ‘sudo’. Rather, it's meant to be used > interactively by a real, present human with credentials to run the > command. Yes, I know all that. >> If I run it from a python program it returns an empty string. > > You can also check the exit status of a command; ‘grep’ will give > different exit status for a match versus no match. > >> Below is the code I am using. Suggestions >> appreciated. >> >> cmdlist = ["sudo", "grep", '"^$USER\:"', "/etc/shadow"] > > One immediate difference I see is that you specify different arguments > to ‘grep’. You have a different pattern for each command. > > * The ‘^user\:’ pattern matches “user\:” at the start of a line. > > * The ‘^$USER\:’ pattern I think won't match anything, since “$” matches > end-of-line and then you expect further characters *past* the end of > the line. I think that will always fail to match any line. Yes, the '^' indicates the start of the line and the ':' indicates the character where to stop. The colon has a special meaning so it has to be escaped, '\:'. The dollar sign precedes a variable. In this case it is an environment variable. The Linux shadow file contains information about the users of the system. It has the user name, encrypted password, salt, encryption type and other information. The format is such that the user name is at the start of the line ending with a colon. Here is an example: wildman:$6$hODbsJJp$/NWGXZ3fMIVB4U.v/oLtAv.CnL0l0I39.IwsDx1ZAlKW3wUSjTfwJdnQvOMpYNbqNqqFfZ52vgYWBmnjsaX9R.:16177:0:9:7::: >> p = subprocess.Popen(cmdlist, >> stdout=subprocess.PIPE, >> stderr=subprocess.PIPE) >> shadow, err = p.communicate() > > Maybe you are expecting Bash to be involved somehow (and so “$USER” will > be substituted by Bash with some other value). That's not what happens. No, the shell is already running. And $USER will be substituted by the name of the user that invoked the shell. > Instead, the ‘subprocess.Popen.communicate’ method will invoke the > program directly, without involving a shell. See the documentation for > ‘subprocess.Popen’. I will look into that. Thanks for the reply. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: Calling Bash Command From Python
On Mon, 31 Oct 2016 09:12:57 +0100, Peter Otten wrote: > Wildman via Python-list wrote: > >> Python 2.7.9 on Linux >> >> Here is a bash command that I want to run from a python >> program: sudo grep "^user\:" /etc/shadow >> >> If I enter the command directly into a terminal it works >> perfectly. If I run it from a python program it returns an >> empty string. Below is the code I am using. Suggestions >> appreciated. >> >> cmdlist = ["sudo", "grep", '"^$USER\:"', "/etc/shadow"] >> p = subprocess.Popen(cmdlist, >> stdout=subprocess.PIPE, >> stderr=subprocess.PIPE) >> shadow, err = p.communicate() >> print shadow > > What happens if you hardcode $USER? Compare: > >>>> subprocess.Popen(["sudo", "echo", "$USER"], > stdout=subprocess.PIPE).communicate() > ('$USER\n', None) > > That should explain the empty result. Possible fix: > >>>> subprocess.Popen(["sudo", "echo", os.environ["USER"]], > stdout=subprocess.PIPE).communicate() > ('user\n', None) > > While a shell should work, too, > >>>> subprocess.Popen("sudo echo $USER", stdout=subprocess.PIPE, > shell=True).communicate() > ('petto\n', None) > > I'd prefer the os.environ lookup. I have code using that approach but I am trying to save myself from having to parse the entire shadow file. Grep will do it for me if I can get code right. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: Calling Bash Command From Python
On Mon, 31 Oct 2016 08:13:54 +, Jon Ribbens wrote: > On 2016-10-31, Wildman wrote: >> Here is a bash command that I want to run from a python >> program: sudo grep "^user\:" /etc/shadow >> >> If I enter the command directly into a terminal it works >> perfectly. If I run it from a python program it returns an >> empty string. Below is the code I am using. Suggestions >> appreciated. >> >> cmdlist = ["sudo", "grep", '"^$USER\:"', "/etc/shadow"] >> p = subprocess.Popen(cmdlist, >> stdout=subprocess.PIPE, >> stderr=subprocess.PIPE) >> shadow, err = p.communicate() >> print shadow > > Slightly surprised that nobody's pointed out that in your bash > invocation, the first argument to grep is: > > ^user\: > > and in the Python code it is: > > "$USER\:" > > Your cmdlist should read: > > ["sudo", "grep", r"^user\:", "/etc/shadow"] > > or if you really want it to do the same as the bash: > > ["sudo", "grep", "^" + os.environ["USER"] + r"\:", "/etc/shadow"] The above line works perfectly. I didn't occur to me to use the 'r' modifier. Thank you. Still one thing is odd. No matter what, if I use the environment variable $USER in the code, it won't work. Just returns an empty string. At this point that is a non-issue tho. Thanks again. -- GNU/Linux user #557453 -- https://mail.python.org/mailman/listinfo/python-list
Re: Calling Bash Command From Python
On Mon, 31 Oct 2016 11:05:23 -0400, Random832 wrote: > On Mon, Oct 31, 2016, at 10:55, Wildman via Python-list wrote: >> I have code using that approach but I am trying to save myself >> from having to parse the entire shadow file. Grep will do it >> for me if I can get code right. > > Python already has built-in functions to parse the shadow file. > > https://docs.python.org/3/library/spwd.html#module-spwd I didn't know about that module. Thanks, this can simplify things for me. > But you can't use sudo this way if you use that. But why do you want to > use sudo from within the python script instead of just running the > python script with sudo? In view of the module I just learned about, that would be a better approach. -- GNU/Linux user #557453 -- https://mail.python.org/mailman/listinfo/python-list
Re: Calling Bash Command From Python
On Mon, 31 Oct 2016 11:55:26 -0500, Wildman wrote: > On Mon, 31 Oct 2016 11:05:23 -0400, Random832 wrote: > >> On Mon, Oct 31, 2016, at 10:55, Wildman via Python-list wrote: >>> I have code using that approach but I am trying to save myself >>> from having to parse the entire shadow file. Grep will do it >>> for me if I can get code right. >> >> Python already has built-in functions to parse the shadow file. >> >> https://docs.python.org/3/library/spwd.html#module-spwd > > I didn't know about that module. Thanks, this can simplify > things for me. > >> But you can't use sudo this way if you use that. But why do you want to >> use sudo from within the python script instead of just running the >> python script with sudo? > > In view of the module I just learned about, that would be > a better approach. I made a discovery that I thought I would share. When using sudo to run the script the environment variable $USER will always return 'root'. Not what I wanted. But this will work: user = os.environ["SUDO_USER"] shadow = spwd.getspnam(user) That will return the actual user name that invoked sudo. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: Call a shell command from Python
On Tue, 01 Nov 2016 12:08:52 +1100, Ben Finney wrote: > Wildman via Python-list writes: > >> On Mon, 31 Oct 2016 15:44:13 +1100, Ben Finney wrote: >> >> > One immediate difference I see is that you specify different >> > arguments to ‘grep’. You have a different pattern for each command. >> > >> > * The ‘^user\:’ pattern matches “user\:” at the start of a line. >> > >> > * The ‘^$USER\:’ pattern I think won't match anything, since “$” matches >> > end-of-line and then you expect further characters *past* the end of >> > the line. I think that will always fail to match any line. >> >> Yes, the '^' indicates the start of the line and the ':' indicates >> the character where to stop. The colon has a special meaning so it >> has to be escaped, '\:'. The dollar sign precedes a variable. In >> this case it is an environment variable. > > The ‘grep’ program you're invoking knows nothing of such variables, and > the ‘$’ sign means to ‘grep’ what I said above. You are correct about that but, in this case grep never "sees" the '$' sign. Bash expands $USER to the actual user name beforehand. If you are on a Linux system, enter this into a terminal to illustrate: sudo grep ^$USER\: /etc/shadow If the user name is ben then grep would see this: grep ben\: /etc/shadow >> > Maybe you are expecting Bash to be involved somehow (and so “$USER” >> > will be substituted by Bash with some other value). That's not what >> > happens. >> >> No, the shell is already running. > > I don't know what you mean by this. If you mean that some *other* > instances of the shell ar running: that isn't relevant to how your > Python program invokes a subprocess. I simply meant that the script is run from a terminal. > The shell is not involved in the command as you invoke it directly as a > subprocess, without asking for a shell. > >> And $USER will be substituted by the name of the user that invoked the >> shell. > > It will not, because there is no shell involved: your Python program > invokes ‘sudo’, which invokes ‘grep’. The shell is never involved in > that chain, so its substitutions rules are irrelevant. I think my terminology is causing confusion. I apologize for that. -- GNU/Linux user #557453 -- https://mail.python.org/mailman/listinfo/python-list
Re: Call a shell command from Python
On Tue, 01 Nov 2016 16:23:08 +1100, Ben Finney wrote: > Wildman via Python-list writes: > >> […] in this case grep never "sees" the '$' sign. Bash expands $USER to >> the actual user name beforehand. > > I understand how Bash substitutes variables on the command line. > > What I need to repeat, though: In this case, no, Bash doesn't do that > because Bash isn't getting involved. Grep does in fact see the “$” in > the command argument, because nothing ever replaces it. I understand now. Thank you. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: Call a shell command from Python
On Tue, 01 Nov 2016 16:52:18 +1100, Steve D'Aprano wrote: > On Tue, 1 Nov 2016 04:00 pm, Wildman wrote: > >> You are correct about that but, in this case grep never "sees" the '$' >> sign. Bash expands $USER to the actual user name beforehand. If you >> are on a Linux system, enter this into a terminal to illustrate: >> >> sudo grep ^$USER\: /etc/shadow > > Bash is not involved here. Python is calling grep directly. > > > You don't have to believe us, you can test this yourself. Create a simple > text file with a single line containing your username, and a simple Python > script that calls grep as you have been: > > > [steve@ando ~]$ echo $USER > steve > [steve@ando ~]$ cat foo.txt > blah blah steve blah blah > [steve@ando ~]$ cat greptest.py > import subprocess > cmdlist = ['grep', '$USER', 'foo.txt'] > p = subprocess.Popen(cmdlist, stdout=subprocess.PIPE,stderr=subprocess.PIPE) > line, err = p.communicate() > print err, line > > [steve@ando ~]$ python2.7 greptest.py > > [steve@ando ~]$ > > > > So there you have it: categorical proof that bash does not expand the > string '$USER'. It cannot: bash is not involved in the subprocess call. > Python calls grep directly. > > If you want to expand the '$USER' string from Python, do it yourself: I understand now. That explains more clearly why my original code did not work. Thank you. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: Call a shell command from Python
On Tue, 01 Nov 2016 13:42:03 +, Grant Edwards wrote: > On 2016-11-01, Steve D'Aprano wrote: >> On Tue, 1 Nov 2016 04:00 pm, Wildman wrote: >> >>> You are correct about that but, in this case grep never "sees" the '$' >>> sign. Bash expands $USER to the actual user name beforehand. If you >>> are on a Linux system, enter this into a terminal to illustrate: >>> >>> sudo grep ^$USER\: /etc/shadow >> >> Bash is not involved here. Python is calling grep directly. > > He's already been told this 6 times, and is willfully ignoring it. > > Just give up. That was not my intention. I was trying to understand that which I did not understand. Ever been there? -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: Call a shell command from Python
On Tue, 01 Nov 2016 11:23:09 -0400, D'Arcy Cain wrote: > On 2016-11-01 01:23 AM, Ben Finney wrote: >> Wildman via Python-list writes: >> So the way your script was invoked has no bearing on whether Bash will >> get involved in what your script does. Your script is *directly* >> invoking programs, and if you don't ask for a shell to be involved you >> won't get it. > > In other words, the OP's script *is* bash in this scenario or a > reasonable facsimile thereof. > > The subject probably should have been "Emulating a shell in Python." Of > course, if the OP knew to use that subject he probably would have > already had the answer. :-) You are absolutely correct. And thank you for your understanding. -- GNU/Linux user #557453 Keyboard not detected! Press any key to continue... -- https://mail.python.org/mailman/listinfo/python-list
Re: Quick help for a python newby, please
On Wed, 23 Nov 2016 06:18:38 -0800, jones.dayton wrote: > I'm just learning, so please excuse my ignorance for > what I know is a simple issue... > > I'm writing a "Hello, World" type of script to see how > things work in python3. I'm asking for input to get a > person's birthday, then I want to compare that to > "today" and see how many days have past. > > --code-- > from datetime import datetime, date > > person = input("Enter your name: ") > bmonth = int(input("Enter the numerical month you were born: ")) > bday = int(input("Enter the numerical day of the month you were born: ")) > byear = int(input("Enter the year you were born: ")) > > today = date.today() > -- end -- > > I know to get what I want, I need to do something like: > d0 = date(2008, 8, 18) > d1 = date(2008, 9, 26) > delta = d0 - d1 > print(delta.days) > > > but how do I replace the "2008, 8, 18" and "2008, 9, 26" with *my* values? > I've tried several things (which I can't remember all of) but usually end up > with an error like this: > >... > delta = (b - a) > TypeError: unsupported operand type(s) for -: 'str' and 'str' Try the code that is below: import datetime from datetime import date today = date.today() person = input("Enter your name: ") byear = raw_input("Enter the four-digit year you were born: ") bmonth = raw_input("Enter the month (1-12)you were born: ") bday = raw_input("Enter the day (1-31) you were born: ") try: birthdate = date(int(byear), int(bmonth), int(bday)) dif = (today - birthdate).days print person + "'s birthday was " + str(dif) + " days ago." except ValueError: print "The date you entered is not valid!" -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: Quick help for a python newby, please
On Thu, 24 Nov 2016 11:59:17 +1100, Chris Angelico wrote: > On Thu, Nov 24, 2016 at 10:02 AM, Wildman via Python-list > wrote: >> Try the code that is below: >> >> import datetime >> from datetime import date >> >> today = date.today() >> person = input("Enter your name: ") >> byear = raw_input("Enter the four-digit year you were born: ") > > Please take care of Python versions. The OP said Python 3, and you've > kept one input() call, but then you've used raw_input for the rest. > These should all be input() calls in Py3. > > ChrisA Point taken. I did miss the python3 part. I switched to raw_input because it handles an empty input. An empty input would trigger the ValueError. No doubt with the correct code the same or similar could be done with input(). My lack of experience caused me to look for simpler solution and perhaps the wrong one. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: Quick help for a python newby, please
On Thu, 24 Nov 2016 14:49:27 +1100, Chris Angelico wrote: > On Thu, Nov 24, 2016 at 2:41 PM, Wildman via Python-list > wrote: >> Point taken. I did miss the python3 part. >> >> I switched to raw_input because it handles an empty >> input. An empty input would trigger the ValueError. >> No doubt with the correct code the same or similar >> could be done with input(). My lack of experience >> caused me to look for simpler solution and perhaps >> the wrong one. > > The exact same thing is true of input() in Python 3. In Python 2, > input() is the same as eval(raw_input()), so don't use it ever [1]. > You can happily use input() in Py3, even if you get empty input. > > I like to put this at the top of cross-version scripts: > > try: input = raw_input > except NameError: pass > > Then you can proceed to use input() without worries. > > ChrisA > > [1] Yes, I'm aware there are times when evalling the user's input is > what you want. In those cases, be explicit and use eval. Understood. Thank you. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Request Help With Byte/String Problem
For the purpose of learning I am writing a script that will return different information about the Linux machine where it is running. Sort of like the inxi utility. Below is some code that I found that returns a list of the network interface devices on the system. It runs as is perfectly on Python2 but I get the error pasted below the code when run on Python3, the desired version. I know it has something to do with bytes vs. strings but I can' seem to figure it out. Any help appreciated. import array import socket import struct def all_interfaces(): max_possible = 128 # arbitrary. raise if needed. bytes = max_possible * 32 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) names = array.array("B", '\0' * bytes) outbytes = struct.unpack('iL', fcntl.ioctl( s.fileno(), 0x8912, # SIOCGIFCONF struct.pack('iL', bytes, names.buffer_info()[0]) ))[0] namestr = names.tostring() lst = [] for i in range(0, outbytes, 40): name = namestr[i:i+16].split('\0', 1)[0] ip = namestr[i+20:i+24] lst.append((name, ip)) return lst def format_ip(addr): return str(ord(addr[0])) + '.' + \ str(ord(addr[1])) + '.' + \ str(ord(addr[2])) + '.' + \ str(ord(addr[3])) ifs = all_interfaces() for i in ifs: print("%12s %s" % (i[0], format_ip(i[1]))) Traceback (most recent call last): File "./ifaces.py", line 32, in ifs = all_interfaces() File "./ifaces.py", line 11, in all_interfaces names = array.array("B", '\0' * bytes) TypeError: cannot use a str to initialize an array with typecode 'B' -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: Request Help With Byte/String Problem
On Tue, 29 Nov 2016 18:29:51 -0800, Paul Rubin wrote: > Wildman writes: >> names = array.array("B", '\0' * bytes) >> TypeError: cannot use a str to initialize an array with typecode 'B' > > In Python 2, str is a byte string and you can do that. In Python 3, > str is a unicode string, and if you want a byte string you have to > specify that explicitly, like b'foo' instead of 'foo'. I.e. > > names = array.array("B", b'\0' * bytes) > > should work. I really appreciate your reply. Your suggestion fixed that problem, however, a new error appeared. I am doing some research to try to figure it out but no luck so far. Traceback (most recent call last): File "./ifaces.py", line 33, in ifs = all_interfaces() File "./ifaces.py", line 21, in all_interfaces name = namestr[i:i+16].split('\0', 1)[0] TypeError: Type str doesn't support the buffer API -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: Request Help With Byte/String Problem
On Wed, 30 Nov 2016 07:54:45 -0500, Dennis Lee Bieber wrote: > On Tue, 29 Nov 2016 22:01:51 -0600, Wildman via Python-list > declaimed the following: > >>I really appreciate your reply. Your suggestion fixed that >>problem, however, a new error appeared. I am doing some >>research to try to figure it out but no luck so far. >> >>Traceback (most recent call last): >> File "./ifaces.py", line 33, in >>ifs = all_interfaces() >> File "./ifaces.py", line 21, in all_interfaces >>name = namestr[i:i+16].split('\0', 1)[0] >>TypeError: Type str doesn't support the buffer API > > The odds are good that this is the same class of problem -- you are > providing a Unicode string to a procedure that wants a byte-string (or vice > versa) > > https://docs.python.org/3/library/array.html?highlight=tostring#array.array.tostring That helped. Thanks. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: Request Help With Byte/String Problem
On Wed, 30 Nov 2016 14:39:02 +0200, Anssi Saari wrote: > There'll be a couple more issues with the printing but they should be > easy enough. I finally figured it out, I think. I'm not sure if my changes are what you had in mind but it is working. Below is the updated code. Thank you for not giving me the answer. I was a good learning experience for me and that was my purpose in the first place. def format_ip(addr): return str(int(addr[0])) + '.' + \ # replace ord() with int() str(int(addr[1])) + '.' + \ str(int(addr[2])) + '.' + \ str(int(addr[3])) ifs = all_interfaces() for i in ifs: # added decode("utf-8") print("%12s %s" % (i[0].decode("utf-8"), format_ip(i[1]))) Thanks again! -- GNU/Linux user #557453 May the Source be with you. -- https://mail.python.org/mailman/listinfo/python-list
Re: Request Help With Byte/String Problem
On Fri, 02 Dec 2016 15:11:18 +, Grant Edwards wrote: > I don't know what the "addr" array contains, but if addr is a byte > string, then the "int()" call is not needed, in Pythong 3, a byte is > already an integer: > > def format_ip(a): >return '.'.join(str(b) for b in a) > > addr = b'\x12\x34\x56\x78' > > print(format_ip(addr)) It is a byte string just like your 'addr =' example and the above code works perfectly. Thank you. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: Request Help With Byte/String Problem
On Fri, 02 Dec 2016 19:39:39 +, Grant Edwards wrote: > On 2016-12-02, Wildman via Python-list wrote: >> On Fri, 02 Dec 2016 15:11:18 +, Grant Edwards wrote: >> >>> I don't know what the "addr" array contains, but if addr is a byte >>> string, then the "int()" call is not needed, in Pythong 3, a byte is >>> already an integer: >>> >>> def format_ip(a): >>>return '.'.join(str(b) for b in a) >>> >>> addr = b'\x12\x34\x56\x78' >>> >>> print(format_ip(addr)) >> >> It is a byte string just like your 'addr =' example and >> the above code works perfectly. > > More importantly, you've now learned about generator comprehensions > (aka generator expressions) and the string type's "join" method. ;) I have seen the join method before but because of my lack of experience it didn't occur to me to use it. I bet I will remember it from now on. I stuck a few code examples into my 'snips' directory. Generator expressions are new to me. I have seen it's use but I didn't understand what it was and what it was doing, until now. Thanks again. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Detect Linux Runlevel
I there a way to detect what the Linux runlevel is from within a Python program? I would like to be able to do it without the use of an external program such as 'who' or 'runlevel'. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: Detect Linux Runlevel
On Mon, 05 Dec 2016 16:25:56 -0500, DFS wrote: > On 12/05/2016 03:58 PM, Wildman wrote: >> I there a way to detect what the Linux runlevel is from >> within a Python program? I would like to be able to do >> it without the use of an external program such as 'who' >> or 'runlevel'. > > > Why not? > > '>>> import os > '>>> os.system("systemctl get-default") > graphical.target > > > > systemd 'graphical.target' corresponds to the old runlevel 5. Thanks but I knew about systemctl. As I already said my goal is to do it without the use of an external program. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: Detect Linux Runlevel
On Mon, 05 Dec 2016 23:59:48 +0200, Marko Rauhamaa wrote: > Wildman : >> Thanks but I knew about systemctl. As I already said my goal is to do >> it without the use of an external program. > > Inspect: > >https://github.com/systemd/systemd/blob/master/src/systemctl/systemctl.c> > > In particular: > >get_state_one_unit() Too bad I don't speak C. I am an amateur programmer and most or all my experience has been with assembly and various flavors of BASIC, including VB and PowerBASIC. I did look over the code but I guess I'm just a rebel without a clue. > Then, proceed to: > >https://dbus.freedesktop.org/doc/dbus-python/doc/tutorial.html> > > > Marko Even if I could figure this out, I can't depend on systemd being installed. The way things are going that may change tho. I have bookmarked the pages for possible future use. Thank you, I do appreciate your post. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: Detect Linux Runlevel
On Mon, 05 Dec 2016 15:39:24 -0700, Michael Torrie wrote: > On 12/05/2016 03:34 PM, Wildman via Python-list wrote: >> Too bad I don't speak C. I am an amateur programmer and most or all >> my experience has been with assembly and various flavors of BASIC, >> including VB and PowerBASIC. I did look over the code but I guess >> I'm just a rebel without a clue. > > May I ask what you are trying to accomplish? Why does the runlevel matter? Of course you may. It is part of a program I'm working on that reports different information about the Linux system it is running on. A program similar to inxi. And I am trying to write it without using external programs, where possible. I am a hobby programmer and I've been trying to learn python for a few months now. The program is 'worthlessware' but it is a 'learning experience' for me. A friend wrote a similar program in Bash script and I have been working on translating it to Python. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: Detect Linux Runlevel
On Mon, 05 Dec 2016 16:08:57 -0600, Tim Chase wrote: > On 2016-12-05 14:58, Wildman via Python-list wrote: >> I there a way to detect what the Linux runlevel is from >> within a Python program? I would like to be able to do >> it without the use of an external program such as 'who' >> or 'runlevel'. > > You can use something like > > https://gist.github.com/likexian/f9da722585036d372dca > > to parse the /var/run/utmp contents. Based on some source-code > scrounging, it looks like you want the first field to be "1" for the > "runlevel" account. To extract the actual runlevel, you can take > the PID value from the second column ("53" in my example here) and > take it's integer value mod 256 (AKA "& 0xff") to get the character > value. So chr(int("53") & 0xff) returns "5" in my case, which is my > runlevel. > > Additional links I found helpful while searching: > > https://casper.berkeley.edu/svn/trunk/roach/sw/busybox-1.10.1/miscutils/runlevel.c > https://github.com/garabik/python-utmp > > -tkc That is exactly the kind of thing I was looking for. Thank you. Now all I have to do is get it to work with Python3. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: Detect Linux Runlevel
On Mon, 05 Dec 2016 18:25:58 -0700, Michael Torrie wrote: > I think Python is a good choice for such a utility, but I agree it is > much better to rely on these external utilities as children to do the > platform-dependent work, rather than try to re-implement everything in > Python. A long time ago I wrote a simple wrapper to Popen that would > run a command and return the standard out and standard error to me. My rational is that all Linux distros are not created equal. One comes with one certain set of utilities and another can have different ones. I can't always depend on a given utility being there. And there is not way to know the names of same utility across all distros. This is especially a problem when comparing .rpm with .deb based distros. In cases where I have to use an external program, I mean in cases where there is no apparent Python solution, I check for the existence of that program and just skip over that section of the code if it is not found. BTW here is a link for the Bash script I mentioned in case you would like to take a look at it. The guy who wrote it had only been learning Bash for a few months. Not bad. I have tried to tweak an interest in him for Python but he sticks with Bash. He says that is the best language for programming on Linux and he is not interested in GUI programming. https://github.com/marek-novotny/linfo -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: Detect Linux Runlevel
On Mon, 05 Dec 2016 20:46:22 -0700, Michael Torrie wrote: > On 12/05/2016 08:27 PM, Wildman via Python-list wrote: >> On Mon, 05 Dec 2016 18:25:58 -0700, Michael Torrie wrote: >> >>> I think Python is a good choice for such a utility, but I agree it is >>> much better to rely on these external utilities as children to do the >>> platform-dependent work, rather than try to re-implement everything in >>> Python. A long time ago I wrote a simple wrapper to Popen that would >>> run a command and return the standard out and standard error to me. >> >> My rational is that all Linux distros are not created equal. >> One comes with one certain set of utilities and another can >> have different ones. I can't always depend on a given >> utility being there. And there is not way to know the >> names of same utility across all distros. This is especially >> a problem when comparing .rpm with .deb based distros. > > Well this is a problem regardless of which scripting language you choose > and the solutions will be the same. It is a problem only if you depend on the utility. > Personally for a script of this type, I'd probably stick with Bash > myself. In most cases I would agree with that, but, in this case my goal is learning Python. I did write a couple of programs with Bash several months ago to learn a little about it. One will take an image and convert it into an X-Face header and the other will take an image and convert it into a Face header. I later wrote GUI versions of the programs with Python and Tkinter. BTW, I don't depend on programming for a living. I would be in bad shape if I did. It is a hobby that I greatly enjoy. And, being in my later years, it keeps my mind sharp(er). > Which by the way is what inxi is written in. Yes, I was aware of that. It's over 12,000 lines! -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: Detect Linux Runlevel
On Mon, 05 Dec 2016 21:42:52 -0600, Tim Chase wrote: > On 2016-12-05 18:26, Wildman via Python-list wrote: >> On Mon, 05 Dec 2016 16:08:57 -0600, Tim Chase wrote: >> >> > On 2016-12-05 14:58, Wildman via Python-list wrote: >> >> I there a way to detect what the Linux runlevel is from >> >> within a Python program? I would like to be able to do >> >> it without the use of an external program such as 'who' >> >> or 'runlevel'. >> > >> > You can use something like >> > >> > https://gist.github.com/likexian/f9da722585036d372dca >> > >> > to parse the /var/run/utmp contents. Based on some source-code >> > scrounging, it looks like you want the first field to be "1" for >> > the "runlevel" account. To extract the actual runlevel, you can >> > take the PID value from the second column ("53" in my example >> > here) and take it's integer value mod 256 (AKA "& 0xff") to get >> > the character value. So chr(int("53") & 0xff) returns "5" in my >> > case, which is my runlevel. >> > >> > Additional links I found helpful while searching: >> > >> > https://casper.berkeley.edu/svn/trunk/roach/sw/busybox-1.10.1/miscutils/runlevel.c >> > https://github.com/garabik/python-utmp >> >> That is exactly the kind of thing I was looking for. Thank you. >> Now all I have to do is get it to work with Python3. > > This works based on my poking at it in both Py2 and Py3: That works perfectly. I owe you a big thanks. That was a lot of work and time on your part. I really appreciate it. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: Detect Linux Runlevel
On Tue, 06 Dec 2016 01:14:35 +0100, Bernd Nawothnig wrote: > On 2016-12-05, Wildman wrote: >> And I am trying to write it without using external programs, where >> possible. > > That is not the Unix way. Yes, but it is my way. >> I am a hobby programmer and I've been trying to learn python >> for a few months now. The program is 'worthlessware' but it >> is a 'learning experience' for me. > > It looks for me like a worthless learning experience. It is sad that you consider learning something new to be worthless. I used the term "worthlessware" in an economical sense, meaning it has little or no commercial value. However, from a learning standpoint I consider it to be priceless. >> A friend wrote a similar program in Bash script and I have been >> working on translating it to Python. > > Stay with shell script for such tasks. It is never a good idea to > choose the programming language before closer evaluating the problem. You have a right to your opinion but I fail to see what that has to do with the price of eggs. I picked Python just because I wanted to learn it not because I had a particular problem to solve. If your job was to advocate Python, I would suggest you find another line of work. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: Detect Linux Runlevel
On Mon, 05 Dec 2016 16:08:57 -0600, Tim Chase wrote: > On 2016-12-05 14:58, Wildman via Python-list wrote: >> I there a way to detect what the Linux runlevel is from >> within a Python program? I would like to be able to do >> it without the use of an external program such as 'who' >> or 'runlevel'. > > You can use something like > > https://gist.github.com/likexian/f9da722585036d372dca I went back to the code from the above link to try to get it to work with Python3, just to see if I could. The problem was that the output was in bytes or partly in bytes like this: ['1', '53', "b'~\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\ x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\ (...) I was trying to convert the bytes to strings and that is what I never got to work right. It didn't occur to me that all I needed was the first two fields and they were already strings. The 'print output' part of the original code was this which printed everything. Over kill for my use: data = read_xtmp('/var/run/utmp') for i in data: print i I changed it to this and it works: data = read_xtmp('/var/run/utmp') for i in data: if i[0] == "1": print("Runlevel: " + chr(int(i[1]) & 0xFF)) break The output: Runlevel: 5 If I had tried this in the beginning, it would have save you a lot of work. Since both versions of the code works, which one do you recommend? Or does it matter? -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: Detect Linux Runlevel
On Tue, 06 Dec 2016 13:06:35 -0600, Tim Chase wrote: > On 2016-12-06 12:10, Wildman via Python-list wrote: >> If I had tried this in the beginning, it would have >> save you a lot of work. >> >> Since both versions of the code works, which one do >> you recommend? Or does it matter? > > Heh, I'm not sure it matters much. The code I provided should be > expandable for tidily handling other entries in utmp, allowing you to > search for other system events that might interest you (check out the > invocation of the filter() function which filters by type). Yes, your code is very expandable and I will keep it archived for that reason. In the future I might want to delve further into utmp. But right now all I need is the runlevel. > Since I've already done the leg-work, I mildly advocate using my > version since it should be pretty clean and easy to expand. But if > you want the satisfaction of using your code, I won't take offense :-) > > -tkc Yes, I think I will use my code. No offense intended. :-) Again, I do appreciate all your work on my behalf. I hope some day I can return the favor. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: Detect Linux Runlevel
On Tue, 06 Dec 2016 09:45:05 -0700, Michael Torrie wrote: > I appreciate your measured response to what could be seen as an > inflammatory post. It was inflammatory and I considered a different response but after the knee jerking, I give it some thought and decided otherwise. The simple fact is I'm an outsider here. Over the last few months I have received some good advice and help from some good folks and for that I am grateful. I do not want to do anything that could jeopardize that. So I will try my best to keep my posts civil. And I thank you for your words. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: Detect Linux Runlevel
On Tue, 06 Dec 2016 13:06:35 -0600, Tim Chase wrote: > I forgot to mention that I want to include your name in the final script as a contributor, if that is ok. You will get a cut of the royalties. Lets see, how much is 20% of $0.00? Well, I'll let my account work that out as soon as she gets home from the grocery. -- GNU/Linux user #557453 The voices in my head may not be real but they have some good ideas. -- https://mail.python.org/mailman/listinfo/python-list
Re: CLP stats: last 500 posts
On Fri, 09 Dec 2016 16:07:16 -0500, DFS wrote: > code (py2.7) > -- > import sys as y,nntplib as t,datetime as d > s='' > g=y.argv[1] > n=t.NNTP(s,119,'','') > r,a,b,e,gn=n.group(g) > def printStat(st,hd,rg): > r,d=n.xhdr(st,'%s-%s'%rg) > p=[] > for i in range(len(d)): > v=d[i][1] > if st=='Subject':v=v[4:] if v[:3]=='Re:' else v > p.append(v) > x=[(i,p.count(i)) for i in set(p)] > x.sort(key=lambda s:(-s[1],s[0].lower())) > print('Posts %s %s'%(len(set(p)),hd)) > for v in x: print(' %s %s'%(v[1],v[0])) > print > print 'As of '+d.datetime.now().strftime("%I:%M%p %B %d, %Y") + '\n' > m=(int(e)-int(y.argv[3])+1,int(e)) > printStat("From","Posters",m) > printStat("Subject","Subjects",m) > printStat("User-Agent","User-Agents",m) > n.quit() > -- > > usage on Windows: > $ python stats.py group last N > $ python stats.py comp.lang.python last 500 Do you happen to have a translation of the code that will run on Linux? $ ./nntp.py comp.lang.python last 500 Traceback (most recent call last): File "./nntp.py", line 7, in n=t.NNTP(s,119,'','') File "/usr/lib/python2.7/nntplib.py", line 119, in __init__ self.sock = socket.create_connection((host, port)) File "/usr/lib/python2.7/socket.py", line 553, in create_connection for res in getaddrinfo(host, port, 0, SOCK_STREAM): socket.gaierror: [Errno -2] Name or service not known -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: CLP stats: last 500 posts
On Sat, 10 Dec 2016 12:31:33 -0500, DFS wrote: > On 12/10/2016 12:06 PM, Wildman wrote: >> On Fri, 09 Dec 2016 16:07:16 -0500, DFS wrote: >> >>> code (py2.7) >>> -- >>> import sys as y,nntplib as t,datetime as d >>> s='' >>> g=y.argv[1] >>> n=t.NNTP(s,119,'','') >>> r,a,b,e,gn=n.group(g) >>> def printStat(st,hd,rg): >>> r,d=n.xhdr(st,'%s-%s'%rg) >>> p=[] >>> for i in range(len(d)): >>> v=d[i][1] >>> if st=='Subject':v=v[4:] if v[:3]=='Re:' else v >>> p.append(v) >>> x=[(i,p.count(i)) for i in set(p)] >>> x.sort(key=lambda s:(-s[1],s[0].lower())) >>> print('Posts %s %s'%(len(set(p)),hd)) >>> for v in x: print(' %s %s'%(v[1],v[0])) >>> print >>> print 'As of '+d.datetime.now().strftime("%I:%M%p %B %d, %Y") + '\n' >>> m=(int(e)-int(y.argv[3])+1,int(e)) >>> printStat("From","Posters",m) >>> printStat("Subject","Subjects",m) >>> printStat("User-Agent","User-Agents",m) >>> n.quit() >>> -- >>> >>> usage on Windows: >>> $ python stats.py group last N >>> $ python stats.py comp.lang.python last 500 >> >> Do you happen to have a translation of the code that will >> run on Linux? >> >> $ ./nntp.py comp.lang.python last 500 >> Traceback (most recent call last): >> File "./nntp.py", line 7, in >> n=t.NNTP(s,119,'','') >> File "/usr/lib/python2.7/nntplib.py", line 119, in __init__ >> self.sock = socket.create_connection((host, port)) >> File "/usr/lib/python2.7/socket.py", line 553, in create_connection >> for res in getaddrinfo(host, port, 0, SOCK_STREAM): >> socket.gaierror: [Errno -2] Name or service not known > > > That code runs unchanged on py2.7 on Linux (I just now tested it). > > You just need to put in your own credentials for the newsserver, user > and password (lines 2 and 4). OK, thanks. That didn't occur to me although it should have. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: CLP stats: last 500 posts
On Sat, 10 Dec 2016 12:31:33 -0500, DFS wrote: > After correcting my stupid oversights, the code runs fine up to the point where the user agents are printed. I get an error saying that 'User-Agent' is an unsupported header field. It must have something to do with giganews. If I use aioe.org I don't get the error and the user agents are printed. I don't think it is a problem with the code but any thoughts why giganews is not playing nice? And it is not related to the python group. I have tried on other groups and i get the same error. Here is the complete error message. Traceback (most recent call last): File "./nntp.py", line 27, in printStat("User-Agent","User-Agents",m) File "./nntp.py", line 12, in printStat r,d=n.xhdr(st,'%s-%s'%rg) File "/usr/lib/python2.7/nntplib.py", line 470, in xhdr resp, lines = self.longcmd('XHDR ' + hdr + ' ' + str, file) File "/usr/lib/python2.7/nntplib.py", line 273, in longcmd return self.getlongresp(file) File "/usr/lib/python2.7/nntplib.py", line 244, in getlongresp resp = self.getresp() File "/usr/lib/python2.7/nntplib.py", line 229, in getresp raise NNTPPermanentError(resp) nntplib.NNTPPermanentError: 501 unsupported header field -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: CLP stats: last 500 posts
On Sun, 11 Dec 2016 12:03:07 -0500, DFS wrote: > For this short stat version I only used the 'User-Agent' header. I have > a longer version that uses both 'User-Agent' and 'X-Newsreader' > > > You can put a conditional in place for now: > > if s='giganews': > printStat("X-Newsreader","News Readers",m) > else: > printStat("User-Agent","User-Agents",m) Thanks but I had already tried X-Newsreader and I got the same result. It is odd because if you look at my headers there is an entry for User-Agent User-Agent: Pan/0.139 (Sexual Chocolate; GIT bf56508 git://git.gnome.org/pan2; x86_64-pc-linux-gnu) -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: Problem running Python 3.5.2 on school network PC
On Thu, 15 Dec 2016 11:11:51 -0500, Jed Mack wrote: > We are having a problem running Python 3.5.2 on Windows 10 x64 computers, > which are members of a school network. > > > > The program seems to install correctly, but when we try to run the program > it stops and give an error message saying: > > > > *Fatal Python error: Py_Initialize: unable to load the file system codec* > > *Traceback (most recent call last):* > > * File "C:\Program Files\Python35\lib\encodings\__init__.py", line 31, in< > module>* > > *zipimport.ZipImportError: can't find module 'codecs'* > > > > > > On a Windows 7 PCs, on the same network, the program runs with no problems. > > > > We have no one here who is familiar with Python. Do you have any > additional information on this error, and suggestions for fixing it? > > > > We have a teacher who needs this program on Windows 10 PCs for students to > use beginning January 3. > > > > Thanks, > > Jed Mack You might try adding the installation folders to the path, if it hasn't been done already. Change 'python' to the actual folder name. C:\python C:\python\Lib\site-packages C:\python\Scripts -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: learning and experimenting python.
On Fri, 30 Dec 2016 11:08:30 -0800, einstein1410 wrote: > LAN you are right. I am agree with you that it's easy to recognise. > > But look > $ for normal user > # for special user/root > % for other shell For python > And so on... > Why? > Why their developer selected that? > Is there any special reason? That would be questions for the developer(s). As an end-user, the only answer I can give is, it is that way because that is the way it is. -- GNU/Linux user #557453 Keyboard not detected! Press any key to continue... -- https://mail.python.org/mailman/listinfo/python-list
Re: learning and experimenting python.
On Fri, 30 Dec 2016 15:34:16 -0800, einstein1410 wrote: > You are also confusing me. > But there mustbe some reason. > What happens if your student questions you like this.? I am not a teacher. > And may be those who questions like this will surely be the developer of its > successor language. > Because out of thousands, only one may asks this, whom you all will consider > fool, but he's the only genius. To get an answer to your questions you need to ask the developer. I don't think I can get any clearer. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: learning and experimenting python.
On Fri, 30 Dec 2016 23:39:43 +, Erik wrote: > On 30/12/16 23:34, einstein1...@gmail.com wrote: >> You are also confusing me. >> But there mustbe some reason. >> What happens if your student questions you like this.? >> And may be those who questions like this will surely be the developer of its >> successor language. >> Because out of thousands, only one may asks this, whom you all will consider >> fool, but he's the only genius > > Do not feed the troll. > > E. Please explain how what I said is trolling. Perhaps it was a little snide but I tend to get that way when trying to explain the obvious. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: learning and experimenting python.
On Fri, 30 Dec 2016 19:23:17 -0700, Michael Torrie wrote: > On 12/30/2016 07:05 PM, Wildman via Python-list wrote: >> On Fri, 30 Dec 2016 23:39:43 +, Erik wrote: >> >>> On 30/12/16 23:34, einstein1...@gmail.com wrote: >>>> You are also confusing me. >>>> But there mustbe some reason. >>>> What happens if your student questions you like this.? >>>> And may be those who questions like this will surely be the developer of >>>> its successor language. >>>> Because out of thousands, only one may asks this, whom you all will >>>> consider fool, but he's the only genius >>> >>> Do not feed the troll. >>> >>> E. >> >> Please explain how what I said is trolling. Perhaps it was a little >> snide but I tend to get that way when trying to explain the obvious. > > Hmm. I thought he was referring to einstein1410... It was his message > he was replying to, not yours, and I took it as a request to the rest of > us (sorry, Erik--couldn't resist posting). I took it to mean that he was telling einstein1410 to not feed the trolls. If I am wrong then my apologies to Erik. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: learning and experimenting python.
On Sun, 01 Jan 2017 10:41:22 -0800, einstein1410 wrote: > What contribution I had made especially valuable? Ask your mommy what sarcasm means. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: learning and experimenting python.
On Sun, 01 Jan 2017 23:02:34 -0800, einstein1410 wrote: > I really don't care the person like you. > Leave my posts, if don't like it. > Why wasting your as well as my time. > Just get lost man, or shut up. _ _ |_| |_| | | /^^^\ | | _| |_ (| "o" |) _| |_ _| | | | _(_---_)_ | | | |_ | | | | |' |_| |_| `| | | | | | | / \ | | \/ / /(. .)\ \ \/ \/ / / | . | \ \ \/ \ \/ /||Y||\ \/ / \__/ || || \__/ () () || || ooO Ooo -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: learning and experimenting python.
On Mon, 02 Jan 2017 20:25:25 -0800, Ethan Furman wrote: > On 01/02/2017 09:53 AM, Wildman via Python-list wrote: > > [rude ascii art omitted] > > That is a completely inappropriate response. Yes it was. I tend to get upset when told to shut up and go away for no good reason. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: How coding in Python is bad for you
On Mon, 23 Jan 2017 20:39:26 +, Jon Ribbens wrote: > On 2017-01-23, alister wrote: >> On Tue, 24 Jan 2017 07:19:42 +1100, Chris Angelico wrote: >>> I believe that's "bad for you" in the sense that chocolate is bad for >>> you. >>> >>> It isn't. >> >> chocolate is a poison (lethal dose for a human approx 22lb) > > That's a meaningless statement. *Everything* is a poison > in sufficient quantities. Yes, even water. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: Is shutil.get_terminal_size useless?
On Sat, 28 Jan 2017 19:03:42 +1100, Steve D'Aprano wrote: > shutil.get_terminal_size returns the wrong values when you pipe your output > to another process, even it you do so in a terminal. Consider this script: > > > import os > import shutil > print('shutil:', shutil.get_terminal_size(fallback=(999, 999))) > print('os:', os.get_terminal_size(0)) > > > That uses two different methods to get the terminal size. If I run that in a > terminal in the normal way, it works fine, returning the correct size for > my terminal: > > > [steve@ando ~]$ python3.5 test_gts.py > shutil: os.terminal_size(columns=116, lines=29) > os: os.terminal_size(columns=116, lines=29) > > > But if I pipe the output to something else, the shutil version fails to > determine the correct terminal size, and falls back on the default: > > > [steve@ando ~]$ python3.5 test_gts.py | cat > shutil: os.terminal_size(columns=999, lines=999) > os: os.terminal_size(columns=116, lines=29) > > > while the os version gives the correct result. > > Is shutil.get_terminal_size useless? When, if ever, should I use it in > preference to the os version? If the shutil version is broken, can it be > fixed? > > > Thanks to Bernardas Ališauskas: > > http://granitosaurus.rocks/getting-terminal-size.html I can suggest a third approach to try but I have not tried piping it. YMMV. import fcntl import os import struct import termios tty = os.open(os.ctermid(), os.O_RDONLY) ts = struct.unpack("hh", fcntl.ioctl(tty, termios.TIOCGWINSZ, "1234")) os.close(tty) columns = ts[1] rows = ts[0] print(str(columns) + "x" + str(rows)) -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: How to know what to install (Ubuntu/Debian) for a given import?
On Wed, 01 Feb 2017 17:12:26 +, Chris Green wrote: > I'm often hitting this problem, how does one find out what package to > install to provide what a give import needs? > > Currently I'm modifying some code which has 'import gtk', I want to > migrate from Python 2 to Python 3 if I can but at the moment the > import fails in Python 3. > > There are dozens of packages in the Ubuntu repositories which *might* > provide what I need I don't want to try them all! So, is there an > easy way to find out? > > ... and while I'm here, can someone tell me what package I need? Try this: import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: How to know what to install (Ubuntu/Debian) for a given import?
On Wed, 01 Feb 2017 19:15:13 +, Chris Green wrote: > Wildman wrote: >> On Wed, 01 Feb 2017 17:12:26 +, Chris Green wrote: >> >> > I'm often hitting this problem, how does one find out what package to >> > install to provide what a give import needs? >> > >> > Currently I'm modifying some code which has 'import gtk', I want to >> > migrate from Python 2 to Python 3 if I can but at the moment the >> > import fails in Python 3. >> > >> > There are dozens of packages in the Ubuntu repositories which *might* >> > provide what I need I don't want to try them all! So, is there an >> > easy way to find out? >> > >> > ... and while I'm here, can someone tell me what package I need? >> >> Try this: >> >> import gi >> gi.require_version('Gtk', '3.0') >> from gi.repository import Gtk >> > That works but it's a workaround rather than the proper way to do it > isn't it? It is the proper way. This page helps explain it. http://askubuntu.com/questions/784068/what-is-gi-repository-in-python > ... and doesn't it need an internet connection? No. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: How to know what to install (Ubuntu/Debian) for a given import?
On Wed, 01 Feb 2017 21:29:00 +, Chris Green wrote: > Wildman wrote: >> On Wed, 01 Feb 2017 19:15:13 +, Chris Green wrote: >> >> > Wildman wrote: >> >> On Wed, 01 Feb 2017 17:12:26 +, Chris Green wrote: >> >> >> >> > I'm often hitting this problem, how does one find out what package to >> >> > install to provide what a give import needs? >> >> > >> >> > Currently I'm modifying some code which has 'import gtk', I want to >> >> > migrate from Python 2 to Python 3 if I can but at the moment the >> >> > import fails in Python 3. >> >> > >> >> > There are dozens of packages in the Ubuntu repositories which *might* >> >> > provide what I need I don't want to try them all! So, is there an >> >> > easy way to find out? >> >> > >> >> > ... and while I'm here, can someone tell me what package I need? >> >> >> >> Try this: >> >> >> >> import gi >> >> gi.require_version('Gtk', '3.0') >> >> from gi.repository import Gtk >> >> >> > That works but it's a workaround rather than the proper way to do it >> > isn't it? >> >> It is the proper way. This page helps explain it. >> >> http://askubuntu.com/questions/784068/what-is-gi-repository-in-python >> > OK, thank you, what a strange way to do it. I am sure there is a reason and I believe it has something to do with the fact that GTK3 is a recent addition. Things might change in the future. >> > ... and doesn't it need an internet connection? >> >> No. >> > OK, no problem, but isn't it very non-portable? I don't see why not. It should work on any system that has Python3 installed, at least that is my understanding. I'm sure someone will correct me if I'm wrong. OTOH if you want in insure 100% portability with any script, you can use pyinstaller. To install for Python2: pip install pyinstaller For Python3: pip3 install pyinstaller http://www.pyinstaller.org/ -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: best way to ensure './' is at beginning of sys.path?
On Fri, 03 Feb 2017 11:06:00 -0500, Neal Becker wrote: > I want to make sure any modules I build in the current directory overide any > others. To do this, I'd like sys.path to always have './' at the beginning. > > What's the best way to ensure this is always true whenever I run python3? In python, this method will work but it is only in effect for the running process that calls it while it is running. It is not system wide and it is not permanent. import os os.environ["PATH"] = os.environ["PATH"] + ":./" or os.environ["PATH"] = "./:" + os.environ["PATH"] (assuming Linux platform) To make it permanent for a certain user, add one of these lines to /home/user/.profile and log out/in: PATH="$PATH:./" or PATH="./:$PATH" To make it permanent for all users, add one of these pairs of lines to /etc/rc.local and reboot: export PATH=$PATH:./ exit 0 or export PATH=./:$PATH exit 0 Add 'exit 0' only if it doesn't exist already and it must be the last line. If /etc/rc.local does not exist, create it. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: best way to ensure './' is at beginning of sys.path?
On Fri, 03 Feb 2017 12:58:15 -0600, Wildman wrote: > On Fri, 03 Feb 2017 11:06:00 -0500, Neal Becker wrote: > >> I want to make sure any modules I build in the current directory overide any >> others. To do this, I'd like sys.path to always have './' at the beginning. >> >> What's the best way to ensure this is always true whenever I run python3? > > In python, this method will work but it is only in effect > for the running process that calls it while it is running. > It is not system wide and it is not permanent. > > import os > os.environ["PATH"] = os.environ["PATH"] + ":./" > or > os.environ["PATH"] = "./:" + os.environ["PATH"] > > (assuming Linux platform) > To make it permanent for a certain user, add one of > these lines to /home/user/.profile and log out/in: > > PATH="$PATH:./" > or > PATH="./:$PATH" > > To make it permanent for all users, add one of > these pairs of lines to /etc/rc.local and reboot: > > export PATH=$PATH:./ > exit 0 > or > export PATH=./:$PATH > exit 0 > > Add 'exit 0' only if it doesn't exist already and it > must be the last line. If /etc/rc.local does not > exist, create it. Sorry, I forgot something important. If you use /etc/rc.local, the execute bit must be set. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: best way to ensure './' is at beginning of sys.path?
On Fri, 03 Feb 2017 13:19:30 -0700, Michael Torrie wrote: > On 02/03/2017 12:07 PM, Wildman via Python-list wrote: >> Sorry, I forgot something important. If you use >> /etc/rc.local, the execute bit must be set. > > I don't think this is what Neal Becker was asking about. He's talking > about the Python module search path (sys.path) not the operating system > PATH variable. Correct me if I'm wrong. After re-reading the post I see you are correct. I will endeavor to read a little closer and a little slower in the future. -- GNU/Linux user #557453 "Well, that's quite different. Never mind." -Emily Litella -- https://mail.python.org/mailman/listinfo/python-list
Re: best way to ensure './' is at beginning of sys.path?
On Sat, 04 Feb 2017 09:25:42 +1100, Cameron Simpson wrote: > On 03Feb2017 14:55, Wildman wrote: >>On Fri, 03 Feb 2017 13:19:30 -0700, Michael Torrie wrote: >> >>> On 02/03/2017 12:07 PM, Wildman via Python-list wrote: >>>> Sorry, I forgot something important. If you use >>>> /etc/rc.local, the execute bit must be set. >>> >>> I don't think this is what Neal Becker was asking about. He's talking >>> about the Python module search path (sys.path) not the operating system >>> PATH variable. Correct me if I'm wrong. >> >>After re-reading the post I see you are correct. >>I will endeavor to read a little closer and a >>little slower in the future. > > Also, what you describe with rc.local wouldn't work anyway, even if it had > ben > what was asked. > > Cheers, > Cameron Simpson Of course, you are correct. I don't know where my head was. I think my tongue got in front of my eye teeth and I could not see what I was saying. :-) If anyone is interested the correct way is to add this to /etc/profile (at the bottom): PATH=$PATH:./ export PATH -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: best way to ensure './' is at beginning of sys.path?
On Sat, 04 Feb 2017 11:27:01 +0200, Jussi Piitulainen wrote: > Wildman writes: > > [snip] > >> If anyone is interested the correct way is to add this to >> /etc/profile (at the bottom): >> >> PATH=$PATH:./ >> export PATH > > Out of interest, can you think of a corresponding way that a mere user > can remove the dot from their $PATH after some presumably well-meaning > system administrator has put it there? > > Is there any simple shell command for it? One that works whether the dot > is at the start, in the middle, or at the end, and with or without the > slash, and whether it's there more than once or not at all. > > And I'd like it to be as short and simple as PATH="$PATH:.", please. No, I do not know. You might try your question in a linux specific group. Personally I don't understand the danger in having the dot in the path. The './' only means the current directory. DOS and Windows has searched the current directory since their beginning. Is that also dangerous? -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: best way to ensure './' is at beginning of sys.path?
On Sat, 04 Feb 2017 18:25:03 +, Grant Edwards wrote: > On 2017-02-04, Wildman via Python-list wrote: > >> No, I do not know. You might try your question in a linux specific >> group. Personally I don't understand the danger in having the dot >> in the path. The './' only means the current directory. > > It allows a malicous user to put an evil executable someplace public > like /tmp and have it executed accidentally. For example, let's say > this executable file was named "sl" and placed in /tmp. > > --sl-- > #!/bin/bash > rm -rf $HOME > -- > > The next time you are in the /tmp directory looking for something, can > you guess what happens when you mistype "ls" as "sl"? > >> DOS and Windows has searched the current directory since their >> beginning. Is that also dangerous? > > Yes. Your scenario assumes the malicious user has root access to be able to place a file into /tmp. And there would have to be some reason why I would be looking around in /tmp. After 10 years of using Linux, it hasn't happened yet. And last I would have to be a complete idiot. I suppose all that could be a reality, but, how many computers do you know of have been compromised in this manor? -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: best way to ensure './' is at beginning of sys.path?
On Sat, 04 Feb 2017 19:12:55 +, Grant Edwards wrote: > On 2017-02-04, Wildman via Python-list wrote: >>> >>> The next time you are in the /tmp directory looking for something, can >>> you guess what happens when you mistype "ls" as "sl"? >>> >>>> DOS and Windows has searched the current directory since their >>>> beginning. Is that also dangerous? >>> >>> Yes. >> >> Your scenario assumes the malicious user has root access >> to be able to place a file into /tmp. > > Nope. /tmp is world-writable. Yea, I realized that right after I clicked post. I was thinking of the fact that /tmp is owned by root. >> And there would have to be some reason why I would be looking around >> in /tmp. After 10 years of using Linux, it hasn't happened yet. >> And last I would have to be a complete idiot. > > To have put '.' in your path? That is something I would never do. Not because I think it is dangerous but because it had never occurred to me. Anything that I run in the current directory, I always prefix it with './' out of habit. Never thought of doing anything else. > Or to have typed 'sl' by mistake? Well, maybe not an idiot but something would have to be going on to misspell a two letter command. >> I suppose all that could be a reality, but, how many computers do >> you know of have been compromised in this manor? > > I've known a few people over the years who've been caught by that > trick. The "evil" program was always more of a joke and did no real > harm. I don't consider that being compromised. Sure, you could trick someone into running a program that could mess with $HOME but that is all. For anyone, like me, that makes regular backups, that is not a big problem. To do any real damage to the system or install a key logger or some other malicious software, root access would be required. As a Linux user you already know that. That is the scenario where idiot would be the correct term. -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: best way to ensure './' is at beginning of sys.path?
On Mon, 06 Feb 2017 09:07:34 +1100, Steve D'Aprano wrote: > On Sun, 5 Feb 2017 07:01 pm, Wildman wrote: > >> Sure, you >> could trick someone into running a program that could >> mess with $HOME but that is all. For anyone, like me, >> that makes regular backups, that is not a big problem. >> To do any real damage to the system or install a key >> logger or some other malicious software, root access >> would be required. > > The complacency of Linux users (and I include myself here) is frightening. No comment. :-) > Why do you value the OS more than your own personal files? In the worst > case, you could re-install the OS is a couple of hours effort. Losing your > personal files, your home directory and email, could be irreplaceable. I wold not say I value the OS more. It is that anything I have that I consider important does not stay in $HOME very long without being backed up or moved to an external drive. > You're also ignoring the possibility of privilege-escalation attacks. The odds of that happening is very low. You should know that. There are very few actual exploits in the wild. Whenever one is discovered, it is fixed quickly. You would be hard pressed to find more than a few examples of where a vulnerability was actually exploited. > As far as "regular backups", well, you're just not thinking deviously > enough. If I were to write a ransomware application, running as the regular > user, I would have the application encrypt files and emails just a few at a > time, over a period of many weeks, gradually increasing the rate. By the > time the victim has realised that their files have been encrypted, their > backups have been compromised too: you can restore from backup, but you'll > be restoring the encrypted version. > > Obviously this requires tuning. How many files will people be willing to > just write-off as lost rather than pay the ransom? How quickly do you > accelerate the process of encrypting files to maximize the number of people > who will pay? I should explain a few things that will make my position clearer. First of all, I am not advocating for anyone to change their computing practices. If you are comfortable with your methods, who am I to tell you different? I am an amateur programmer and therefore I do not make a living writing code. If I suddenly lost all my code, it would not be the end of the world for me. I would have enjoyment writing it again. Because of this I am not very paranoid when it come to my computer data, although I do practice safe surfing when it comes to the internet. Scripting and Java stays off unless it is needed by a 'known' site. Also, I never click unknown links without doing a little sniffing first. And last I would like to say that I admit some of the scenarios you and others have laid out could happen, but, in my circumstance, it is very unlikely. One would have a hard time placing a program on my computer and running it without me knowing about it. No, that is not a challenge. :-) -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list
Re: Help with python code
On Tue, 29 Mar 2016 21:19:05 +, Rob Gaddi wrote: >> menu = input("Enter the type of pizza that you want to order from 1-5 \n") >> while menu>5 or menu <=0: >> menu = input ("Enter the right number ") >> pizza_cost = pizzatype[menu] As it has already been pointed out, a Python list starts with an index of 0. Change the last line in the above code to this... pizza_cost = pizzatype[menu - 1] Anywhere else that your code references a list index you may need to make the same change. -- GNU/Linux user #557453 May the Source be with you. -- https://mail.python.org/mailman/listinfo/python-list
Re: pygtk button right/middle click
On Wed, 30 Mar 2016 15:36:12 +, Grant Edwards wrote: > I'm trying to figure out how to get a pygtk button respond to > somehting other than just a simple "left click". With a standard > 3-button mouse, X11 provides at least 9 different "click" types, but > the pygtk button only seems to support one of them. > > [Yes, I know there are left-handled mouse configurations -- by "left" > click I'm using the common term to mean the primary mouse button.] > > After googling for some time, I haven't found any good answers. Some > people just say things like "use the button_release_event signal of > the button widget". > > But, that signal is depricated (and AFAICT still doesn't make the > button actually respond to the left/middle click by "depressing" the > way it should). > > Other answers are things like "you'll have to write you own button > class in C, not C++". > > Is the gtk button widget really incapable of handling left or middle > mouse buttons or shift/ctrl/alt modifiers? This might help... http://faq.pygtk.org/index.py?req=show&file=faq05.004.htp -- GNU/Linux user #557453 May the Source be with you. -- https://mail.python.org/mailman/listinfo/python-list
Re: pygtk button right/middle click
On Wed, 30 Mar 2016 19:23:35 +, Grant Edwards wrote: > On 2016-03-30, Grant Edwards wrote: >> On 2016-03-30, Wildman wrote: >> Is the gtk button widget really incapable of handling left or middle mouse buttons or shift/ctrl/alt modifiers? >>> >>> This might help... >>> >>> http://faq.pygtk.org/index.py?req=show&file=faq05.004.htp >> >> Yep, I found that. I'm just missing the clues required to use those >> two pieces. > > FWIW, I've decided to give up on this. Since it took only a few lines > of code to handle the "left" click, I assumed that like some other > toolkits, it would be similarly easy to handle "right" and "middle". > > I don't have the time to re-invent the wheel at the moment, so this > project will have to be postponed. I'm sorry to say I have no experience using pygtk. My only gui experience is with Tkinter. In Tk you would do something like this to trap a right-click. # create the popup menu and add commands as needed self.menu = tk.Menu(self, tearoff=0) self.menu.add_command(label="Whatever", command=self.do_whatever) # bind the button with mouse right-click self.button.bind("", self.popup) # define the handler for the menu def do_whatever(self): # do whatever # define the popup handler, this displays the menu def popup(self, event): self.menu.post(event.x_root, event.y_root) I posted this on the off chance there might be a way to translate this to gtk code. -- GNU/Linux user #557453 "The Constitution only gives people the right to pursue happiness. You have to catch it yourself." -Benjamin Franklin -- https://mail.python.org/mailman/listinfo/python-list
Re: tkinter Entry validation modes
On Sat, 02 Apr 2016 16:11:19 +0100, Mark Lawrence wrote: > A typical call to create an Entry field would be:- > > e = Entry(master, validate='all', ...) > > Once this call has been made is it possible to change the validation > mode at runtime? Background, I'm knocking up an app so I can play with > the various modes so that I can see how they work, as I'm just venturing > into the tkinter world. This is off the top of my head and I have not tested it. Since validate is a config option this might do it: e.config(validate='focus') -- GNU/Linux user #557453 The cow died so I don't need your bull! -- https://mail.python.org/mailman/listinfo/python-list