Re: Terminal Emulator (Posting On Python-List Prohibited)
On 2024-05-19, Barry via Python-list wrote: > > >> On 18 May 2024, at 16:27, Peter J. Holzer via Python-list >> wrote: >> >> I don't think Linux users have to deal with venvs > > Modern debian (ubuntu) and fedora block users installing using pip. You can't even use pip to do "user" installs? -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: Terminal Emulator (Posting On Python-List Prohibited)
On 2024-05-19, Gilmeh Serda via Python-list wrote: > On Sun, 19 May 2024 08:32:46 +0100, Alan Gauld wrote: > >> I've honestly never experienced this "nightmare". >> I install stuff and it just works. > > Hear! Hear! Me too! And all that. > > I'm on Manjaro, which is a tad finicky about other people touching its > Python since it's used for lots of things. I install things for myself > only. > > Was there a reason they chose the name Pip? I always assumed it was in honor of the PIP (Peripheral Interchange Program?) utility that was used to copy files around on CP/M and DEC's PDP-11 OSes. -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: Terminal Emulator (Posting On Python-List Prohibited)
On 2024-05-19, Alan Gauld via Python-list wrote: >> The dependency nightmare created by python, pip >> and all the rest cannot be resolved otherwise. > > I've honestly never experienced this "nightmare". > I install stuff and it just works. Same here. I occasonlly use pip to install something that isn't packaged for Gentoo, but it doesn't seem to cause problems — let alone nightmares. I also occasionally package something myself. -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: Terminal Emulator (Posting On Python-List Prohibited)
On 2024-05-18, Mats Wichmann via Python-list wrote: > Distros have do offer a good selection of packaged Python bits, yes, but > only for the version of Python that's "native" to that distro release. > If you need to test other versions of Python, you're mostly on your own. For a few years I needed both 2.x and 3.x installed, but my distro (Gentoo) handled that fine (I think most others do also). Gentoo also allows multiple minor versions to be installed (currently I have 3.11 and 3.12 on this machine). But, since Gentoo is a source-based meta-distro, when I install a Python package, the package manager knows how to install it for all installed Python versions that are supported by the package. I can't think of why I would need a venv unless I needed to test something with a Python version that isn't available for Gentoo. That said, there are currently 7 versions available (2.7.18, 3.8.19, 3.9.19, 3.10.14, 3.11.9, 3.12.3, 3.13.0). 3.13 isn't marked stable yet in the Gentoo package database, and I apparently have some Python app/package installed that doesn't yet support 3.12, so I've currently got both 3.12 and 3.11. -- https://mail.python.org/mailman/listinfo/python-list
Re: Terminal Emulator (Posting On Python-List Prohibited)
On 2024-05-18, Peter J. Holzer via Python-list wrote: > On 2024-05-16 19:46:07 +0100, Gordinator via Python-list wrote: > >> To be fair, the problem is the fact that they use Windows (but I >> guess Linux users have to deal with venvs, so we're even. > > I don't think Linux users have to deal with venvs any more than > Windows users. Maybe even less because many distributions come with > a decent set of Python packages. I've been using Python on Linux almost daily for 25 years, and I've yet to use a venv... -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: Terminal Emulator
On 2024-05-14, Alan Gauld via Python-list wrote: > On 14/05/2024 18:44, Gordinator via Python-list wrote: > >> I wish to write a terminal emulator in Python. I am a fairly >> competent Python user, and I wish to try a new project idea. What >> references can I use when writing my terminal emulator? I wish for >> it to be a true terminal emulator as well, not just a Tk text >> widget or something like that. > > The first thing is to decide which terminal. If you want to make life easier, make it a superset of a terminal that already exists in the terminfo database. Going with some sort of ANSI terminal will probably provide operability even with dumb apps which ignore $TERM and just spit out basic ANSI escape sequences. If you really want to break trail, you could invent your own control sequences, which means you'll have to write terminfo and/or termcap entries as well as the terminal emulator. > A VT100 is very different from a 3270. And even a VT330 is quite > different from a VT100 although sharing a common subset of control > codes. And if you start looking at graphical terminals things get > even more interesting! "Intersting" is putting it mildly... -- https://mail.python.org/mailman/listinfo/python-list
Re: Terminal Emulator
On 2024-05-14, Alan Gauld via Python-list wrote: > On 14/05/2024 18:44, Gordinator via Python-list wrote: > >> I wish to write a terminal emulator in Python. I am a fairly >> competent Python user, and I wish to try a new project idea. What >> references can I use when writing my terminal emulator? I wish for >> it to be a true terminal emulator as well, not just a Tk text >> widget or something like that. > > The first thing is to decide which terminal. You also need to decide if you're going to support real serial ports or just ptys. -- https://mail.python.org/mailman/listinfo/python-list
Re: How to Add ANSI Color to User Response
On 2024-04-10, Alan Gauld via Python-list wrote: > On 10/04/2024 19:50, WordWeaver Evangelist via Python-list wrote: > >> I have a simple question. I use the following textPrompt in some of my >> Jython modules: >> '\n[1;33mYour choice is? (A B C D E): ', maxChars=1, autoAccept=False, >> forceUppercase=True) >> Is there a way to add an ANSI color code to the end > > Normally, for any kind of fancy terminal work, I'd say use curses. If you want to use the terminal escape sequences provided by terminfo and ncurses, but don't want to use the ncurses windowing functions, here are some notes on how to do that: https://github.com/GrantEdwards/Python-curses-and-terminfo That too is C-Python oriented, and I don't really know how to do the same things using Jython. -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: How to Add ANSI Color to User Response
On 2024-04-10, WordWeaver Evangelist via Python-list wrote: > I have a simple question. I use the following textPrompt in some of my Jython > modules: > '\n[1;33mYour choice is? (A B C D E): ', maxChars=1, autoAccept=False, > forceUppercase=True) > Is there a way to add an ANSI color code to the end where the > conditions are, so that the color of the user’s input is of a color > of my choosing, instead of just white? I'm not sure what is meant by "the end where the conditions are", nor do I know what "textPrompt" refers to. Are you asking how to put a second escape sequence at the end of the string literal after the colon? -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: Popping key causes dict derived from object to revert to object
On 2024-03-25, Loris Bennett via Python-list wrote: > Grant Edwards writes: > >> On 2024-03-22, Loris Bennett via Python-list wrote: >> >>> Yes, I was mistakenly thinking that the popping the element would >>> leave me with the dict minus the popped key-value pair. >> >> It does. > > Indeed, but I was thinking in the context of > > dict_list = [d.pop('a') for d in dict_list] > > and incorrectly expecting to get a list of 'd' without key 'a', instead > of a list of the 'd['a]'. So when you say "leave me with", you mean "return the same dictionary with"? There's an important difference between what a function returns and what global/local state it "leaves you with". > Thanks for pointing out 'del'. My main problem, however, was > failing to realise that the list comprehension is populated by the > return value of the 'pop', not the popped dict. OK, so perhaps you weren't execting the original dict objects to be mutated, but rather that the pop method would return a new dict object without the "popped" element. The whole point of the 'pop method is to return the popped value, otherwise it wouldn't be needed. The 'del' statement would suffice. -- https://mail.python.org/mailman/listinfo/python-list
Re: Popping key causes dict derived from object to revert to object
On 2024-03-22, Loris Bennett via Python-list wrote: > Yes, I was mistakenly thinking that the popping the element would > leave me with the dict minus the popped key-value pair. It does. > Seem like there is no such function. Yes, there is. You can do that with either pop or del: >>> d = {'a':1, 'b':2, 'c':3} >>> d {'a': 1, 'b': 2, 'c': 3} >>> d.pop('b') 2 >>> d {'a': 1, 'c': 3} >>> d = {'a':1, 'b':2, 'c':3} >>> del d['b'] >>> d {'a': 1, 'c': 3} In both cases, you're left with the dict minus the key/value pair. In the first case, the deleted value printed by the REPL because it was returned by the expression "d.pop('b')" (a method call). In the second case is no value shown by the REPL because "del d['b']" is a statement not an expression. -- https://mail.python.org/mailman/listinfo/python-list
Re: the name ``wheel''
On 2024-03-21, MRAB via Python-list wrote: > As it's recommended to use the Python Launcher py on Windows, I use > that instead: > > py -m pip install something > > because it gives better support if you have multiple versions of > Python installed. I adopted that practice years ago on Linux as well after wasting what seemed like most of a day trying to figure out problems which turned out to be caused by the fact that "pip" and "python" invoked different versions of Python. -- https://mail.python.org/mailman/listinfo/python-list
Re: Configuring an object via a dictionary
On 2024-03-15, Thomas Passin via Python-list wrote: > On 3/15/2024 5:30 AM, Loris Bennett via Python-list wrote: >> Hi, >> >> I am initialising an object via the following: >> >> def __init__(self, config): >> >> self.connection = None >> >> self.source_name = config['source_name'] >> self.server_host = config['server_host'] >> self.server_port = config['server_port'] >> self.user_base = config['user_base'] >> self.user_identifier = config['user_identifier'] >> self.group_base = config['group_base'] >> self.group_identifier = config['group_identifier'] >> self.owner_base = config['owner_base'] >> >> However, some entries in the configuration might be missing. What is >> the best way of dealing with this? >> >> I could of course simply test each element of the dictionary before >> trying to use. I could also just write >> >> self.config = config >> >> but then addressing the elements will add more clutter to the code. >> >> However, with a view to asking forgiveness rather than >> permission, is there some simple way just to assign the dictionary >> elements which do in fact exist to self-variables? >> >> Or should I be doing this completely differently? > > self.source_name = config.get('source_name', default_value) > > Or, if you like this kind of expression better, > > self.source_name = config.get('source_name') or default_value Won't the latter version misbehave if the value of config['source_name'] has a "false" boolean value (e.g. "", 0, 0.0, None, [], (), {}, ...) >>> config = {} >>> config['source_name'] = "" >>> config.get('source_name') or 'default' 'default' -- https://mail.python.org/mailman/listinfo/python-list
Re: pathlib.Path.is_file vs os.path.isfile difference
On 2024-03-08, Thomas Passin via Python-list wrote: > >> Hi, I tested this with Python 3.8. Good to know that this was fixed! > > We just learned a few posts back that it might be specific to Linux; I > ran it on Windows. On Linux, the limit is imposed by the filesystem. Most of the "real" filesystems on Linux have a 255 character limit, a few support 256, and some of the legacy filesystems have lower limits. Reiser4 is the only one that's even remotely common which supports more than 256 -- according to https://en.wikipedia.org/wiki/Comparison_of_file_systems#Limits it supports filenames up to 3976 bytes long. NB: The behavior when the limit is exceeded might also vary from one filesystem to another. In any case, the pathlib docs for is_file() are explicit: any errors from the underlying OS and libraries will be propogated. There is nothing to fix. https://docs.python.org/3/library/pathlib.html#pathlib.Path.is_file Path.is_file() Return True if the path points to a regular file (or a symbolic link pointing to a regular file), False if it points to another kind of file. False is also returned if the path doesn’t exist or is a broken symlink; other errors (such as permission errors) are propagated. -- https://mail.python.org/mailman/listinfo/python-list
Re: pathlib.Path.is_file vs os.path.isfile difference
On 2024-03-08, Grant Edwards via Python-list wrote: >> OSError: [Errno 36] File name too long: >> '' > > On all of the Linux filesystems I know about, the max length for a > filename is 255 bytes, so the OSError is too surprising, and it does > seem to follow the documentation. Doh. I meant "is not too surprising". -- https://mail.python.org/mailman/listinfo/python-list
Re: pathlib.Path.is_file vs os.path.isfile difference
On 2024-03-08, Grant Edwards via Python-list wrote: > On 2024-03-08, Thomas Passin via Python-list wrote: >> On 3/8/2024 1:03 PM, Albert-Jan Roskam via Python-list wrote: >>> Hi, >>> I was replacing some os.path stuff with Pathlib and I discovered this: >>> Path(256 * "x").is_file() # OSError >>> os.path.isfile(256 * "x") # bool >>> Is this intended? Does pathlib try to resemble os.path as closely as >>> possible? >> >> You must have an very old version of Python. I'm running 3.12.2 and it >> returns False. > > It throws OSError with Python 3.11.8 on Linux. > OSError: [Errno 36] File name too long: > '' On all of the Linux filesystems I know about, the max length for a filename is 255 bytes, so the OSError is too surprising, and it does seem to follow the documentation. >>>> import os >>>> os.path.isfile(256 * "x") > False However, os.path.isfile() apprently masks that error somehow and returns False instead. I notice that the os.path.isfile() documentation does not specify what happens if the path is not a file or is illegal. It only specifies that True is returned if the path is a regular file. Presumably something other than "return True" is supposed to happen, but exactly what is not specified. -- https://mail.python.org/mailman/listinfo/python-list
Re: pathlib.Path.is_file vs os.path.isfile difference
On 2024-03-08, Thomas Passin via Python-list wrote: > On 3/8/2024 1:03 PM, Albert-Jan Roskam via Python-list wrote: >> Hi, >> I was replacing some os.path stuff with Pathlib and I discovered this: >> Path(256 * "x").is_file() # OSError >> os.path.isfile(256 * "x") # bool >> Is this intended? Does pathlib try to resemble os.path as closely as >> possible? > > You must have an very old version of Python. I'm running 3.12.2 and it > returns False. It throws OSError with Python 3.11.8 on Linux. $ python Python 3.11.8 (main, Feb 23 2024, 16:11:29) [GCC 13.2.1 20240113] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import pathlib >>> pathlib.Path(256 * "x").is_file() Traceback (most recent call last): File "", line 1, in File "/usr/lib/python3.11/pathlib.py", line 1267, in is_file return S_ISREG(self.stat().st_mode) ^^^ File "/usr/lib/python3.11/pathlib.py", line 1013, in stat return os.stat(self, follow_symlinks=follow_symlinks) ^^ OSError: [Errno 36] File name too long: '' >>> >>> import os >>> os.path.isfile(256 * "x") False -- https://mail.python.org/mailman/listinfo/python-list
Re: Variable scope inside and outside functions - global statement being overridden by assignation unless preceded by reference
On 2024-03-08, Chris Angelico via Python-list wrote: > On Sat, 9 Mar 2024 at 00:51, Grant Edwards via Python-list > wrote: > >> One might argue that "global" isn't a good choice for what to call the >> scope in question, since it's not global. It's limited to that source >> file. It doesn't make sense to me to call a binding "global", when >> there can be multile different "global" bindings of the same name. > > Most "globals" aren't global either, since you can have different > globals in different running applications. To me, "global" has always been limited to within a single process/address space, but that's probably just bias left over from C/Pascal/FORTRAN/assembly/etc. It never occurred to me that a global called "X" in one program on one computer would be the same as a global called "X" in a different program on a different computer somewhere else on the "globe". -- https://mail.python.org/mailman/listinfo/python-list
Re: Variable scope inside and outside functions - global statement being overridden by assignation unless preceded by reference
On 2024-03-07, Cameron Simpson via Python-list wrote: > Yes. Note that the "global" namespace is the module in which the > function is defined. One might argue that "global" isn't a good choice for what to call the scope in question, since it's not global. It's limited to that source file. It doesn't make sense to me to call a binding "global", when there can be multile different "global" bindings of the same name. -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: Variable scope inside and outside functions - global statement being overridden by assignation unless preceded by reference
On 2024-03-07, dn via Python-list wrote: > The idea of importing a module into the REPL and then (repeatedly) > manually entering the code to set-up and execute is unusual (surely type > such into a script (once), and run that (repeatedly). As you say, most > of us would be working from an IDE and hitting 'Run'. Am wondering why > you weren't - but it's not important. Unless the code is intended to be used as a module, 'import'ing it into the REPL doesn't make sense. A simple example: ---testit.py-- x = 'x' y = 'y' def foo(): global y print("hi") x = 'X' y = 'Y' print(x) print(y) -- The usual method to play with that interactively is $ python -i testit.py >>> x 'x' >>> y 'y' >>> foo() hi X Y >>> x 'x' >>> y 'Y' >>> As we've seen, doing a 'from testit.py import *' doesn't let you test what the OP was trying to test. Doing 'import testit.py' gets you closer, but it's a hassle to test code that way. The right thing to do is 'python -i ' (or the equivalent button/option in an IDE). https://docs.python.org/3/tutorial/interpreter.html If you intended to use testit.py as a module, and wanted to experiment with its behavior as a module, then go ahead and import it. But, don't do 'from testit.py import *' until 1. you know how that differs from 'import testit.py' and 2. you want to use that difference -- https://mail.python.org/mailman/listinfo/python-list
Re: Variable scope inside and outside functions - global statement being overridden by assignation unless preceded by reference
On 2024-03-06, Roel Schroeven via Python-list wrote: > Op 6/03/2024 om 17:40 schreef Jacob Kruger via Python-list: >> >>> from scoping2 import * > > [...] > > I would advice not to use 'import *', if at all possible, for multiple > reasons, one of which is to prevent problems like this. Unfortunately, many (most?) tutorials for particular modules (and even example code in the Python documentation itself) are all written assuming that you do "from import *". It saves the tutorial write a few keystrokes, but causes untold trouble for people who learn incorrectly that "from import *" is the proper way to do things. > I would also advice not to use global variables from other modules > directly, and in fact would advice to minimize the use of globals in > general as much as possible. If you need to keep state between > methods, it might be better to use a class. -- https://mail.python.org/mailman/listinfo/python-list
Re: Can u help me?
On 2024-03-06, MRAB via Python-list wrote: > On 2024-03-06 01:44, Ethan Furman via Python-list wrote: >> On 3/5/24 16:49, MRAB via Python-list wrote: >> > On 2024-03-06 00:24, Ethan Furman via Python-list wrote: >> >> On 3/5/24 16:06, Chano Fucks via Python-list wrote: >> >> >> >>> [image: image.png] >> >> >> >> The image is of MS-Windows with the python installation window of >> "Repair Successful". Hopefully somebody better at >> >> explaining that problem can take it from here... >> >> >> > If the repair was successful, what's the problem? >> >> I imagine the issue is trying get Python to run (as I recall, the python >> icon on the MS-Windows desktop is the >> installer, not Python itself). > > There was an issue 3 years ago about renaming the installer for clarity: > > https://github.com/python/cpython/issues/87322 Yea, this problem comes up constantly (and has for many years). People have suggested renaming the installer so it has "setup" or "install" in the name. People have suggested adding text to the installer splash screen to explain that it's the installer and not python itself, that you already have python installed, and if you want to _run_ python instead of _install_ python, here's how. People have suggested having the installer remove itself by default when it's done installing. People have suggested lots of solutions. AFAICT, nobody has actually done anything. -- https://mail.python.org/mailman/listinfo/python-list
Re: Variable scope inside and outside functions - global statement being overridden by assignation unless preceded by reference
On 2024-03-05, Cameron Simpson via Python-list wrote: > Because there are no variable definitions in Python, when you write > a function Python does a static analysis of it to decide which > variables are local and which are not. If there's an assignment to a > variable, it is a local variable. _Regardless_ of whether that > assignment has been executed, or gets executed at all (eg in an > if-statement branch which doesn't fire). Unfortunately, crap "information" sites like geeksforgeeks often describe this either incorrectly or so vaguely as to be worthless. >From the page https://www.geeksforgeeks.org/global-local-variables-python/ Python Global variables are those which are not defined inside any function and have a global scope whereas Python local variables are those which are defined inside a function and their scope is limited to that function only. Since "define" (in this context) isn't a term of art in Python, and it's never defined on the page in question, the quoted paragraph is not meaningful: it simply says that "global variables are global and local variables are local". That page goes on to say: In other words, we can say that local variables are accessible only inside the function in which it was initialized This is equally crap. It doesn't matter whether the variable is initialized or not. As Cameron correctly stated, if a function contains an assignment to a variable, and that variable is not declared global, then that variable is local. For example: def foo(): print(s) if 0: s = "there" print(s) In the function above s _is_not_ initialized in the function foo(). However, foo() does contain an assignment to s, therefore s is local unless declared global/nonlocal. [And the first print() will throw an exception even if there is a value bound to the global name 's'.] Unfortunately (presumably thanks to SEO) the enshittification of Google has reached the point where searching for info on things like Python name scope, the first page of links are to worthless sites like geeksforgeeks. -- https://mail.python.org/mailman/listinfo/python-list
Re: Problem resizing a window and button placement
On 2024-02-24, MRAB via Python-list wrote: > On 2024-02-24 01:14, Steve GS via Python-list wrote: > >> Python, Tkinter: How do I determine if a window has been resized? I >> want to locate buttons vertically along the right border and need >> to know the new width. The buttons are to move with the change of >> location of the right-side border. > > Bind an event handler for '': > > 8< > [...] > 8< > > Are you placing the buttons yourself? I always use layouts and they > handle such things automatically. Yes, definitely what he said: use a layout manager. I hope this doesn't sound rude, but if you're calculating button positions based on window size, you're doing it wrong and will end up wasting a lot of time to produce something that won't work right. Use a layout manager: https://tkinterpython.top/layout/#:~:text=Tkinter%20has%20three%20built%2Din,%2C%20grid%20%2C%20and%20place%20managers. https://www.pythonguis.com/tutorials/create-ui-with-tkinter-pack-layout-manager/ https://www.pythonguis.com/tutorials/use-tkinter-to-design-gui-layout/ You'll have to spend a little time learning how they work, but in the end you'll get done sooner and have better results. -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: Can one output something other than 'nan' for not a number values?
On 2024-02-19, Chris Green via Python-list wrote: > It's using f'{...}' at the moment. Here's a demonstration of how to hook custom code into the f-string formatting engine. It's brilliantly depraved. https://stackoverflow.com/questions/55876683/hook-into-the-builtin-python-f-string-format-machinery >From the above: You can, but only if you write evil code that probably should never end up in production software. So let's get started! I'm not going to integrate it into your library, but I will show you how to hook into the behavior of f-strings. This is roughly how it'll work: 1. Write a function that manipulates the bytecode instructions of code objects to replace FORMAT_VALUE instructions with calls to a hook function; 2. Customize the import mechanism to make sure that the bytecode of every module and package (except standard library modules and site-packages) is modified with that function. Final code is here: https://github.com/mivdnber/formathack -- https://mail.python.org/mailman/listinfo/python-list
Re: Testing (sorry)
On 2024-02-19, Thomas Passin wrote: >> About 24 hours later, all of my posts (and the confirmation e-mails) >> all showed up in a burst at the same time on two different unrelated >> e-mail accounts. >> >> I still have no clue what was going on... > > Sometimes a post of mine will not show up for hours or even half a day. > They are all addressed directly to the list. Sometimes my email > provider sends me a notice that the message bounced. Those notices say > that the address wasn't available when the transmission was tried. I guess that in future I'll wait a couple days before I assume something is broken. -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: Testing (sorry)
On 2024-02-18, Peter J. Holzer via Python-list wrote: > [Replying to the list *and* Grant] > > On 2024-02-17 19:38:04 -0500, Grant Edwards via Python-list wrote: >> Today I noticed that nothing I've posted to python-list in past 3 >> weeks has shown up on the list. > > January 29th, AFAICS. And end of december before that. > >> I don't know how to troubleshoot this other than sending test >> messages. Obviously, if this shows up on the list, then I've gotten >> it to work... > > This did show up and 3 other test messages with very similar text > as well. > > Also there was a whole flurry of almost but not quite identical messages > from you in the "nan" thread. Sorry about that. All of those were posted at various times throughout the day yesterday using two different accounts, two different mail servers, and three different methods for submitting the e-mails. I finally gave up and switched to using comp.lang.python via Usenet. Then, about 24 hours later, all those messages finally showed up. At one point about half way through that process yesterday, I unsusbscribed and then re-subscribed both e-mail addresses. I got confirmation and welcome messages on both accounts. Sending "help" requests to the list server produced the expected results. I enabled the sending of confirmation messages from the list server. But posts to the list still seemed to vanish into the ether while emails from both accounts reached other destinations without delay, During this process a number of posts from other users did appear in the list archive and at at _one_ of the two e-mail addresses which I had subscribed. But no sign of any of my posts. About 24 hours later, all of my posts (and the confirmation e-mails) all showed up in a burst at the same time on two different unrelated e-mail accounts. I still have no clue what was going on... -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Testing (sorry)
Today I noticed that nothing I've posted to python-list in the past 3 weeks has shown up on the list. I don't know how to troubleshoot this other than by sending test messages. Obviously, if this shows up on the list, then I'm making progress... [message 3] -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Testing (sorry)
Today I noticed that nothing I've posted to python-list in past 3 weeks has shown up on the list. I don't know how to troubleshoot this other than sending test messages. Obviously, if this shows up on the list, then I'm making progress. [message 4] -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Testing - 2 (sorry)
Today I noticed that nothing I've posted to python-list in past 3 weeks has shown up on the list. I don't know how to troubleshoot this other than sending test messages. Obviously, if this shows up on the list, then I've gotten it to work... -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Testing (sorry)
Today I noticed that nothing I've posted to python-list in past 3 weeks has shown up on the list. I don't know how to troubleshoot this other than sending test messages. Obviously, if this shows up on the list, then I've gotten it to work... -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: Can one output something other than 'nan' for not a number values?
On 2024-02-16, Chris Green wrote: > I'm looking for a simple way to make NaN values output as something > like '-' or even just a space instead of the string 'nan'. I tried monkey-patching the __format__ method of float, but it's immutable, so that didnt' work. Is float.__format__ what's used by f-strings, the % operator, etc.? -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Can one output something other than 'nan' for not a number values?
[I've been trying all afternoon to post via slrn, but nothing is showing up on the list. Forgive me if multiple posts eventually show up.] On 2024-02-17, Cameron Simpson via Python-list wrote: > On 16Feb2024 22:12, Chris Green wrote: >>I'm looking for a simple way to make NaN values output as something >>like '-' or even just a space instead of the string 'nan'. [...] >> >>Battery Voltages and Currents >>Leisure Battery - 12.42 volts -0.52 Amps >>Starter Battery - 12.34 volts -0.01 Amps > The simplest thing is probably just a function writing it how you > want it: > > def float_s(f): > if isnan(f): > return "-" > return str(f) Since he's obviously using one of the float formatting mechanisms to control the number of columsn and decimal places, I doubt str(f) will meet the need. I tried monkey-patching the float type's __format__ method, but it's immutable. Is float.__format__() what's used by f-strings, the '%' operator, etc.? -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Can one output something other than 'nan' for not a number values?
[Posts via slrn and my GMail account aren't showing up, so I guess I'll try subscribing from a different e-mail address.] On 2024-02-17, Cameron Simpson via Python-list wrote: On 16Feb2024 22:12, Chris Green wrote: I'm looking for a simple way to make NaN values output as something like '-' or even just a space instead of the string 'nan'. [...] Battery Voltages and Currents Leisure Battery - 12.42 volts -0.52 Amps Starter Battery - 12.34 volts -0.01 Amps The simplest thing is probably just a function writing it how you want it: def float_s(f): if isnan(f): return "-" return str(f) Since he's obviously using one of the float formatting mechanisms to control the number of columsn and decimal places, I doubt str(f) will meet the need. I tried monkey-patching the float type's __format__ method, but it's immutable. Is float.__format__() what's used by f-strings, the '%' operator, etc.? -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: Can one output something other than 'nan' for not a number values?
On 2024-02-17, Cameron Simpson via Python-list wrote: > On 16Feb2024 22:12, Chris Green wrote: >>I'm looking for a simple way to make NaN values output as something >>like '-' or even just a space instead of the string 'nan'. [...] >> >>Battery Voltages and Currents >>Leisure Battery - 12.42 volts -0.52 Amps >>Starter Battery - 12.34 volts -0.01 Amps > The simplest thing is probably just a function writing it how you > want it: > > def float_s(f): > if isnan(f): > return "-" > return str(f) Since he's obviously using one of the float formatting mechanisms to control the number of columsn and decimal places, I doubt str(f) will meet the need. I tried monkey-patching the float type's __format__ method, but it's immutable. Is float.__format__() what's used by f-strings, the '%' operator, etc.? -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: Can one output something other than 'nan' for not a number values?
On 2024-02-17, Cameron Simpson via Python-list wrote: > On 16Feb2024 22:12, Chris Green wrote: >>I'm looking for a simple way to make NaN values output as something >>like '-' or even just a space instead of the string 'nan'. [...] >> >>Battery Voltages and Currents >>Leisure Battery - 12.42 volts -0.52 Amps >>Starter Battery - 12.34 volts -0.01 Amps > The simplest thing is probably just a function writing it how you > want it: > > def float_s(f): > if isnan(f): > return "-" > return str(f) Since he's obviously using one of the float formatting mechanisms to control the number of columsn and decimal places, I doubt str(f) will meet the need. I tried monkey-patching the float type's __format__ method, but it's immutable. Is float.__format__() what's used by f-strings, the '%' operator, etc.? -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: Can one output something other than 'nan' for not a number values?
On 2024-02-17, Cameron Simpson via Python-list wrote: > On 16Feb2024 22:12, Chris Green wrote: >>I'm looking for a simple way to make NaN values output as something >>like '-' or even just a space instead of the string 'nan'. [...] >> >>Battery Voltages and Currents >>Leisure Battery - 12.42 volts -0.52 Amps >>Starter Battery - nan voltsnan Amps >> >>What I would like is for those 'nan' strings to be just a '-' or >>something similar. > > The simplest thing is probably just a function writing it how you want > it: > > def float_s(f): > if isnan(f): > return "-" > return str(f) He's obviouisly using a formatting feature to control columns and decimal places, so I doubt that 'str(f)' is going to meet the need. I tried monkey-patching the __format__ method of the 'float' type, but it's immutable -- so that didn't work. Is float.__format__() what's used by f-strings, the % operator, etc.? -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: Can one output something other than 'nan' for not a number values?
On 2024-02-17, Cameron Simpson via Python-list wrote: > On 16Feb2024 22:12, Chris Green wrote: >>I'm looking for a simple way to make NaN values output as something >>like '-' or even just a space instead of the string 'nan'. >>[...] >> >>Battery Voltages and Currents >>Leisure Battery - 12.42 volts -0.52 Amps >>Starter Battery - nan voltsnan Amps >> >>What I would like is for those 'nan' strings to be just a '-' or >>something similar. > The simplest thing is probably just a function writing it how you want > it: > > def float_s(f): > if isnan(f): > return "-" > return str(f) > > and then use eg: > > print(f'value is {float_s(value)}') > > or whatever fits your code. Except he's obviously using some sort of formatting to control the number of columns and decimal places, so 'str(f)' is not going to cut it. Is the basic floating point number formatting functionality seen when using f-strings or '%' operator part of the float type or is it part of the f-string and % operator? -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: Can one output something other than 'nan' for not a number values?
On 2024-02-16, Chris Green via Python-list wrote: > I'm looking for a simple way to make NaN values output as something > like '-' or even just a space instead of the string 'nan'. It would probably help if you told us how you're "outputting" them now (the Python feaatures/functions used, not the actual output format). Are you using f-strings, the % operator, str.format(), or ?? I would be tempted to try monkey-patching the float class to override the __format__ method. I have no idea what side effects that might have, or if it's even used by the various formatting mechanisms, so you might end up scraping bits off the walls... -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: Extract lines from file, add to new files
On 2024-01-29, Rich Shepard via Python-list wrote: > On Mon, 29 Jan 2024, Rich Shepard via Python-list wrote: > >> No, I hadn't ... but I am reading it now. > > Perhaps I missed the answer to my question when reading the io module. It > explains how to open/write/read files of text and binary data, not passing > a variable's value from one file to a place-keeper in another file. It's not at all clear (to me) what you're asking about. When you talk about "files" are you referring to data files? Python modules within a single program? Seperate Python programs? Something else? The phrase "place-keeper in another file" sounds a bit like you're trying to do templating. There are many, many ways to do templating in Python -- ranging from literal 'f-strings' to powerful templating engines that are used to construct entire web sites: https://www.google.com/search?q=python+templating https://docs.python.org/3/tutorial/inputoutput.html#tut-f-strings https://en.wikipedia.org/wiki/Jinja_(template_engine) -- https://mail.python.org/mailman/listinfo/python-list
Re: How/where to store calibration values - written by program A, read by program B
On 2023-12-28, Peter J. Holzer via Python-list wrote: > On 2023-12-28 05:20:07 +, rbowman via Python-list wrote: >> On Wed, 27 Dec 2023 03:53:42 -0600, Greg Walters wrote: >> > The biggest caveat is that the shared variable MUST exist before it can >> > be examined or used (not surprising). >> >> There are a few other questions. Let's say config.py contains a variable >> like 'font' that is a user set preference or a calibration value >> calculated by A to keep with the thread title. Assuming both scripts are >> running, how does the change get propagated to B after it is set in A > > It isn't. The variable is set purely in memory. This is a mechanism to > share a value between multiple modules used by the same process, not to > share between multiple processes (whether they run the same or different > scripts) > >> and written to the shared file? > > Nothing is ever written to a file. Then how does it help the OP to propogate clibration values from one program to another or from one program run to the next run? > You could of course write python files from a python script (in fact I > do this), but that's not what this pattern is about, AFAICS. -- https://mail.python.org/mailman/listinfo/python-list
Re: How to enter multiple, similar, dictionaries?
On 2023-12-11, Chris Green via Python-list wrote: > Is there a way to abbreviate the following code somehow? > > lv = {'dev':'bbb', 'input':'1', 'name':'Leisure volts'} > sv = {'dev':'bbb', 'input':'0', 'name':'Starter volts'} > la = {'dev':'bbb', 'input':'2', 'name':'Leisure Amps'} > sa = {'dev':'bbb', 'input':'3', 'name':'Starter Amps'} > bv = {'dev':'adc2', 'input':0, 'name':'BowProp Volts'} > > It's effectively a 'table' with columns named 'dev', 'input' and > 'name' and I want to access the values of the table using the variable > name. Named tuples stored in a dictionary or list? > I could, obviously, store the data in a database (sqlite), I have some > similar data in a database already but the above sort of format in > Python source is more human readable and accessible. I'm just looking > for a less laborious way of entering it really. -- https://mail.python.org/mailman/listinfo/python-list
Re: Context without manager
On 2023-11-27, Grant Edwards via Python-list wrote: > On 2023-11-26, Dieter Maurer via Python-list wrote: > >> If you do not have this case (e.g. usually if you open the file >> in a class's `__init__`), you do not use a context manager. > > He knows that. The OP wrote that he wants to use that can > _only_ be used by a context manager, but he wants that usage to be > spread over various methods of a class he's writing. So he's asking > how to fool that into working when he's not using a > context manager. I should probably have written "how to fool that into working when he's not using a 'with' statement" -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: Context without manager
On 2023-11-26, Dieter Maurer via Python-list wrote: > If you do not have this case (e.g. usually if you open the file > in a class's `__init__`), you do not use a context manager. He knows that. The OP wrote that he wants to use that can _only_ be used by a context manager, but he wants that usage to be spread over various methods of a class he's writing. So he's asking how to fool that into working when he's not using a context manager. -- Grnat -- https://mail.python.org/mailman/listinfo/python-list
Re: xor operator
On 2023-11-14, Dom Grigonis via Python-list wrote: > >> Except the 'any' and 'all' builtins are _exactly_ the same as bitwise >> or and and applided to many bits. To do something "in line" with that >> using the 'xor' operator would return True for an odd number of True >> values and False for an even Number of True values. > > Fair point. > > Have you ever encountered the need for xor for many bits (the one > that I am NOT referring to)? Would be interested in what sort of > case it could be useful. Yes, it's used all the time in low-level communications protocols, where it's often implemented in hardware. But, it is also not at all unusual to implement it in software. It's also not that unusual for the "count-ones" part of the function you're asking for to be implemented in hardware by a CPU having an instruction that counts the number of 1 bits in a register. GCC has a low-level builtins called __builtin_popcount() and __builtin-popcountl() that counts the number of 1's in an unsigned (long) int. -- https://mail.python.org/mailman/listinfo/python-list
Re: xor operator
On 2023-11-13, Dom Grigonis via Python-list wrote: > I am not asking. Just inquiring if the function that I described > could be useful for more people. > > Which is: a function with API that of `all` and `any` and returns > `True` if specified number of elements is True. I've got no objection to a function that counts True objects returned by an iterator and returns True IFF count == . I've got no objection to a function that counts True objects returned by an iterator and returns True IFF count >= . I've got no objection if that latter function short-circuits by stopping the iteration and returning True when it has seen true objects. I don't recall ever having a need for such a function in the 25 years I've been writing Python code, but I'm not going to claim that nobody else has a need for such a function. I would object to that being called 'xor', and would fight to the death (yes, I'm being hyperbolic) the addition of a builtin with the name 'xor' that does what you describe. > It is not a generalised `xor` in strict programatic space. AFAICT, it's not nothing at all to do with 'xor' in any sense. > I.e. NOT bitwise xor applied to many bits. This is more in line > with cases that `any` and `all` builtins are used. Except the 'any' and 'all' builtins are _exactly_ the same as bitwise or and and applided to many bits. To do something "in line" with that using the 'xor' operator would return True for an odd number of True values and False for an even Number of True values. -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: xor operator
On 2023-11-13, Dom Grigonis via Python-list wrote: > Hi All, > > I think it could be useful to have `xor` builtin, which has API similar to > the one of `any` and `all`. > > * Also, it could have optional second argument `n=1`, which > * indicates how many positives indicates `True` return. For > * complete flexibility 3rd argument could indicate if `the number` > * is equal, greater, less, ... than `n` I would expect "xor" to return true if there are an odd number of trues, and false if there are an even number of trues. It's not clear to me what you're asking for. -- https://mail.python.org/mailman/listinfo/python-list
Re: Checking if email is valid
On 2023-11-06, Greg Ewing via Python-list wrote: > On 7/11/23 7:45 am, Mats Wichmann wrote: >> Continuing with the example, if you have a single phone number field, or >> let a mobile number be entered in a field marked for landline, you will >> probably assume you can text to that number. > > But if the site can detect that you've entered a mobile number into > the landline field or vice versa and reject it, then it can figure out > whether it can text to a given numner or not without you having > to tell it! Maybe. I'm pretty sure the last time I was in Australia, you could send/recieve text messages from landalines. And I've had mobile number that didn't support text messaging. If you, as a web developer, want the user to enter a text-message capable phone number, then ASK FOR THAT! -- https://mail.python.org/mailman/listinfo/python-list
Re: Checking if email is valid
On 2023-11-05, D'Arcy Cain via Python-list wrote: > On 2023-11-05 00:39, Grant Edwards via Python-list wrote: >> Definitely. Syntactic e-mail address "validation" is one of the most >> useless and widely broken things on the Interwebs. People who do >> anything other than require an '@' (and optionally make you enter the >> same @-containing string twice) are deluding themselves. > > And don't get me started on phone number validation. I can see how the truley dim-witted might forget that other countries have phone numbers with differing lengths and formatting/punctuation, but there are tons of sites where it takes multiple tries when entering even a bog-standard USA 10-0digit phone nubmer because they are completely flummuxed by an area code in parens or hyphens in the usual places (or lack of hyhpens in the usual places). This stuff isn't that hard, people... > The most annoying thing to me, though, is sites that reject names > that have an apostrophe in them. I hate being told that my name, > that I have been using for over seventy years, is invalid. > > OK, now that I am started, what else? Oh yah. Look at your credit > card. The number has spaces in it. Why do I have to remove them. If > you don't like them then you are a computer, just remove them. Indeed. There is a tiny but brightly burning kernel of hate in my heart for web sites (and their developers) that refuse to accept credit card numbers entered with spaces _as_they_are_shown_on_the_card_! I've concluded that using PHP causes debilitating and irreversible brain damage. > When do we stop working for computers and have the computers start > working for us? -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: Checking if email is valid
On 2023-11-04, Michael Torrie via Python-list wrote: > On 11/4/23 02:51, Simon Connah via Python-list wrote: > >> Wow. I'm half tempted to make a weird email address to see how many >> websites get it wrong. In my experience, they don't have to be very weird at all. >> Thank you for the link. > > Nearly all websites seem to reject simple correct email addresses > such as myemail+sometext@example.domain. I like to use this kind of > email address when I can to help me filter out the inevitable spam > that comes from companies selling off my address even after claiming > they won't. I've always suspected that's intentional. They refuse those sorts of e-mail addresses because they know that's what they are used for. If they allowed "plus suffixed" e-mail addresses, then all the crap they want to send to you would go into /dev/null where it belongs -- and we can't have that! > So I suspect that nearly all websites are going to reject other > kinds of weird email addresses you can create that are actually > correct. Definitely. Syntactic e-mail address "validation" is one of the most useless and widely broken things on the Interwebs. People who do anything other than require an '@' (and optionally make you enter the same @-containing string twice) are deluding themselves. -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: Checking if email is valid
On 2023-11-02, Michael Torrie via Python-list wrote: > On 11/2/23 00:42, Simon Connah via Python-list wrote: > >> Valid as in conforms to the standard. Although having looked at the >> standard that might be more difficult than originally planned. > > You'll have to read the relevant RFCs. Lots of corner cases! From what > I can see virtually no one on the internet gets it right, judging by the > number of times I have valid email addresses flagged as not valid by > poor algorithms. I've wondered if there are addresses that violate the RFC (and would therefore be "correctly" rejected), but but in practice will work just fine. I've never spent enough time looking at the RFC to even propose test cases for that... -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: Checking if email is valid
On 2023-11-01, Chris Angelico via Python-list wrote: > On Thu, 2 Nov 2023 at 08:09, Grant Edwards via Python-list > wrote: >> Make sure it has an '@' in it. Possibly require at least one '.' >> after the '@'. > > No guarantee that there'll be a dot after the at. Ah, I forgot about defaulting to a local domain if one is omitted. Will MTAs do that these days? > (Technically there's no guarantee of an at sign either, but email > addresses without at signs are local-only, so in many contexts, you > can assume there needs to be an at.) > > So the regex to match all valid email addresses that aren't > local-only is... drumroll please... > > r"@" Unless you want to support UUCP or X400 addresses... :) -- https://mail.python.org/mailman/listinfo/python-list
Re: Checking if email is valid
On 2023-11-01, Simon Connah via Python-list wrote: > I'm building a simple project using smtplib and have a > question. I've been doing unit testing but I'm not sure how to check > if an email message is valid. Send an e-mail using it? If the right person gets the e-mail, then it's valid? > Using regex sounds like a bad idea to me and the other options I > found required paying for third party services. > > Could someone push me in the right direction please? I just want to > find out if a string is a valid email address. You'll have to define "valid". Valid syntactically according to ? Will be accepted by an SMTP server somewhere? Corresponds to a real person? Make sure it has an '@' in it. Possibly require at least one '.' after the '@'. Trying to do anything more than that is just wasting your time and annoying the mule. -- https://mail.python.org/mailman/listinfo/python-list
Re: Question(s)
On 2023-10-25, o1bigtenor via Python-list wrote: > Haven't heard of a python IDE - - - doesn't mean that there isn't such - - > just that I haven't heard of such. Is there a python IDE? Seriously? Now you're just trolling. google.com/search?q=python+ide=python+ide -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: Question(s)
On 2023-10-24, o1bigtenor via Python-list wrote: > So how does one test software then? That's what customers are for! [Actually, that's true more often than it should be.] -- https://mail.python.org/mailman/listinfo/python-list
Re: Question(s)
On 2023-10-24, Thomas Passin via Python-list wrote: > Something less ambitious than a full proof of correctness of an > arbitrary program can sometimes be achieved. The programming team > for the Apollo moon mission developed a system which, if you would > write your requirements in a certain way, could generate correct C > code for them. Er, what? C didnt' exist until after the Apollo program was done. FORTRAN, perhaps? -- https://mail.python.org/mailman/listinfo/python-list
Re: Question(s)
On 2023-10-24, Dan Purgert via Python-list wrote: > On 2023-10-24, o1bigtenor wrote: >> Greetings >> >> (Sorry for a nebulous subject but dunno how to have a short title for >> a complex question.) >> [...] >> Is there a way to verify that a program is going to do what it is >> supposed to do even before all the hardware has been assembled and >> installed and tested? > > In short, no. > > Reality is a mess, and even if you've programmed/perfectly/ to the > datasheets (and passed our unit-tests that are also based on those > datasheets), a piece of hardware may not actually conform to what's > written. Maybe the sheet is wrong, maybe the hardware is faulty, etc. And the specified customer requirements are usually wrong too. Sure, the customer said it is supposed to do X, but what they actually needed was Y. And the protocol spec isn't quite right either. Sure, it says "when A is received reply with B", but what everybody really does is slighty different, and you need to do what everybody else does, or the widget you're talking to won't cooperate. And floating point doesn't really work the way you think it does. Sometimes it does, close-enough, for the test-cases you happened to choose... -- https://mail.python.org/mailman/listinfo/python-list
Re: Question(s)
On 2023-10-24, o1bigtenor via Python-list wrote: > Is there a way to verify that a program is going to do what it is > supposed to do even before all the hardware has been assembled and > installed and tested? It depends on what you mean by "verify ...". If you want to prove a program correct (in the mathematical sense), then the practical answer is no. It's possible to prove _some_ programs correct, but they tend to be uselessly trivial. For real programs, the best you can do is choose a good set of test cases and test them. If you can simulate the various inputs and collect the outputs, then you can do testing before you have real target hardware. -- https://mail.python.org/mailman/listinfo/python-list
Re: isinstance()
On 2023-08-04, Chris Angelico via Python-list wrote: > On Sat, 5 Aug 2023 at 09:36, dn via Python-list > wrote: > >> Faced with a situation where an argument may be a scalar-value or an >> iterable, I'll presume the latter, eg throw it straight into a for-loop. >> If that fails (because the argument is a scalar), use try-except to >> re-route the logic. > > That's great as long as you aren't expecting to handle strings. If you do that, you're obviously not expecting to handle strings. The problem happens when you're not expecting to handle strings, and you get passed one anyway. It's like the Spanish Inquisition... > The string "spam" is sometimes equivalent to the list ["s", "p", > "a", "m"] and sometimes not. And b"ABCD" is sometimes equivalent to the list [65,66,67,68] and sometimes not. Been there, fell in that hole. More than a few times. :/ Famous Last Words: "I wasn't expecting to handle strings -- but I should have been..." -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: What is this TEST BANK stuff ?
On 2023-06-21, Chris Angelico via Python-list wrote: > On Thu, 22 Jun 2023 at 02:54, Dan Kolis via Python-list > wrote: >> >> Why do we tolerate this spam ? >> >> this seems most likely a way to inject viruses into people's workflow. >> >> That wiped out usenet. Ahh without an explaination; ( and it woudl have to >> be a good one ); what is the purpsoe of this, why is it here ? >> >> Can it be eliminated ? >> > > Yes, follow the mailing list instead of the newsgroup. Most spam > doesn't reach us over here at the list. > > Sign up here: https://mail.python.org/mailman/listinfo/python-list If you want to stick with NNTP as your access protocol, you can follow the list on gmane: nntp://news.gmane.io/gmane.comp.python.general However, the list recently stopped accepting posts via gmane, so you'll need to configure your nntp client to e-mail posts to that group. -- https://mail.python.org/mailman/listinfo/python-list
Re: Resolution of paths in tracebacks
On 2023-05-31, Vishal Chandratreya wrote: > When an exception occurs, the full path to the file from which it > originates is displayed, but redundant elements are not removed. For > instance: > $ ./python ./foo > Traceback (most recent call last): > File "/home/User/cpython/./foo", line 4, in > a() > File "/home/User/cpython/./foo", line 3, in a > def a(): raise ValueError > ValueError > This happens because the function _Py_abspath (in Python/fileutils.c) > appends relative_path_to_file to absolute_path_to_current_working_directory. > Not sure if this should be treated as a bug, because the definition of > 'absolute path' is not clear. Does it mean a path starting from the root > directory, or a path without redundant elements? The former: https://www.linuxfoundation.org/blog/blog/classic-sysadmin-absolute-path-vs-relative-path-in-linux-unix -- https://mail.python.org/mailman/listinfo/python-list
Re: Tkinter docs?
On 2023-05-26, Rob Cliffe via Python-list wrote: > Grant, I may well buy one of the books you suggested. I haven't had look at either of the newer books, but I got a lot of good out of the Grayson book (20 years ago). I also had a Tcl/Tk book that I found useful even when usng tkinter, but it's even older than the Grayson one... -- https://mail.python.org/mailman/listinfo/python-list
Re: Invalid literal for int() with base 10?
On 2023-05-26, Grant Edwards wrote: > On 2023-05-25, Kevin M. Wilson via Python-list wrote: > >> Ok, I'm not finding any info. on the int() for converting a str to >> an int (that specifies a base parameter)?! > > Where are you looking? > > https://docs.python.org/3/library/functions.html#int And don't forget about the help() function: $ python Python 3.11.3 (main, May 8 2023, 09:00:58) [GCC 12.2.1 20230428] on linux Type "help", "copyright", "credits" or "license" for more information. >>> >>> help(int) Help on class int in module builtins: class int(object) | int([x]) -> integer | int(x, base=10) -> integer | | Convert a number or string to an integer, or return 0 if no arguments | are given. If x is a number, return x.__int__(). For floating point | numbers, this truncates towards zero. | | If x is not a number or if base is given, then x must be a string, | bytes, or bytearray instance representing an integer literal in the | given base. The literal can be preceded by '+' or '-' and be surrounded | by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. | Base 0 means to interpret the base from the string as an integer literal. | >>> int('0b100', base=0) | 4 | | Built-in subclasses: | bool | | Methods defined here: | | __abs__(self, /) | abs(self) | | __add__(self, value, /) | Return self+value. | [...] -- https://mail.python.org/mailman/listinfo/python-list
Re: Invalid literal for int() with base 10?
On 2023-05-25, Kevin M. Wilson via Python-list wrote: > Ok, I'm not finding any info. on the int() for converting a str to > an int (that specifies a base parameter)?! Where are you looking? https://docs.python.org/3/library/functions.html#int > The picture is of the code I've written... And the base 10 paradigm > involved?? I've no clue what that sentence means. > years = int('y') # store for calculationValueError: > invalid literal for int() with base 10: 'y'What is meant by "invalid > literal"? It means that the string 'y' isn't an integer literal. The strings '123' and '-4' are integer literals. https://docs.python.org/3/reference/expressions.html?highlight=integer%20literal#literals > I'm trying to convert srt to int, and I didn't know I needed to > specify the base. You don't need to unless you want a base other than 10. > Plus I haven't read anything that I need to specify the base for the int(). Don't know what you mean there. > Attached is the code, showing the code and the execution of said > code. Sorry, I don't see attachments. Include code in posts. > "When you pass through the waters, I will be with you: and > when you pass through the rivers, they will not sweep > over you. When you walk through the fire, you will not be burned: > the flames will not set you ablaze." Isaiah 43:2 Huh? -- https://mail.python.org/mailman/listinfo/python-list
Re: Tkinter docs?
On 2023-05-24, Rob Cliffe via Python-list wrote: > I have recently started converting a large project to tkinter, starting > with zero knowledge of tkinter. (You are free to think: BAD IDEA. ) Well, you could be translating them to Tcl/Tk -- so on the scale of bad ideas, your's barely registers. > I am well aware that adopting a new tool always involves a learning > curve, and that one is prone to think that things are more difficult > than they are/should be, and to belly-ache about it, and that in a year > from now I'll probably wonder what I'm fussing about. > Nonetheless ISTM that there is a particular problem with tkinter: > > There doesn't seem to be any decent documentation for it anywhere. Back in the day, the Grayson book was the definitive reference: https://www.amazon.com/Python-Tkinter-Programming-John-Grayson/dp/1884777813/ It's 20+ years old now, so the version of Python it uses is pretty ancient, and I presume Tk has also changed a bit over the years, so... There are a couple recent books, but I haven't looked at them: https://www.amazon.com/Modern-Tkinter-Busy-Python-Developers-dp-1999149564/dp/1999149564/ https://www.amazon.com/Python-GUI-Programming-Tkinter-user-friendly/dp/1801815925/ -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: What to use instead of nntplib?
On 2023-05-22, Keith Thompson wrote: > My understanding is that nntplib isn't being erased from reality, > it's merely being removed from the set of modules that are provided > by default. > > I presume that once it's removed from the core, it will still be > possible to install it via pip or some other mechanism. If somebody rescues the code and puts it in Pypi (assuming the copyright owner allows that). IIRC, somebody is trying to do that, but there some contention because Pypi won't allow the use of the name "nntplib" for the package because it conflicts with a library builtin. > > import warnings > warnings.filterwarnings("ignore", category=DeprecationWarning) > import nntplib Yep, thanks. That at least prevents the warning from messing up my slrn screen. :) > If my understanding is correct, why is this such a big problem? It's not a "big" problem, but something that "just worked" with any Python installation now requires that the user install an extra package. If they don't already have pip, then they have to install that first. And then they have to do it again, because the first time they installed pip for the wrong version of python. [I don't really get how that happens, but there seem to be a constant stream of postings from people with that problem.] -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: What to use instead of nntplib?
On 2023-05-21, Retrograde wrote: > Who ever came up with "Removing dead batteries" as a slogan, when > some of those batteries still work perfectly well, needs to rethink > it. Go ahead and remove code that no longer works, OK. But removing > unpopular modules? That undercuts the entire philosophy of the > platform, in my opinion. And one of the metrics of "popularity" seems to be "activity" (e.g. changes committed). For things that have been around for 20+ years and have all the features they need and all of the bugs fixed (and are now very stable) that lack of "activity" is interpreted as "unpopular" regardless of how many people are using the module. -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: Tkinter (related)~
On 2023-05-19, Cameron Simpson wrote: > On 18May2023 12:06, Jack Dangler wrote: >>I thought the OP of the tkinter thread currently running may have >>needed to install the tkinter package (since I had the same missing >>component error message), so I tried to install the package on to my >>Ubu laptop - >> >>pip install tkinter >>Defaulting to user installation because normal site-packages is not >>writeable >>ERROR: Could not find a version that satisfies the requirement tkinter >>(from versions: none) >>ERROR: No matching distribution found for tkinter >> >>Is there an alternate path to installing this? > > Usually tkinter ships with Python because it is part of the stdlib. > > On some platforms eg Ubuntu Linux the stdlib doesn't come in completely > unless you ask - a lot of stdlib packages are apt things you need to ask > for. On my Ubunut here tkinter comes from python3-tk. So: > > $ sudo apt-get install python3-tk And in general, on Linux systems, you'll be better off in the long run if you use the distro's package manager to install Python packages instead of using pip. If there is no distro package, you're usually also better off using 'pip install --user' so that pip isn't messing about with directories that are normally managed by the distro's package manager. When I do have to resort to using pip in install something, I always do a --dry-run first and make a note of any dependancies that pip is going to try to install -- so I can install those using the package manager if possible. -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: Learning tkinter
On 2023-05-12, Rob Cliffe via Python-list wrote: > > Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:20:19) [MSC v.1925 32 > bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> import tkinter > >>> tkinter.messagebox > Traceback (most recent call last): > File "", line 1, in > AttributeError: module 'tkinter' has no attribute 'messagebox' > >>> $ python Python 3.11.3 (main, May 8 2023, 09:00:54) [GCC 12.2.1 20230428] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import tkinter >>> from tkinter import messagebox >>> messagebox >>> > Why is this? Dunno. -- https://mail.python.org/mailman/listinfo/python-list
Re: What to use instead of nntplib?
On 2023-05-16, Chris Green wrote: > Grizzy Adams wrote: >> Tuesday, May 16, 2023 at 9:26, Alan Gauld wrote: >> Re: What to use instead of nntplib? (at least in part) >> >> >On 15/05/2023 22:11, Grant Edwards wrote: >> >> I got a nice warning today from the inews utility I use daily: >> >> >> >> DeprecationWarning: 'nntplib' is deprecated and slated for removal in >> >> Python 3.13 >> >> >> >> What should I use in place of nntplib? >> >> >I'm curious as to why nntplib is deprecated? Surely there are still a >> >lot of nntp servers around >> >> there must be this list is mirrored on one, and AFAICS some pythoners use >> that >> way to post (over the list) > > Yes, me for one, a good newsreader is really a wonderful way to manage > technical 'lists' like this one. IMO, there's nothing better. Newsreaders were designed from the beginning to deal with the sort of traffic and usage patterns seen in mailing lists. Using an MUA (even combined with something like procmail) and folders/labels is just a pale imitation of a good newsreader. > Usenet news is still very much alive though a minority interest now > I suspect. This list's decision to stop accepting postings via news.gmane.io is what prompted me to write my own "inews" application in Python that uses SMTP for some groups and NNTP for others when I "post" via slrn. I probably use NNTP more to access mailing lists via gmane than I use it for accessing the "real" Usenet groups. NNTP is not just for Usenet... -- https://mail.python.org/mailman/listinfo/python-list
Re: What to use instead of nntplib?
On 2023-05-16, Alan Gauld wrote: > On 16/05/2023 10:06, Cameron Simpson wrote: > >>> I'm curious as to why nntplib is deprecated? Surely there are still a >>> lot of nntp servers around, both inside and outside corporate firewalls? Anything not used to develop AI is going to be depricated. An AI told me, so it must be true. >>> Is there a problem with the module or is it just perceived as no longer >>> required? Two issues were cited: 1. It's too stable, bug-free, and feature-complete. IOW "no activity". Apparently, people equate "activity" with "usage". 2. A problem with automated testing, since there's no server side support. Though testing a module's client implementation by having it talk to a module's server implementation seems like a singularly bad idea. >> See PEP 594: https://peps.python.org/pep-0594/ > > Thanks Cameron. > A scary list; I must have a dozen projects from the late 90s still > live that are using many of these! I'm glad I'm retired and won't > be the one who has to fix 'em :-) It has been pointed out to me that Perl still has a supported NNTP library. That stung. However, it's a CPAN module, which is more equivalent to PyPI than to the standard library, so I guess that it isn't as bad a loss of face as I feared. -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: What to use instead of nntplib?
On 2023-05-15, Skip Montanaro wrote: >> I got a nice warning today from the inews utility I use daily: >> >> DeprecationWarning: 'nntplib' is deprecated and slated for >> removal in Python 3.13 >> >> What should I use in place of nntplib? > > I'd recommend creating a PyPI project with the existing 3.12 code, > then using that from 3.13 onward. That may be the easiest option. :/ I did some googling for utilities to post articles to NNTP servers and found "postnews". Of course it's written in Python and depends on nntplib... -- https://mail.python.org/mailman/listinfo/python-list
What to use instead of nntplib?
I got a nice warning today from the inews utility I use daily: DeprecationWarning: 'nntplib' is deprecated and slated for removal in Python 3.13 What should I use in place of nntplib? -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: Is npyscreen still alive?
On 2023-04-24, Mats Wichmann wrote: > On 4/24/23 10:32, Grant Edwards wrote: > >> However... I just realized that Python's curses support is missing two >> huge chunks: both menu and form support are not there. I guess that >> explains why people feel the need to write high-level UI wrappers for >> Python curses: the high level stuff that curses does support is >> missing from the Python bindings. >> >> Adding a curses UI for my app might not be feasible after all... > > I guess it's also worth mentioning that Python curses doesn't work out > of the box on Windows - because the actual curses library isn't commonly > present on Windows. It's not hard to get hold of builds (check PyPI) but > that means it's no longer "standard". That's a good point. I neglected to mention that the use case for curses UI app is to run on headless Linux servers. It needs to work when run on a Linux by a user logged in via Putty on Windows, but I have no need to execute the application in curses-mode on Windows. -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: Python curses missing form library?
On 2023-04-24, Alan Gauld wrote: > On 24/04/2023 17:26, Grant Edwards wrote: >> Does the Python curses support in the standard library not include >> support for the curses form library? It seems to include support for >> the panel library, but I can't find any mention of the form library. > > I don't believe so. If you are building terminal based form-type > apps the best bet seems to be urwid. I haven't used it in anger > but the beginner docs I saw looked promising. urwid does indeed look nice, but it would require doing the whole bundling and installing thing. I was hoping to avoid that by sticking with stdlib and curses. -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: Is npyscreen still alive?
On 2023-04-24, Grant Edwards wrote: > The other big advantage of an ncurses program is that since curses > support is in the std library, a curses app is simpler to > distribute. Right now, the application is a single .py file you > just copy to the destination machine and run. It supports > command-line use and a Tk GUI. I can add an ncurses "CUI" without > having to either adopt a more complex bundling mechanism that > requires it to be "installed" or require that users install > dependencies via pip/apt/yum/whatever. However... I just realized that Python's curses support is missing two huge chunks: both menu and form support are not there. I guess that explains why people feel the need to write high-level UI wrappers for Python curses: the high level stuff that curses does support is missing from the Python bindings. Adding a curses UI for my app might not be feasible after all... -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Python curses missing form library?
Does the Python curses support in the standard library not include support for the curses form library? It seems to include support for the panel library, but I can't find any mention of the form library. I see in the docs that menu support is still missing. :/ -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: Is npyscreen still alive?
On 2023-04-24, Michael Torrie wrote: > On 4/21/23 15:57, Barry wrote: > >> Maybe this, recently lwn.net article, >> https://textual.textualize.io/ I was planning to check it out. > > Textual definitely looks slick and modern. And with a modern > terminal emulator it works quite well and is responsive. I'd > definitely consider it for a TUI. > > But on the Linux console, or on an older terminal, not so much. > Textual's really designed for smallish unicode fonts in a windowed > environment, not any kind of real, old-school text mode. Just > something to keep in mind. 99% of terminal users are using a modern > terminal emulator these days, with full color and unicode, which is > the target of textual. Is putty running on Windows a "modern terminal emulator" in this context? After observing some of the local IT types work, I suspect that will be a common use-case for the app I'm working on. > Curses-based programs don't look great on anything, but they do look > consistent on more primitive terminals. The other big advantage of an ncurses program is that since curses support is in the std library, a curses app is simpler to distribute. Right now, the application is a single .py file you just copy to the destination machine and run. It supports command-line use and a Tk GUI. I can add an ncurses "CUI" without having to either adopt a more complex bundling mechanism that requires it to be "installed" or require that users install dependencies via pip/apt/yum/whatever. -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Is npyscreen still alive?
I recently googled across the ncurses application framework npyscreen, and was thinking about giving it a try for a small but real project (something that would be distributed to customers), but I'm a bit concerned that npyscreen no longer "alive". The pypi page says the homepage is http://www.npcole.com/npyscreen/, which then points to a Google Code page at https://code.google.com/archive/p/npyscreen/. That page says the official repo is at https://bitbucket.org/npcole/npyscreen which returns a 404. There seems to be a copy in Github at https://github.com/npcole/npyscreen/commits/master, but the last commit was almost 4 years ago. Maybe it "just works" and is suitable for production? -- https://mail.python.org/mailman/listinfo/python-list
Re: Weak Type Ability for Python
On 2023-04-13, Cameron Simpson wrote: > On 12Apr2023 22:12, avi.e.gr...@gmail.com wrote: > >>I suspect the OP is thinking of languages like PERL or JAVA which guess >>for you and make such conversions when it seems to make sense. > > JavaScript guesses. What a nightmare. So does PHP. What's really impressive is that it never seems to guess correctly. :) -- https://mail.python.org/mailman/listinfo/python-list
Re: Weak Type Ability for Python
On 2023-04-12, Ali Mohseni Roodbari wrote: > Hi all, > Please make this command for Python (if possible): > x=1 y='a' wprint (x+y) 1a If that's what you want, use PHP or some other language. Don't try to ruin Python. > In fact make a new type of print command which can print and show strings > and integers together. -- https://mail.python.org/mailman/listinfo/python-list
Re: Dataclasses, immutability(?), and ChatGPT
On 2023-04-12, Roel Schroeven wrote: >> Huh? If we'd been discussing namedtuples over (say) dictionaries, I'd >> perhaps have accepted the reply. > > ChatGPT is wrong. > >> Anything I've 'missed'? >> - or a salutary tale of not depending upon ChatGPT etc? > You didn't miss anything, ChatGPT is wrong. The thing to look out for is > that when ChatGPT is wrong, it sounds just as convincing as when it's > right; there is no indication in it's tone or style that it's making > things up. Yep, that's how ChatGPT works. It's a program to generate output language that sounds right based on a huge training set of text. Whether that "right sounding" language agrees with real world facts or not is irrelevent to the language-generating algorithm. -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: Windows Gui Frontend
On 2023-04-02, Michael Torrie wrote: > On 4/2/23 05:09, Dietmar Schwertberger wrote: >> I also did evaluate all the GUI builder from time to time between >> 2000 and 2016 to find one that I could recommend to colleagues, >> but could not find one. Then I started contributing to wxGlade >> and I can say that since a few years it's as easy again to >> build GUIs as it was with VB6. > > [...] > > But any modern GUI toolkit has sizers and layout managers. If you're > manually placing elements you cannot deal with HiDPI or changing window > sizes. Ah, that's the brilliant thing about VB6 apps! They only work properly on machines with the same resoultion and display/font configuration as the developer. -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: Windows Gui Frontend
On 2023-04-01, Thomas Passin wrote: > Having worked with both, I'd rather use PyQt, although Tk might be > easier to get a toy app going with. Both editing windows and packing > are easier for me to understand with PyQt, for one thing. With tk it is _very_ easy to get small apps going. As the apps get larger and more complex, I find it easier to use wxPython or pyGTK (never tried pyQt). However, if you want to package that small app using cxfreeze (or whatever) tk tends to produce pretty large bundles compared to others. -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: built-in pow() vs. math.pow()
On 2023-03-30, Thomas Passin wrote: > On 3/30/2023 5:15 AM, Andreas Eisele wrote: >> [...] I was unpleasantly surprised that math.pow() does not have >> this feature, hence "from math import *" overwrites the built-in >> pow() function with a function that lacks functionality. [...] > > Not an answer to your question, but it's better not to use "import *". > It's usually better to import just the names you actually need. Or to imporot math and then use math.pow(). Unfortunately, the official Python documentation always seems to assume you do "from import *". I think that leads people to believe it's a good practice when, in fact, it's a frequent source of trouble as the OP found out. -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: What kind of "thread safe" are deque's actually?
On 2023-03-29, Jack Dangler wrote: > >> data = sorted(data) > > Sorry for any injected confusion here, but that line "data = > sorted(data)" appears as though it takes the value of the variable named > _data_, sorts it and returns it to the same variable store, so no copy > would be created. Am I missing something there? Yes, you're missing the basics of what an assignment does in Python and how objects work. Python doesn't have such a thing as "a variable st store". The assignment operator binds a name to an object. The 'sorted(data)' expression creates a new object containing a sorted copy of 'data'. The assignment then binds the name "data" to that new object. The old, unsorted object then becomes inaccessable (unless there are other names bound to it, or it's being otherwise used). At some point that old, unsorted object will "go away" completely and cease to exist. -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: Standard class for time *period*?
On 2023-03-28, Thomas Passin wrote: > On 3/28/2023 12:13 PM, Grant Edwards wrote: >> On 2023-03-28, Dennis Lee Bieber wrote: >> >>> So far, you seem to be the only person who has ever asked for a >>> single entity incorporating an EPOCH (datetime.datetime) + a >>> DURATION (datetime.timedelta). >> >> It seems to me that tuple of two timdate objects (start,end) is the >> more obvious representation, but it's six of one and a horse of the >> same color. >> >> If one really needs it to be a class, then it woulnd't be much more >> than a dozen or two lines of code... > > I think it would be more than that. The OP said You're right. I had forgotten about a few of the operations mentioned, so it might take a bit more than a couple dozen line, but not _that_ much more. The hard part would be defining those operations, and as the OP says, it doesn't seem to me like there is an obvious definition for many of them. If there's no obvious common definition for what a class is supposed to do, then there can't really be a standard one... -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: Standard class for time *period*?
On 2023-03-28, Dennis Lee Bieber wrote: > So far, you seem to be the only person who has ever asked for a > single entity incorporating an EPOCH (datetime.datetime) + a > DURATION (datetime.timedelta). It seems to me that tuple of two timdate objects (start,end) is the more obvious representation, but it's six of one and a horse of the same color. If one really needs it to be a class, then it woulnd't be much more than a dozen or two lines of code... -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: What kind of "thread safe" are deque's actually?
On 2023-03-28, Travis Griggs wrote: > A while ago I chose to use a deque that is shared between two threads. I did > so because the docs say: > > "Deques support thread-safe, memory efficient appends and pops from > either side of the deque with approximately the same O(1) > performance in either direction.” > > (https://docs.python.org/3.11/library/collections.html?highlight=deque#collections.deque) > > Earlier today, looking through some server logs I noticed that from > time to I’m getting a > > RuntimeError: deque mutated during iteration > > I guess this surprised me. When I see “thread safe”, I don’t expect > to get errors. Well, I guess it doesn't say that iteration of a deque is thread safe. It only claims that appends and pops from either end are thread safe. It doesn't even claim that inserts, removes, clear, copy, or any other operations are thread-safe. -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: Friday finking: IDE 'macro expansions'
On 2023-03-16, Thomas Passin wrote: > In general, I don't like a lot of popups and code completions, so I > tend to avoid them. I don't even like automatic parens or brace > insertion. I _hate_ it when the "editor" decides to insert stuff I didn't type. There's an html editor I use occasionally that auto-inserts the closing tag when you type an opening tag. It's, always, 100% of the time, wrong. Either the tag ends up in the wrong place, or it's a duplicate because there was already a closing tag. > They distract me, and often put the cursor somewhere I don't want it. Maybe it matters how good a typist you are, but I don't really concentrate that hard on watching the letters show up on the screen, so any sort of "IDE know better than you do" stuff tends to trip me up. > Of course, for Python code I do like automatic indentation after a > colon: if the cursor ends up in the right place, then I'm happy. Yep, I do allow emacs to do auto indent. > If I'm using a plain editor, then I usually like EditPlus. It's not > free but the cost is low and it's well worth it (but Windows only). > It knows about file types, and can do various insertions and > completions if you want (as I said, I mostly don't). I also use > Notepad++, but I more often go with EditPlus. > > What I find more useful is matching brackets/parens/braces. Not > inserting them but highlighting or (better) jumping to the matching one > when asked. Same here. -- https://mail.python.org/mailman/listinfo/python-list
Re: Baffled by readline module
On 2023-03-10, Cameron Simpson wrote: > On 10Mar2023 09:12, Grant Edwards wrote: >>On 2023-03-10, Weatherby,Gerard wrote: >>> On our Linux systems, I can up-arrow to go back to prior commands >>> and use the left and right arrows to navigate a line. The >>> functionality may be provided internally by readline. I’ve never had >>> to dig into it because it meets my needs out of the box. >> >>Apparently the cmd.Cmd docs are wrong. It says: >> >> If the readline module is loaded, input will automatically >> inherit bash-like history-list editing (e.g. Control-P scrolls >> back to the last command, Control-N forward to the next one, >> Control-F moves the cursor to the right non-destructively, >> Control-B moves the cursor to the left non-destructively, etc.). >> >>On my Python 3.10.10 Linux system, cmd.Com itself is importing the >>readline module unconditionally when I call cmdloop(). There's no 'if' >>about it. > > I was wondering about that myself, whether this is an accident of > phrasing. It doesn't say "is imported", so maybe the author was thinking > "if readline's part of the install" here. Ah, that never ocurred to me. I understood "loaded" to mean "imported" without giving it a second thought. It probably does mean supported. -- https://mail.python.org/mailman/listinfo/python-list
Re: Baffled by readline module
On 2023-03-10, Weatherby,Gerard wrote: > On our Linux systems, I can up-arrow to go back to prior commands > and use the left and right arrows to navigate a line. The > functionality may be provided internally by readline. I’ve never had > to dig into it because it meets my needs out of the box. Apparently the cmd.Cmd docs are wrong. It says: If the readline module is loaded, input will automatically inherit bash-like history-list editing (e.g. Control-P scrolls back to the last command, Control-N forward to the next one, Control-F moves the cursor to the right non-destructively, Control-B moves the cursor to the left non-destructively, etc.). On my Python 3.10.10 Linux system, cmd.Com itself is importing the readline module unconditionally when I call cmdloop(). There's no 'if' about it. [It's moot for my current usage, because my application allows multiple commands per input line, and I don't see how cmd.Cmd can support that.] Here's my application that seem to show that cmd.Cmd.cmdloop() is importing the readline module: ---testit.py import sys print('readline' in sys.modules) import cmd print('readline' in sys.modules) class MyShell(cmd.Cmd): intro = 'Welcome to my shell. Type help or ? to list commands.\n' prompt = '(what) ' file = None def do_what(self,arg): print('readline' in sys.modules) def do_bye(self, arg): print('Good bye') return True print('readline' in sys.modules) if __name__ == '__main__': print('readline' in sys.modules) MyShell().cmdloop() And here's what I see when I run it: $ python testit.py False False False False Welcome to my shell. Type help or ? to list commands. (what) what True (what) bye Good bye $ -- https://mail.python.org/mailman/listinfo/python-list
Re: Baffled by readline module
On 2023-03-10, Weatherby,Gerard wrote: > I would say, “No, readline is not the right tool.” > > cmd.Cmd is: https://docs.python.org/3/library/cmd.html. I have a > couple of cmd.Cmd modules, one of which I use daily and the other > weekly. I'll have to remember that one. It doesn't really fit my current use case, but there are others where it would work nicely. However, cmd.Cmd does not provide command recall and editing. According to the page above, that's provided by the readline module: If the readline module is loaded, input will automatically inherit bash-like history-list editing (e.g. Control-P scrolls back to the last command, Control-N forward to the next one, Control-F moves the cursor to the right non-destructively, Control-B moves the cursor to the left non-destructively, etc.). -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: Baffled by readline module
On 2023-03-10, 2qdxy4rzwzuui...@potatochowder.com <2qdxy4rzwzuui...@potatochowder.com> wrote: > On 2023-03-10 at 12:57:48 +1100, > Chris Angelico wrote: > >> On Fri, 10 Mar 2023 at 12:56, Greg Ewing via Python-list >> wrote: >> > >> > On 10/03/23 1:46 pm, Grant Edwards wrote: >> > > That's not how it acts for me. I have to "import readline" to get >> > > command line recall and editing. >> > >> > Maybe this has changed? Or is platform dependent? >> > >> > With Python 3.8 on MacOSX I can use up arrow with input() >> > to recall stuff I've typed before, without having to >> > import anything. If you run this application from the command line, you get command recall and editing when entering strings at the "cmd:" prompt? #!/usr/bin/python while True: try: line = input('cmd: ') except EOFError: print() break print('You entered "%s"' % line) >> import sys; "readline" in sys.modules >> >> Is it? Might be that something's pre-importing it. > > My ~/.pythonrc contains the following: > > import readline > import rlcompleter > readline.parse_and_bind( 'tab: complete' ) > > IIRC, that's been there "forever," certainly back into Python2, and > probably back into Python1. On my Arch Linux system Python 3.10.9, I > get readline behavior with or without those lines. I "get readline behavior" in the REPL without an "import readline", but that's irrelevent. We're talking about a command-line application that's calling input(). -- https://mail.python.org/mailman/listinfo/python-list
Re: Baffled by readline module
On 2023-03-10, Greg Ewing via Python-list wrote: > On 10/03/23 10:08 am, Grant Edwards wrote: >> It finally dawned on me after seeing an example I found elsewhere that >> you don't call some module method to fetch the next user-entered line. >> >> You call the input() built-in. >> >> Having a module modify the behavior of a built-in makes me cringe. > > Importing the module is not modifying the built-in. > > If your Python has been compiled with gnu readline support, > input() *already* provides recall and editing facilities. That's not how Python 3.10.10 works for me. When I run the code below, I do not get command recall and editing. If I hit arrow keys, I just see the escape sequence echoed and returned by input(). Likewise for things like ctrl-P, ctrl-N, etc. I have to uncomment the import statement to get command line recall and editing to work. Without the import, the escape sequences from arrow keys just end up in the input data. #!/usr/bin/python # import readline # readline.parse_and_bind('set editing-mode emacs') while True: try: line = input('enter something (EOF to quit): ') except EOFError: print() break print('ENTERED: "%s"' % line) > You only need to import the readline module if you want to > change the configuration. That's not how it acts for me. I have to "import readline" to get command line recall and editing. The parse_and_bind, doesn't seem to do anything -- emacs mode seems to be the default. > Yes, it would be helpful if the docs for the readline module > explained this. At present they seem to assume that you already > know what the readline module is for and just want a summary > of the API. > > It *is* mentioned briefly in the docs for input(), but again > somebody wanting line editing functionality wouldn't necessarily > think of looking there. -- https://mail.python.org/mailman/listinfo/python-list
Re: Baffled by readline module
On 2023-03-09, Chris Angelico wrote: > On Fri, 10 Mar 2023 at 10:04, Grant Edwards wrote: > >> Yeesh. What's _really_ embarassing is that I just stumbled across a >> small test program with which I had apparently figured this out >> 10-12 years ago. Must be about time to retire... > > You expect yourself to remember test programs you wrote a decade > ago?? I've forgotten full-on projects from that far back! Another thing that has happened a few times is that I'm trying to figure out how to do something I'm pretty sure should be possible, but I can't figure out how. After the usual resources fail, then I start Googling with varous sets of keywords. After a while, Google eventually finds the answer in an old mailing-list archive where there's a nice explanation in a post... by me. > Though, congrats on being able to stumble across it. That's quite > something. After I figured out the answer, I realized it did seem a little familar, so I tried a grep -r in my home directory which has stuff lying around from as far back as 2001. When a computer dies, I generally just cp -a (or rsync -a) $HOME to a new one. -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: Baffled by readline module
On 2023-03-09, Grant Edwards wrote: > On 2023-03-09, Cameron Simpson wrote: > >> [...] >>>It finally dawned on me after seeing an example I found elsewhere that >>>you don't call some module method to fetch the next user-entered line. >>> >>>You call the input() built-in. >> >> Ah. That's not overtly stated? [...reads...] Ah, there it is in the last >> sentence of the opening paragraph. Not quite as in-your-face as I'd have >> liked it. > > What threw me off the track for a while was that the sentence to which > you refer says it affects the "prompts offered by input()". In my head, > that means it changes the string that's printed on stdout before stuff > is read from stdin. That's different that affecting the handling of > user input read by input(). > > It doesn't actually change anything about the prompts provided by > input(). It changes the handling of the user input by input(). > > I guess I read it too literally. I must spend too much time with > computers. Yeesh. What's _really_ embarassing is that I just stumbled across a small test program with which I had apparently figured this out 10-12 years ago. Must be about time to retire... -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: Baffled by readline module
On 2023-03-09, Cameron Simpson wrote: > [...] >>It finally dawned on me after seeing an example I found elsewhere that >>you don't call some module method to fetch the next user-entered line. >> >>You call the input() built-in. > > Ah. That's not overtly stated? [...reads...] Ah, there it is in the last > sentence of the opening paragraph. Not quite as in-your-face as I'd have > liked it. What threw me off the track for a while was that the sentence to which you refer says it affects the "prompts offered by input()". In my head, that means it changes the string that's printed on stdout before stuff is read from stdin. That's different that affecting the handling of user input read by input(). It doesn't actually change anything about the prompts provided by input(). It changes the handling of the user input by input(). I guess I read it too literally. I must spend too much time with computers. > That paragraph could do with being a bullet list of use cases. -- https://mail.python.org/mailman/listinfo/python-list
Re: Baffled by readline module
On 2023-03-09, Chris Angelico wrote: > Not sure about the history file, and I would assume that if you don't > configure one, history is simply lost when you restart. But with tab > completion, unless you need to be able to input a tab character, it > should be safe to ignore the feature and leave it at the defaults. Indeed, that seems to be how it works (though I never found that stated anywhere in the docs). What's really weird about the docs is that when it is described it doesn't even _mention_ that it provides command-line recall and editing: The readline module defines a number of functions to facilitate completion and reading/writing of history files from the Python interpreter. This module can be used directly, or via the rlcompleter module, which supports completion of Python identifiers at the interactive prompt. Settings made using this module affect the behaviour of both the interpreter’s interactive prompt and the prompts offered by the built-in input() function. It just talks about manipulating history files and about tab-completion of Python identfiers. The last sentence mentions that settings affect both the REPL prompt and the prompts offered by the built-in input() function. However, I also don't really care about the "prompts offered" either. What I care about is the interactive handling of user keystrokes vis-a-vis command line recall and editing. Or is that what's meant by the phrase "behavior of the prompt"? To me "the prompt" is the string that's printed _before_ the program starts reading user keystrokes and doing the stuff I care about. It finally dawned on me after seeing an example I found elsewhere that you don't call some module method to fetch the next user-entered line. You call the input() built-in. Having a module modify the behavior of a built-in makes me cringe. I suppose this way you can easily slap-on "readline" command-line recall/editing to an existing application as long as it uses the input() built-in instead of reading from stdin. -- Grant -- https://mail.python.org/mailman/listinfo/python-list
Re: Baffled by readline module
On 2023-03-09, Grant Edwards wrote: > In an interactive command-line Python program on Linux, I want to be > able to read a line at a time from stdin, providing command line > history and editing to the user. In C, I would use GNU readline to do > that. > > Python has the readline module, which appears to be a wrapper for GNU > readline. However, I've read and re-read the documenation for that > module, but I'm completely baffled. After googling for a while, I finally stumbled across an old Python 2 example that pointed me in the right direction. Here's the sort of example I had hoped to find in the module's docs: #!/usr/bin/python import readline readline.parse_and_bind('set editing-mode emacs') while True: try: line = input('enter something (EOF to quit): ') except EOFError: print() break print('You entered: "%s"' % line) -- https://mail.python.org/mailman/listinfo/python-list