Re: Assistance Request - Issue with Installing 'pip' despite Python 3.10 Installation

2023-06-07 Thread MRAB via Python-list

On 2023-06-07 15:54, Florian Guilbault via Python-list wrote:

Dear Python Technical Team,

I hope this email finds you well. I am reaching out to you today to seek
assistance with an issue I am facing regarding the installation of 'pip'
despite my numerous attempts to resolve the problem.

Recently, I performed installation, uninstallation, and even repair
operations on Python 3.10 on my computer. However, I have noticed that
'pip' has never been installed successfully. When I check via the command
prompt, I receive the following error: "'pip' is not recognized as an
internal or external command, operable program, or batch file."

I have tried several approaches to resolve this issue. I have verified that
the PATH environment variable is correctly configured to include the path
to the Python Scripts directory. I have also attempted to run the
'get-pip.py' installation script from the command line, but it did not work
either.

I am aware that 'pip' is typically installed automatically with Python, but
I am encountering this persistent difficulty. Therefore, I would like to
request your assistance and expertise in resolving this 'pip' installation
issue. I would like to be able to use 'pip' to manage my Python packages
efficiently.

I am open to any suggestions and steps you can provide to help me resolve
this problem. Please note that I am a user on the Windows operating system.

Thank you sincerely for your attention and support. I eagerly await your
guidance to resolve this situation.


On Windows, it's recommended to use the Python Launcher and the pip module:

py -m pip install whatever

--
https://mail.python.org/mailman/listinfo/python-list


Re: Trouble with defaults and timeout decorator

2023-06-24 Thread MRAB via Python-list

On 2023-06-24 17:18, Jason Friedman via Python-list wrote:

I'm writing a database connectivity module to be used by other modules and
leveraging the jaydebeapi module.
  From what I can tell jaydebeapi contains no built-in timeout capability, so
then I turned to https://pypi.org/project/timeout-decorator/.
My goal is to have a default timeout of, say, 10 seconds, which can be
overridden by the caller.


import jaydebeapi
from timeout_decorator import timeout

class Database:
 database_connection = None
 database_name, user_name, password, host, port = stuff
 timeout = None

 def __init__(self, timeout=10):
 self.timeout = timeout

 @timeout(self.timeout)
 def get_connection(self):
 if not self.database_connection:
 self.database_connection = jaydebeapi.connect(some_args)
 return self.database_connection


The trouble occurs on line 12 with:
NameError: name 'self' is not defined


The decorator is applied when the class is defined, but 'self' exists 
only in 'Database.__init__' and 'Database.get_connection' when they are 
called.


Have you tried applying the decorator "manually" in 'Database.__init__'?

def __init__(self, timeout=10):
self.timeout = timeout
self.get_connection = timeout(self.timeout)(self.get_connection)

--
https://mail.python.org/mailman/listinfo/python-list


Re: Setup-tools

2023-07-15 Thread MRAB via Python-list

On 2023-07-15 07:12, YOUSEF EZZAT via Python-list wrote:

Hey!. i face a problem when i get setup packages by pip
when i code this : "pip install numpy" in my command line it gives me error
"ModuleNotFoundError: No module named 'distutils'"

please, i need help for solving this problem.
i have python 3.12.0b4


What do you normally do when it can't find a module? Install it via pip!

pip install distutils

By the way, do you really need Python 3.12? It's still in beta, so 
unless you're specifically checking whether it works, ready for its 
final release, you'd be better off with Python 3.11.


--
https://mail.python.org/mailman/listinfo/python-list


Re: Passing info to function used in re.sub

2023-09-03 Thread MRAB via Python-list

On 2023-09-03 17:10, Jan Erik Moström via Python-list wrote:

I'm looking for some advice for how to write this in a clean way

I want to replace some text using a regex-pattern, but before creating 
replacement text I need to some file checking/copying etc. My code right now 
look something like this:

def fix_stuff(m):
# Do various things that involves for info
# that what's available in m
replacement_text = m.group(1) + global_var1 + global_var2
return replacement_text

and the call comes here

global_var1 = "bla bla"
global_var2 = "pff"

new_text = re.sub(im_pattern,fix_stuff,md_text)


The "problem" is that I've currently written some code that works but it uses 
global variables ... and I don't like global variables. I assume there is a better way to 
write this, but how?


You could use pass an anonymous function (a lambda) to re.sub:

def fix_stuff(m, var1, var2):
# Do various things that involves for info
# that what's available in m
replacement_text = m.group(1) + var1 + var2
return replacement_text

global_var1 = "bla bla"
global_var2 = "pff"

new_text = re.sub(im_pattern, lambda m, var1=global_var1, 
var2=global_var2: fix_stuff(m, var1, var2), md_text)


Or, if you prefer a named function, define one just before the re.sub:

def fix_stuff(m, var1, var2):
# Do various things that involves for info
# that what's available in m
replacement_text = m.group(1) + var1 + var2
return replacement_text

global_var1 = "bla bla"
global_var2 = "pff"

def fix_it(m, var1=global_var1, var2=global_var2):
return fix_stuff(m, var1, var2)

new_text = re.sub(im_pattern, fix_it, md_text)

--
https://mail.python.org/mailman/listinfo/python-list


Re: Forward References

2023-09-03 Thread MRAB via Python-list

On 2023-09-03 21:43, Jonathan Gossage via Python-list wrote:

I am attempting to use forward references in my program and I am failing.
This also does not work with the older way of putting the name of a class
as a string. Here is some sample code:

from __future__ import annotations

from dataclasses import dataclass
from typing import TypeAlias


ColorDef: TypeAlias = RGB | int | str



@dataclass(frozen=True, slots=True)
class RGB(object):

Can anyone suggest how I should fix this without reversing the statement
order?

 pass

The usual way to deal with forward type references is to use a string 
literal, i.e. 'RGB', but that doesn't work with '|', so use typing.Union 
instead:


from typing import TypeAlias, Union

ColorDef: TypeAlias = Union['RGB', int, str]

--
https://mail.python.org/mailman/listinfo/python-list


Re: Tkinter ttk Treeview binding responds to past events!

2023-09-12 Thread MRAB via Python-list

On 2023-09-12 06:43, John O'Hagan via Python-list wrote:

On Mon, 2023-09-11 at 22:25 +0200, Mirko via Python-list wrote:

Am 11.09.23 um 14:30 schrieb John O'Hagan via Python-list:
> I was surprised that the code below prints 'called' three times.
> 
> 
> from tkinter import *

> from tkinter.ttk import *
> 
> root=Tk()
> 
> def callback(*e):

>      print('called')
> 
> tree = Treeview(root)

> tree.pack()
> 
> iid = tree.insert('', 0, text='test')
> 
> tree.selection_set(iid)

> tree.selection_remove(iid)
> tree.selection_set(iid)
> 
> tree.bind('<>', callback)
> 
> mainloop()
> 
> In other words, selection events that occurred _before_ the

> callback
> function was bound to the Treeview selections are triggering the
> function upon binding. AFAIK, no other tk widget/binding
> combination
> behaves this way (although I haven't tried all of them).
> 
> This was a problem because I wanted to reset the contents of the

> Treeview without triggering a relatively expensive bound function,
> but
> found that temporarily unbinding didn't prevent the calls.
> 
> I've worked around this by using a regular button-click binding for

> selection instead, but I'm curious if anyone can cast any light on
> this.
> 
> Cheers
> 
> John



AFAIK (it's been quite some time, since I used Tk/Tkinter):

These selection events are not triggered upon binding, but after the 
mainloop has startet. Tk's eventloop is queue-driven, so the 
tree.selection_{set,remove}() calls just place the events on the 
queue. After that, you setup a callback and when the mainloop 
starts, it processes the events from the queue, executing the 
registered callback.


I seem to remember, that I solved a similar issue by deferring the 
callback installation using root.after().



from tkinter import *
from tkinter.ttk import *

root=Tk()

def callback(*e):
 print('called')

tree = Treeview(root)
tree.pack()

iid = tree.insert('', 0, text='test')

tree.selection_set(iid)
tree.selection_remove(iid)
tree.selection_set(iid)

root.after(100, lambda: tree.bind('<>', callback))

mainloop()



This does not print "called" at all after startup (but still selects 
the entry), because the callback has not been installed when the 
mainloop starts. But any subsequent interaction with the list 
(clicking) will print it (since the callback is then setup).


HTH



Thanks for your reply. However, please see the example below, which is
more like my actual use-case. The selection events take place when a
button is pressed, after the mainloop has started but before the
binding. This also prints 'called' three times.

from tkinter import *
from tkinter.ttk import *

class Test:

def __init__(self):
   root=Tk()
   self.tree = Treeview(root)
   self.tree.pack()
   self.iid = self.tree.insert('', 0, text='test')
   Button(root, command=self.temp_unbind).pack()
   mainloop()

def callback(self, *e):
   print('called')

def temp_unbind(self):

   self.tree.unbind('<>')
   self.tree.selection_set(self.iid)
   self.tree.selection_remove(self.iid)
   self.tree.selection_set(self.iid)
   self.tree.bind('<>', self.callback)
   #self.tree.after(0, lambda: self.tree.bind('<>',
   self.callback))
   
c=Test()


It seems the events are still queued, and then processed by a later
bind?

However, your solution still works, i.e. replacing the bind call with
the commented line. This works even with a delay of 0, as suggested in
Rob Cliffe's reply. Does the call to after clear the event queue
somehow?

My issue is solved, but I'm still curious about what is happening here.


Yes, it's still queuing the events.
When an event occurs, it's queued.

So, you unbound and then re-bound the callback in temp_unbind?

Doesn't matter.

All that matters is that on returning from temp_unbind to the main event 
loop, there are events queued and there's a callback registered, so the 
callback is invoked.


Using the .after trick queues an event that will re-bind the callback 
_after_ the previous events have been handled.

--
https://mail.python.org/mailman/listinfo/python-list


Re: Tkinter ttk Treeview binding responds to past events!

2023-09-12 Thread MRAB via Python-list

On 2023-09-12 19:51, Mirko via Python-list wrote:

Am 12.09.23 um 07:43 schrieb John O'Hagan via Python-list:


My issue is solved, but I'm still curious about what is happening here.


MRAB already said it: When you enter the callback function, Tk's
mainloop waits for it to return. So what's happening is:

1. Tk's mainloop pauses
2. temp_unbind() is called
3. TreeviewSelect is unbound
4. events are queued
5. TreeviewSelect is bound again
6. temp_unbind() returns
7. Tk's mainloop continues with the state:
- TreeviewSelect is bound
- events are queued

Am 11.09.23 um 23:58 schrieb Rob Cliffe:


Indeed.  And you don't need to specify a delay of 100 milliseconds. 0 will work 
(I'm guessing that's because queued actions are performed in the order that 
they were queued).


Ah, nice, didn't know that!

Well, strictly speaking, it's the order in which they were queued except 
for .after, which will be postponed if you specify a positive delay.


[snip]

--
https://mail.python.org/mailman/listinfo/python-list


Re: Tkinter ttk Treeview binding responds to past events!

2023-09-12 Thread MRAB via Python-list

On 2023-09-13 00:40, John O'Hagan via Python-list wrote:

On Tue, 2023-09-12 at 20:51 +0200, Mirko via Python-list wrote:

Am 12.09.23 um 07:43 schrieb John O'Hagan via Python-list:

> My issue is solved, but I'm still curious about what is happening
> here.

MRAB already said it: When you enter the callback function, Tk's 
mainloop waits for it to return. So what's happening is:


1. Tk's mainloop pauses
2. temp_unbind() is called
3. TreeviewSelect is unbound
4. events are queued
5. TreeviewSelect is bound again
6. temp_unbind() returns
7. Tk's mainloop continues with the state:
 - TreeviewSelect is bound
 - events are queued

[. . .]


Thanks (also to others who have explained), now I get it!


FWIW, here's a version without after(), solving this purely on the 
python side, not by temporarily unbinding the event, but by 
selectively doing nothing in the callback function.


from tkinter import *
from tkinter.ttk import *

class Test:
 def __init__(self):
 self.inhibit = False
 root=Tk()
 self.tree = Treeview(root)
 self.tree.pack()
 self.iid = self.tree.insert('', 0, text='test')
 Button(root, command=self.temp_inhibit).pack()
 mainloop()

 def callback(self, *e):
 if not self.inhibit:
 print('called')

 def temp_inhibit(self):
 self.inhibit = True
 self.tree.selection_set(self.iid)
 self.tree.selection_remove(self.iid)
 self.tree.selection_set(self.iid)
 self.inhibit = False
 self.callback()

c=Test()




I like this solution better - it's much more obvious to me what it's
doing.

That code is not binding at all, it's just calling 'temp_inhibit' when 
the button is clicked.


You can remove all uses of self.inhibit and rename 'temp_inhibit' to 
something more meaningful, like 'delete_item'.


--
https://mail.python.org/mailman/listinfo/python-list


Re: The GIL and PyEval_RestoreThread

2023-09-26 Thread MRAB via Python-list

On 2023-09-26 14:20, Peter Ebden via Python-list wrote:

Hi all,

I've been working on embedding Python and have an interesting case around
locking with PyEval_RestoreThread which wasn't quite doing what I expect,
hoping someone can explain what I should expect here.

I have a little example (I'm running this in parallel from two different
threads; I have some more C code for that but I don't think it's super
interesting):

void run_python(PyThreadState* thread) {
   LOG("Restoring thread %p...", thread);
   PyEval_RestoreThread(thread);
   LOG("Restored thread %p", thread);
   PyRun_SimpleString("import time; print('sleeping'); time.sleep(3.0)");
   LOG("Saving thread...");
   PyThreadState* saved_thread = PyEval_SaveThread();
   LOG("Saved thread %p", saved_thread);
}

This produces output like
11:46:48.110058893: Restoring thread 0xabc480...
11:46:48.110121656: Restored thread 0xabc480
11:46:48.110166060: Restoring thread 0xabc480...
sleeping
11:46:48.110464194: Restored thread 0xabc480
sleeping
11:46:51.111307541: Saving thread...
11:46:51.111361075: Saved thread 0xabc480
11:46:51.113116633: Saving thread...
11:46:51.113177605: Saved thread 0xabc480

The thing that surprises me is that both threads seem to be able to pass
PyEval_RestoreThread before either reaches the corresponding
PyEval_SaveThread call, which I wasn't expecting to happen; I assumed that
since RestoreThread acquires the GIL, that thread state would remain locked
until it's released.

I understand that the system occasionally switches threads, which I guess
might well happen with that time.sleep() call, but I wasn't expecting the
same thread to become usable somewhere else. Maybe I am just confusing
things by approaching the same Python thread from multiple OS threads
concurrently and should be managing my own locking around that?

Storing the result of PyEval_SaveThread in a local variable looks wrong 
to me.


In the source for the regex module, I release the GIL with 
PyEval_SaveThread and save its result. Then, when I want to claim the 
GIL, I pass that saved value to PyEval_RestoreThread.


You seem to be releasing the GIL and discarding the result, so which 
thread are you resuming when you call PyEval_RestoreThread?


It looks like you're resuming the same thread twice. As it's already 
resumed the second time, no wonder it's not blocking!


--
https://mail.python.org/mailman/listinfo/python-list


Re: error of opening Python

2023-09-26 Thread MRAB via Python-list

On 2023-09-27 03:30, Chris Roy-Smith via Python-list wrote:

On 26/9/23 22:27, Abdelkhelk ashref salay eabakh via Python-list wrote:

Dear Python team,

This is my not first time using Python, I tried to launch Python and it showed


I'm no expert but

"Python 3.11.3 (tags/v3.11.3:f3909b8, Apr  4 2023, 23:49:59) [MSC v.1934 64 bit 
(AMD64)] on win

surely running a 64 bit version of python in a 23mbit version of windows
will cause significant problems!


It says "win32" even on 64-bit Windows.

If you try to run 64-bit Python on 32-bit Windows, it won't get as far 
as printing that header!



try the correct python or windows

regards,




Type "help", "copyright", "credits" or "license" for more information." I
don't know what this meant and how to fix this. Could you please help me?
Thank you very much.

Kind regards






--
https://mail.python.org/mailman/listinfo/python-list


Re: How to write list of integers to file with struct.pack_into?

2023-10-02 Thread MRAB via Python-list

On 2023-10-01 23:04, Jen Kris via Python-list wrote:
>
> Iwant to write a list of 64-bit integers to a binary file. 
Everyexample I have seen in my research convertsit to .txt, but I want 
it in binary.  I wrote this code,based on some earlier work I have done:

>
> buf= bytes((len(qs_array)) * 8)
>
> foroffset in range(len(qs_array)):
>
> item_to_write= bytes(qs_array[offset])
>
> struct.pack_into(buf,"
> ButI get the error "struct.error: embedded null character."
>
> Maybethere's a better way to do this?
>
You can't pack into a 'bytes' object because it's immutable.

The simplest solution I can think of is:

buf = struct.pack("<%sQ" % len(qs_array), *qs_array)
--
https://mail.python.org/mailman/listinfo/python-list


Re: PyInstaller value error: Invalid Windows resource specifier

2023-10-30 Thread MRAB via Python-list

On 2023-10-30 19:19, McDermott Family via Python-list wrote:

Hello, I am trying to create a one file executable with pyinstaller 6.1.0
and auto-py-to-exe 2.41.0 using Python version 3.10.9 in a virtual
environment.

Some points before the output of pinstaller is shown. My resource .py file
is there where it should be. Also I can fun my program from the command-line


and it does work with the compiled resource file without a problem. Any help
would be greatly appreciated. Thank you.


Running auto-py-to-exe v2.41.0

Building directory: C:\Users\icnte\AppData\Local\Temp\tmpp870eytg

Provided command: pyinstaller --noconfirm --onefile --windowed --icon
"D:/Work/Python/cfepy310/xl/cfegui/Resources/Conform-e_48_1.ico" --name
"Conform-e" --clean --log-level "DEBUG" --debug "all" --version-file
"D:/Work/Python/cfepy310/xl/cfegui/cfe_versionfile.txt" --resource
"D:/Work/Python/cfepy310/xl/cfegui/cfe_Resource_rc.py"
"D:/Work/Python/cfepy310/xl/cfegui/cfe_MainForm.py"

Recursion Limit is set to 5000

Executing: pyinstaller --noconfirm --onefile --windowed --icon
D:/Work/Python/cfepy310/xl/cfegui/Resources/Conform-e_48_1.ico --name
Conform-e --clean --log-level DEBUG --debug all --version-file
D:/Work/Python/cfepy310/xl/cfegui/cfe_versionfile.txt --resource
D:/Work/Python/cfepy310/xl/cfegui/cfe_Resource_rc.py
D:/Work/Python/cfepy310/xl/cfegui/cfe_MainForm.py --distpath
C:\Users\icnte\AppData\Local\Temp\tmpp870eytg\application --workpath
C:\Users\icnte\AppData\Local\Temp\tmpp870eytg\build --specpath
C:\Users\icnte\AppData\Local\Temp\tmpp870eytg


[snip]


ValueError: Invalid Windows resource specifier
'D:WorkPythoncfepy310xlcfeguicfe_Resource_rc.py'!
For arbitrary data file, the format is 'filename,type,name,[language]'!

  


Project output will not be moved to output folder

Complete.


In the docs for "--resource" it says:

"""FILE can be a data file or an exe/dll. For data files, at least TYPE 
and NAME must be specified."""


That might be the problem, but I haven't been able to find out what 
"TYPE" means!


I also wonder whether "--add-data" would work.

--
https://mail.python.org/mailman/listinfo/python-list


Re: Checking if email is valid

2023-11-06 Thread MRAB via Python-list

On 2023-11-06 08:57, Simon Connah via Python-list wrote:



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 thing I truly hate is when you have two telephone number fields. One for 
landline and one for mobile. I mean who in hell has a landline these days? And 
not accepting your mobile number in the landline number field is just when I 
give up. Or having a landline only field that does not accept mobile phones.


I have a landline. It's also how I access the internet.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Writing to clipboard in Python 3.11

2023-11-07 Thread MRAB via Python-list

On 2023-11-06 00:51, Rob Cliffe via Python-list wrote:

Recently I switched from Python 3.8.3 to Python 3.11.4.  A strange
problem appeared which was not there before:
I am using the win32clipboard backage (part of pywin32), and when I use
SetClipboardData() to write text which consists ENTIRELY OF DIGITS to
the clipboard, I either get an error (not always the same error message)
or a program crash.  The problem does not appear if I use
SetClipboardText() instead.
Sample program:

from win32clipboard import *
OpenClipboard()
SetClipboardData(CF_UNICODETEXT, "A")
SetClipboardData(CF_UNICODETEXT, "A0")
SetClipboardData(CF_UNICODETEXT, "0A")
SetClipboardText("0", CF_UNICODETEXT)
print("OK so far")
SetClipboardData(CF_UNICODETEXT, "0")
CloseClipboard()

Sample output:

OK so far
Traceback (most recent call last):
    File "R:\W.PY", line 8, in 
      SetClipboardData(CF_UNICODETEXT, "0")
pywintypes.error: (0, 'SetClipboardData', 'No error message is available')

I can get round the problem by using SetClipboardText().  But can anyone
shed light on this?


It also happens in Python 3.10, but not Python 3.9.

--
https://mail.python.org/mailman/listinfo/python-list


Re: fCONV_AUSRICHTG is not defined - Why?

2023-11-07 Thread MRAB via Python-list

On 2023-11-07 18:30, dn via Python-list wrote:

On 08/11/2023 06.47, Egon Frerich via Python-list wrote:

I've no idea why this happens. In a module there are lists and definitions:

...


     ["%s%s%s " % (i[fCONV_AUSRICHTG], i[fLG2], i[fTYP]) for i in Felder])
   File "/home/egon/Entw/Geldspur/geldspur/gui/GUI_Konfig.py", line 90, 
in 

     ["%s%s%s " % (i[fCONV_AUSRICHTG], i[fLG2], i[fTYP]) for i in Felder])
NameError: name 'fCONV_AUSRICHTG' is not defined

You see "Felder" and with "0 0 3 4" the correct value 4 for 
fCONV_AUSRICHTG. But there is the NameError.


What does  mean? Is there a change from python2 to python3?


Works for me (Python 3.11 on Fedora-Linux 37)
- both as a script, and simple/single import.

What happens when you extract the second dimension's definitions into a
module of their own, and import that (with/out less-sophisticated join)?


The missing detail is this line from the traceback:

   File "/home/egon/Entw/Geldspur/geldspur/gui/GUI_Konfig.py", line 11,
in 
 class GUIcfg:

Here's a small example that shows the problem:

8<
#!python3.11
# -*- encoding: utf-8 -*-

class Test:
hello = "hello"
print(hello)
print([[zero] for _ in range(4)])
8<

and its traceback:

8<
hello
Traceback (most recent call last):
  File "C:\Projects\regex3\test_clipboard.py", line 4, in 
class Test:
  File "C:\Projects\regex3\test_clipboard.py", line 7, in Test
print([zero for _ in range(4)])
 ^^
  File "C:\Projects\regex3\test_clipboard.py", line 7, in 
print([zero for _ in range(4)])
   
NameError: name 'zero' is not defined
8<

'zero' is visible in:

print(hello)

but not in:

print([zero for _ in range(4)])

Something to do with how scoping is implemented in comprehensions?

--
https://mail.python.org/mailman/listinfo/python-list


Re: fCONV_AUSRICHTG is not defined - Why?

2023-11-07 Thread MRAB via Python-list

On 2023-11-07 19:20, Jim Schwartz via Python-list wrote:

Where do you define fCONV_AUSRICHTG? It must be initialized or defined 
somewhere. Did you leave out a statement from the python 2 version?


It's given its value here:

(
fNAME,
fLG1,
fLG2,
fTYP,
fCONV_AUSRICHTG,
fENTRY_AUSRICHTG,
fTEXT_AUSRICHTUNG,
fHOLFUNKT,
fPRUEFFUNKT,
fPRUEF_ARG,
) = list(range(10))




On Nov 7, 2023, at 1:06 PM, Thomas Passin via Python-list 
 wrote:

On 11/7/2023 12:47 PM, Egon Frerich via Python-list wrote:

I've no idea why this happens. In a module there are lists and definitions:
Felder = [
# Name   lg1  lg2 typ   Ausrichtung Holen Prüfen Prüfvorg
["Jahr", 4, 5, "u", "", "right", "center"],
["Monat", 2, 5, "u", "", "right", "center"],
["Tag", 2, 3, "u", "", "right", "center"],
["Belegnr", 5, 7, "s", "", "right", "center"],
["Bank", 2, 4, "u", "", "center", "center"],
["Art", 2, 3, "u", "", "center", "center"],
["Aufg", 2, 4, "u", "", "center", "center"],
["Text", 25, 25, "s", "-", "left", "left"],
["Ergänzung", 12, 12, "s", "-", "left", "left"],
["Betrag", 13, 13, "s", "", "right", "right"],
["W", 1, 2, "s", "", "center", "center"],
["WBetrag", 7, 7, "s", "", "right", "right"],
["Kurs", 6, 6, "s", "", "right", "right"],
]
"Reihenfolge in der Dimension 1"
(
fJAHR,
fMONAT,
fTAG,
fBELEGNR,
fBANK,
fART,
fAUFGABE,
fTEXT,
fTEXTERG,
fBETRAG,
fWAEHRUNG,
fBETRAGinWAEHRUNG,
fUMRECHNUNGSKURS,
) = list(range(13))
"Reihenfolge in der Dimension 2"
(
fNAME,
fLG1,
fLG2,
fTYP,
fCONV_AUSRICHTG,
fENTRY_AUSRICHTG,
fTEXT_AUSRICHTUNG,
fHOLFUNKT,
fPRUEFFUNKT,
fPRUEF_ARG,
) = list(range(10))
Two lines with  test statements follow and the statement which produces an 
error:
print(Felder)
print(fJAHR, fNAME, fTYP, fCONV_AUSRICHTG)
akette = "%" + "%".join(
["%s%s%s " % (i[fCONV_AUSRICHTG], i[fLG2], i[fTYP]) for i in Felder])
The traceback shows:
$ python3 testGeldspurGUI.py
[['Jahr', 4, 5, 'u', '', 'right', 'center'], ['Monat', 2, 5, 'u', '', 'right', 
'center'], ['Tag', 2, 3, 'u', '', 'right', 'center'], ['Belegnr', 5, 7, 's', 
'', 'right', 'center'], ['Bank', 2, 4, 'u', '', 'center', 'center'], ['Art', 2, 
3, 'u', '', 'center', 'center'], ['Aufg', 2, 4, 'u', '', 'center', 'center'], 
['Text', 25, 25, 's', '-', 'left', 'left'], ['Ergänzung', 12, 12, 's', '-', 
'left', 'left'], ['Betrag', 13, 13, 's', '', 'right', 'right'], ['W', 1, 2, 
's', '', 'center', 'center'], ['WBetrag', 7, 7, 's', '', 'right', 'right'], 
['Kurs', 6, 6, 's', '', 'right', 'right']]
0 0 3 4
Traceback (most recent call last):
  File "/home/egon/Entw/Geldspur/geldspur/testGeldspurGUI.py", line 15, in 

from tests.testU2 import testU2
  File "/home/egon/Entw/Geldspur/geldspur/tests/testU2.py", line 9, in 
from gui.GUI_Konfig import GUIcfg
  File "/home/egon/Entw/Geldspur/geldspur/gui/GUI_Konfig.py", line 11, in 

class GUIcfg:
  File "/home/egon/Entw/Geldspur/geldspur/gui/GUI_Konfig.py", line 90, in GUIcfg
["%s%s%s " % (i[fCONV_AUSRICHTG], i[fLG2], i[fTYP]) for i in Felder])
  File "/home/egon/Entw/Geldspur/geldspur/gui/GUI_Konfig.py", line 90, in 

["%s%s%s " % (i[fCONV_AUSRICHTG], i[fLG2], i[fTYP]) for i in Felder])
NameError: name 'fCONV_AUSRICHTG' is not defined
You see "Felder" and with "0 0 3 4" the correct value 4 for fCONV_AUSRICHTG. 
But there is the NameError.
What does  mean? Is there a change from python2 to python3?


You are using a syntax that I don't understand, but "listcomp" means a list 
comprehenson.



--
https://mail.python.org/mailman/listinfo/python-list


Re: fCONV_AUSRICHTG is not defined - Why?

2023-11-07 Thread MRAB via Python-list

On 2023-11-07 20:56, Thomas Passin via Python-list wrote:

On 11/7/2023 3:29 PM, MRAB via Python-list wrote:

On 2023-11-07 19:20, Jim Schwartz via Python-list wrote:
Where do you define fCONV_AUSRICHTG? It must be initialized or defined 
somewhere. Did you leave out a statement from the python 2 version?



It's given its value here:

     (
     fNAME,
     fLG1,
     fLG2,
     fTYP,
     fCONV_AUSRICHTG,
     fENTRY_AUSRICHTG,
     fTEXT_AUSRICHTUNG,
     fHOLFUNKT,
     fPRUEFFUNKT,
     fPRUEF_ARG,
     ) = list(range(10))



This construction is a sneaky way to assign index numbers to list
entries.  A simplified example:

  >>> S1 = 'string 1'
  >>> S2 = 'string 2'
  >>> (fS1, fS2) = list(range(2))
  >>> fS1
0
  >>>
  >>> fS2
1


You don't need the 'list', though: range(...) will work on its own.

[snip]

--
https://mail.python.org/mailman/listinfo/python-list


Re: Beep on WIndows 11

2023-11-12 Thread MRAB via Python-list

On 2023-11-12 11:16, Chris Angelico via Python-list wrote:

On Sun, 12 Nov 2023 at 21:27, Y Y via Python-list
 wrote:


I am curious and humble to ask: What is the purpose of a BEEP?



There are several purposes. I can't say which of these are relevant to
the OP, but some or all of them could easily be.

* A very very simple notification that can be triggered by any program
* An audio cue that is not routed to your regular audio system (good
if you use headphones but are AFK)
* An extremely low level signal that requires little-to-no processing power
* An emergency signal that does not even require a CPU (probably not
in this instance though!)
* Imitating a pre-existing audio signal that works by beeping

Depending on what's needed, a more complex system might suffice (for
example, I cover the first two points by having an entire separate
audio subsystem with its own dedicated speakers, which I can invoke
using VLC in a specific configuration); but a basic beep is definitely
of value. I suspect in this situation that the first point is
important here, but it's up to the OP to elaborate.

(Note that the "no CPU emergency sound" option usually requires a
motherboard-mounted speaker or speaker header, which not all have
these days. Sad.)


Recently, I wanted a program to beep.

In the old days, with a BBC micro, that was simple. It had 3 tone 
channels and 1 white noise channel, with control over frequency, 
duration and volume, beeps on different channels could be synchronised 
to start at the same time, there was a sound queue so that the SOUND 
command returned immediately, and there was an ENVELOPE command for 
controlling the attack, decay, sustain and release. All this on an 8-bit 
machine!


My current PC is way more powerful. 64-bit processor, GBs of RAM, etc. 
Python offers winsound.Beep. 1 tone, no volume control, and it blocks 
while beeping.

--
https://mail.python.org/mailman/listinfo/python-list


Re: xor operator

2023-11-13 Thread MRAB via Python-list

On 2023-11-13 21:03, Barry via Python-list wrote:




On 13 Nov 2023, at 17:48, Dom Grigonis  wrote:

Short circuiting happens, when:
xor([True, True, False, False], n=1)
At index 1 it is clear that the answer is false.


Can you share an example with 4 values that is true?
And explain why it is xor.

I think what the OP wants is something that stops after finding n true 
items.


It's a more general form of what 'any' and 'all' do - 'any' stops when 
it finds 1 true item and 'all' stops when it finds 1 false item.


In general, you might want to stop when you find n true items or n false 
items, or whatever.


--
https://mail.python.org/mailman/listinfo/python-list


Re: Code improvement question

2023-11-14 Thread MRAB via Python-list

On 2023-11-14 23:14, Mike Dewhirst via Python-list wrote:

I'd like to improve the code below, which works. It feels clunky to me.

I need to clean up user-uploaded files the size of which I don't know in
advance.

After cleaning they might be as big as 1Mb but that would be super rare.
Perhaps only for testing.

I'm extracting CAS numbers and here is the pattern xx-xx-x up to
xxx-xx-x eg., 1012300-77-4

def remove_alpha(txt):

      """  r'[^0-9\- ]':

      [^...]: Match any character that is not in the specified set.

      0-9: Match any digit.

      \: Escape character.

      -: Match a hyphen.

      Space: Match a space.

      """

  cleaned_txt = re.sub(r'[^0-9\- ]', '', txt)

      bits = cleaned_txt.split()

      pieces = []

      for bit in bits:

      # minimum size of a CAS number is 7 so drop smaller clumps of digits

      pieces.append(bit if len(bit) > 6 else "")

      return " ".join(pieces)


Many thanks for any hints


Why don't you use re.findall?

re.findall(r'\b[0-9]{2,7}-[0-9]{2}-[0-9]{2}\b', txt)

--
https://mail.python.org/mailman/listinfo/python-list


Re: Code improvement question

2023-11-14 Thread MRAB via Python-list

On 2023-11-15 03:41, Mike Dewhirst via Python-list wrote:

On 15/11/2023 10:25 am, MRAB via Python-list wrote:

On 2023-11-14 23:14, Mike Dewhirst via Python-list wrote:

I'd like to improve the code below, which works. It feels clunky to me.

I need to clean up user-uploaded files the size of which I don't know in
advance.

After cleaning they might be as big as 1Mb but that would be super rare.
Perhaps only for testing.

I'm extracting CAS numbers and here is the pattern xx-xx-x up to
xxx-xx-x eg., 1012300-77-4

def remove_alpha(txt):

      """  r'[^0-9\- ]':

      [^...]: Match any character that is not in the specified set.

      0-9: Match any digit.

      \: Escape character.

      -: Match a hyphen.

      Space: Match a space.

      """

  cleaned_txt = re.sub(r'[^0-9\- ]', '', txt)

      bits = cleaned_txt.split()

      pieces = []

      for bit in bits:

      # minimum size of a CAS number is 7 so drop smaller clumps 
of digits


      pieces.append(bit if len(bit) > 6 else "")

      return " ".join(pieces)


Many thanks for any hints


Why don't you use re.findall?

re.findall(r'\b[0-9]{2,7}-[0-9]{2}-[0-9]{2}\b', txt)


I think I can see what you did there but it won't make sense to me - or
whoever looks at the code - in future.

That answers your specific question. However, I am in awe of people who
can just "do" regular expressions and I thank you very much for what
would have been a monumental effort had I tried it.

That little re.sub() came from ChatGPT and I can understand it without
too much effort because it came documented

I suppose ChatGPT is the answer to this thread. Or everything. Or will be.


\b  Word boundary
[0-9]{2,7}  2..7 digits
-   "-"
[0-9]{2}2 digits
-   "-"
[0-9]{2}2 digits
\b  Word boundary

The "word boundary" thing is to stop it matching where there are letters 
or digits right next to the digits.


For example, if the text contained, say, "123456789-12-1234", you 
wouldn't want it to match because there are more than 7 digits at the 
start and more than 2 digits at the end.


--
https://mail.python.org/mailman/listinfo/python-list


Re: Code improvement question

2023-11-16 Thread MRAB via Python-list

On 2023-11-17 01:15, Mike Dewhirst via Python-list wrote:

On 15/11/2023 3:08 pm, MRAB via Python-list wrote:

On 2023-11-15 03:41, Mike Dewhirst via Python-list wrote:

On 15/11/2023 10:25 am, MRAB via Python-list wrote:

On 2023-11-14 23:14, Mike Dewhirst via Python-list wrote:
I'd like to improve the code below, which works. It feels clunky to 
me.


I need to clean up user-uploaded files the size of which I don't 
know in

advance.

After cleaning they might be as big as 1Mb but that would be super 
rare.

Perhaps only for testing.

I'm extracting CAS numbers and here is the pattern xx-xx-x up to
xxx-xx-x eg., 1012300-77-4

def remove_alpha(txt):

      """  r'[^0-9\- ]':

      [^...]: Match any character that is not in the specified set.

      0-9: Match any digit.

      \: Escape character.

      -: Match a hyphen.

      Space: Match a space.

      """

  cleaned_txt = re.sub(r'[^0-9\- ]', '', txt)

      bits = cleaned_txt.split()

      pieces = []

      for bit in bits:

      # minimum size of a CAS number is 7 so drop smaller 
clumps of digits


      pieces.append(bit if len(bit) > 6 else "")

      return " ".join(pieces)


Many thanks for any hints


Why don't you use re.findall?

re.findall(r'\b[0-9]{2,7}-[0-9]{2}-[0-9]{2}\b', txt)


I think I can see what you did there but it won't make sense to me - or
whoever looks at the code - in future.

That answers your specific question. However, I am in awe of people who
can just "do" regular expressions and I thank you very much for what
would have been a monumental effort had I tried it.

That little re.sub() came from ChatGPT and I can understand it without
too much effort because it came documented

I suppose ChatGPT is the answer to this thread. Or everything. Or 
will be.



\b  Word boundary
[0-9]{2,7}  2..7 digits
-   "-"
[0-9]{2}    2 digits
-   "-"
[0-9]{2}    2 digits
\b  Word boundary

The "word boundary" thing is to stop it matching where there are 
letters or digits right next to the digits.


For example, if the text contained, say, "123456789-12-1234", you 
wouldn't want it to match because there are more than 7 digits at the 
start and more than 2 digits at the end.



Thanks

I know I should invest some brainspace in re. Many years ago at a Perl
conferenceI did buy a coffee mug completely covered with a regex cheat
sheet. It currently holds pens and pencils on my desk. And spiders now I
look closely!

Then I took up Python and re is different.

Maybe I'll have another look ...

The patterns themselves aren't that different; Perl's just has more 
features than the re module's.

--
https://mail.python.org/mailman/listinfo/python-list


Re: Code improvement question

2023-11-17 Thread MRAB via Python-list

On 2023-11-17 09:38, jak via Python-list wrote:

Mike Dewhirst ha scritto:

On 15/11/2023 10:25 am, MRAB via Python-list wrote:

On 2023-11-14 23:14, Mike Dewhirst via Python-list wrote:

I'd like to improve the code below, which works. It feels clunky to me.

I need to clean up user-uploaded files the size of which I don't know in
advance.

After cleaning they might be as big as 1Mb but that would be super rare.
Perhaps only for testing.

I'm extracting CAS numbers and here is the pattern xx-xx-x up to
xxx-xx-x eg., 1012300-77-4

def remove_alpha(txt):

      """  r'[^0-9\- ]':

      [^...]: Match any character that is not in the specified set.

      0-9: Match any digit.

      \: Escape character.

      -: Match a hyphen.

      Space: Match a space.

      """

  cleaned_txt = re.sub(r'[^0-9\- ]', '', txt)

      bits = cleaned_txt.split()

      pieces = []

      for bit in bits:

      # minimum size of a CAS number is 7 so drop smaller clumps 
of digits


      pieces.append(bit if len(bit) > 6 else "")

      return " ".join(pieces)


Many thanks for any hints


Why don't you use re.findall?

re.findall(r'\b[0-9]{2,7}-[0-9]{2}-[0-9]{2}\b', txt)


I think I can see what you did there but it won't make sense to me - or 
whoever looks at the code - in future.


That answers your specific question. However, I am in awe of people who 
can just "do" regular expressions and I thank you very much for what 
would have been a monumental effort had I tried it.


That little re.sub() came from ChatGPT and I can understand it without 
too much effort because it came documented


I suppose ChatGPT is the answer to this thread. Or everything. Or will be.

Thanks

Mike


I respect your opinion but from the point of view of many usenet users
asking a question to chatgpt to solve your problem is truly an overkill.
The computer world overflows with people who know regex. If you had not
already had the answer with the use of 're' I would have sent you my
suggestion that as you can see it is practically identical. I am quite
sure that in this usenet the same solution came to the mind of many
people.

with open(file) as fp:
  try: ret = re.findall(r'\b\d{2,7}\-\d{2}\-\d{1}\b', fp.read())
  except: ret = []

The only difference is '\d' instead of '[0-9]' but they are equivalent.


Bare excepts are a very bad idea.
--
https://mail.python.org/mailman/listinfo/python-list


Re: How/where to store calibration values - written by program A, read by program B

2023-12-05 Thread MRAB via Python-list

On 2023-12-05 14:37, Chris Green via Python-list wrote:

Is there a neat, pythonic way to store values which are 'sometimes'
changed?

My particular case at the moment is calibration values for ADC inputs
which are set by running a calibration program and used by lots of
programs which display the values or do calculations with them.

 From the program readability point of view it would be good to have a
Python module with the values in it but using a Python program to
write/update a Python module sounds a bit odd somehow.

I could simply write the values to a file (or a database) and I
suspect that this may be the best answer but it does make retrieving
the values different from getting all other (nearly) constant values.

Are there any Python modules aimed specifically at this sort of
requirement?

Some kind of key/value store sounds like the correct solution. I 
wouldn't go as far a database - that's overkill for a few calibration 
values.


I might suggest TOML, except that Python's tomllib (Python 3.11+) is 
read-only!


Personally, I'd go for lines of:

key1: value1
key2: value2

Simple to read, simple to write.

--
https://mail.python.org/mailman/listinfo/python-list


Re: How/where to store calibration values - written by program A, read by program B

2023-12-06 Thread MRAB via Python-list

On 2023-12-06 12:23, Thomas Passin via Python-list wrote:

On 12/6/2023 6:35 AM, Barry Scott via Python-list wrote:




On 6 Dec 2023, at 09:32, Chris Green via Python-list  
wrote:

My requirement is *slightly* more complex than just key value pairs,
it has one level of hierarchy, e.g.:-

KEY1:
  a: v1
  c: v3
  d: v4
KEY2:
  a: v7
  b: v5
  d: v6

Different numbers of value pairs under each KEY.


JSON will allow you to nest dictionaries.

{
 'KEY1': {
 'a': v1
 'c': v3
 'd': v4
 }
 'KEY2': {
  'a': v7
  'b': v5
  'd': v6
 }
}

Personally I would not use .ini style these days as the format does not include 
type of the data.


Neither does JSON.  Besides, JSON is more complicated than necessary
here - in fact, your example isn't even legal JSON since lines are
missing commas.

Fun fact - for at least some, maybe most, JSON files, using eval() on
them is hugely faster than using Python's standard JSON library.  I
learned this when I wanted to ingest a large browser bookmarks JSON
file. It wouldn't matter for a much smaller file, of course.


It would be safer if you used literal_eval.
--
https://mail.python.org/mailman/listinfo/python-list


Re: How/where to store calibration values - written by program A, read by program B

2023-12-06 Thread MRAB via Python-list

On 2023-12-06 20:11, dn via Python-list wrote:

On 7/12/23 07:12, MRAB via Python-list wrote:

On 2023-12-06 12:23, Thomas Passin via Python-list wrote:

On 12/6/2023 6:35 AM, Barry Scott via Python-list wrote:



On 6 Dec 2023, at 09:32, Chris Green via Python-list 
 wrote:


My requirement is *slightly* more complex than just key value pairs,
it has one level of hierarchy, e.g.:-

    KEY1:
  a: v1
  c: v3
  d: v4
    KEY2:
  a: v7
  b: v5
  d: v6

Different numbers of value pairs under each KEY.


JSON will allow you to nest dictionaries.

{
 'KEY1': {
 'a': v1
 'c': v3
 'd': v4
 }
 'KEY2': {
  'a': v7
  'b': v5
  'd': v6
 }
}

Personally I would not use .ini style these days as the format does 
not include type of the data.


Neither does JSON.  Besides, JSON is more complicated than necessary
here - in fact, your example isn't even legal JSON since lines are
missing commas.

Fun fact - for at least some, maybe most, JSON files, using eval() on
them is hugely faster than using Python's standard JSON library.  I
learned this when I wanted to ingest a large browser bookmarks JSON
file. It wouldn't matter for a much smaller file, of course.


It would be safer if you used literal_eval.


Ah, memories of Python2...

Does this little hack still work?

What about True/False cf true/false?


Nope, nor None cf null.

If it's numbers, strings, lists and dicts, it works.

--
https://mail.python.org/mailman/listinfo/python-list


Re: How to enter multiple, similar, dictionaries?

2023-12-11 Thread MRAB via Python-list

On 2023-12-11 15:57, Chris Green via Python-list wrote:

Chris Green  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.


Or, more sensibly, make the above into a list (or maybe dictionary)
of dictionaries:-

adccfg = [
 {'abbr':'lv', 'dev':'bbb', 'input':'1', 'name':'Leisure volts'},
 {'abbr':'sv', 'dev':'bbb', 'input':'0', 'name':'Starter volts'},
 {'abbr':'la', 'dev':'bbb', 'input':'2', 'name':'Leisure Amps'},
 {'abbr':'sa', 'dev':'bbb', 'input':'3', 'name':'Starter Amps'},
 {'abbr':'bv', 'dev':'adc2', 'input':0, 'name':'BowProp Volts'}
]

This pickles nicely, I just want an easy way to enter the data!


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.


How about:

keys = ['abbr', 'dev', 'input', 'name']
adccfg = [
('lv', 'bbb', '1', 'Leisure volts'),
('sv', 'bbb', '0', 'Starter volts'),
('la', 'bbb', '2', 'Leisure Amps'),
('sa', 'bbb', '3', 'Starter Amps'),
('bv', 'adc2', '0', 'BowProp Volts'),
]
adccfg = [dict(zip(keys, row)) for row in adccfg]

or even:

keys = ['abbr', 'dev', 'input', 'name']
adccfg = '''\
lv,bbb,1,Leisure volts
sv,bbb,0,Starter volts
la,bbb,2,Leisure Amps
sa,bbb,3,Starter Amps
bv,adc2,0,BowProp Volts
'''
adccfg = [dict(zip(keys, line.split(','))) for line in adccfg.splitlines()]

--
https://mail.python.org/mailman/listinfo/python-list


Re: IDLE editor suggestion.

2023-12-12 Thread MRAB via Python-list

On 2023-12-12 08:22, Steve GS via Python-list wrote:

Maybe this already exists but
I have never seen it in any
editor that I have used.

It would be nice to have a
pull-down text box that lists
all of the searches I have
used during this session. It
would make editing a lot
easier if I could select the
previous searches rather than
having to enter it every time.

If this is inappropriate to
post this here, please tell me
where to go.
Life should be so
complicated.


EditPad has this.
--
https://mail.python.org/mailman/listinfo/python-list


Re: IDLE editor suggestion.

2023-12-12 Thread MRAB via Python-list

On 2023-12-13 01:28, Steve GS via Python-list wrote:

Does anything from the Visual Studio family of software have a pull down menu 
that lists previous searches so that I don’t have to enter them every time?

SGA

Visual Studio search box has a dropdown list that's shown when you press 
the down arrow key.



-Original Message-
From: Friedrich Romstedt 
Sent: Tuesday, December 12, 2023 12:52 PM
To: Steve GS 
Cc: python-list@python.org
Subject: Re: IDLE editor suggestion.

Hi!

Am Di., 12. Dez. 2023 um 09:28 Uhr schrieb Steve GS via Python-list
:


Maybe this already exists but
I have never seen it in any
editor that I have used.


You might want to choose Microsoft Code from its Visual Studio family of 
software, or, if you're ready for a deep dive, you might try using vim. 
Personally I am using both.

HTH,
Friedrich



--
https://mail.python.org/mailman/listinfo/python-list


Re: >>> %matplotlib inline results in SyntaxError: invalid syntax

2023-12-25 Thread MRAB via Python-list

On 2023-12-25 19:53, Alan Gauld via Python-list wrote:

On 25/12/2023 05:34, geetanajali homes via Python-list wrote:

import numpy as np 
import pandas as pd 
import random 
import matplotlib.pyplot as plt 
%matplotlib inline 

I get an error on the last line. I am running this code in Idle Python 
3.4.4 Shell... 


Python names can't start with a % (its the modulo or
string formatting operator).

I know nothing of the innards of matplotlib so I can only
suggest a closer examination of their tutorial information.


I believe it's a feature of Jupyter specifically. It won't work in IDLE.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Extract lines from file, add to new files

2024-01-11 Thread MRAB via Python-list

On 2024-01-11 18:08, Rich Shepard via Python-list wrote:

It's been several years since I've needed to write a python script so I'm
asking for advice to get me started with a brief script to separate names
and email addresses in one file into two separate files: salutation.txt and
emails.txt.

An example of the input file:

Calvin
cal...@example.com

Hobbs
ho...@some.com

Nancy
na...@herown.com

Sluggo
slu...@another.com

Having extracted salutations and addresses I'll write a bash script using
sed and mailx to associate a message file with each name and email address.

I'm unsure where to start given my lack of recent experience.


From the look of it:

1. If the line is empty, ignore it.

2. If the line contains "@", it's an email address.

3. Otherwise, it's a name.

--
https://mail.python.org/mailman/listinfo/python-list


Re: How to create a binary tree hierarchy given a list of elements as its leaves

2024-01-28 Thread MRAB via Python-list

On 2024-01-28 18:16, marc nicole via Python-list wrote:

So I am trying to build a binary tree hierarchy given numerical elements
serving for its leaves (last level of the tree to build). From the leaves I
want to randomly create a name for the higher level of the hierarchy and
assign it to the children elements. For example: if the elements inputted
are `0,1,2,3` then I would like to create firstly 4 elements (say by random
giving them a label composed of a letter and a number) then for the second
level (iteration) I assign each of 0,1 to a random name label (e.g. `b1`)
and `2,3` to another label (`b2`) then for the third level I assign a
parent label to each of `b1` and `b2` as `c1`.

An illustation of the example is the following tree:


[image: tree_exp.PNG]

This list strips images, and discussion has mostly moved to 
https://discuss.python.org.


--
https://mail.python.org/mailman/listinfo/python-list


Re: Error pd.set_option('display.width', 10000)

2024-02-03 Thread MRAB via Python-list

On 2024-02-03 23:02, gelukt gelukt via Python-list wrote:

Dear,

While running a code, I get the error below:
What does this error mean? How can I fix this error?

C:\Users\brech\Desktop\Crypto\venv\Scripts\python.exe 
"C:/Users/brech/Desktop/Crypto/Project/aaa Arbitrage.py"
Traceback (most recent call last):
   File "C:\Users\brech\Desktop\Crypto\Project\aaa Arbitrage.py", line 458, in 

 methode()
   File "C:\Users\brech\Desktop\Crypto\Project\aaa Arbitrage.py", line 49, in 
methode
 wb.sheets[website]['A' + str(1+a)].value = 
inputString[startIndex:startIndex + 3]
 
   File "C:\Users\brech\Desktop\Crypto\venv\Lib\site-packages\xlwings\main.py", 
line 2411, in value
 conversion.write(data, self, self._options)
   File 
"C:\Users\brech\Desktop\Crypto\venv\Lib\site-packages\xlwings\conversion\__init__.py",
 line 102, in write
 pipeline(ctx)
   File 
"C:\Users\brech\Desktop\Crypto\venv\Lib\site-packages\xlwings\conversion\framework.py",
 line 79, in __call__
 stage(*args, **kwargs)
   File 
"C:\Users\brech\Desktop\Crypto\venv\Lib\site-packages\xlwings\conversion\standard.py",
 line 75, in __call__
 self._write_value(ctx.range, ctx.value, scalar)
   File 
"C:\Users\brech\Desktop\Crypto\venv\Lib\site-packages\xlwings\conversion\standard.py",
 line 63, in _write_value
 rng.raw_value = value
 ^
   File "C:\Users\brech\Desktop\Crypto\venv\Lib\site-packages\xlwings\main.py", 
line 1973, in raw_value
 self.impl.raw_value = data
 ^^^
   File 
"C:\Users\brech\Desktop\Crypto\venv\Lib\site-packages\xlwings\_xlwindows.py", 
line 1209, in raw_value
 self.xl.Value = data
 ^
   File 
"C:\Users\brech\Desktop\Crypto\venv\Lib\site-packages\xlwings\_xlwindows.py", 
line 161, in __setattr__
 return setattr(self._inner, key, value)

   File 
"C:\Users\brech\Desktop\Crypto\venv\Lib\site-packages\win32com\client\__init__.py",
 line 597, in __setattr__
 self._oleobj_.Invoke(*(args + (value,) + defArgs))
pywintypes.com_error: (-2147352567, 'Er is een uitzondering opgetreden.', (0, 
None, None, None, 0, -2147024882), None)

Process finished with exit code 1


There's a question on StackOverflow that looks similar:

https://stackoverflow.com/questions/72223654/pywintypes-com-error-2147352567-exception-occured-0-none-none-none-0

Something to do with the cell format.

Check which cell it i, what value it's trying to put there, and whether 
the format of the cell and the value are compatible.

--
https://mail.python.org/mailman/listinfo/python-list


Re: test-ignore

2024-02-15 Thread MRAB via Python-list

On 2024-02-16 00:29, Skip Montanaro via Python-list wrote:


> Test post to see if my Newsgroup post program is working.

Aim your test messages at alt.test, please.



I agree that basic Usenet connectivity messages should go to alt.test. It's
not clear from the original post, but if the poster's aim was to see if
posts to comp.lang.python traverse the gateway and show up on this list,
then alt.test won't help.

True, but did the poster really need to send another one to say "yes, 
that worked"?

--
https://mail.python.org/mailman/listinfo/python-list


Re: A question about import

2024-02-16 Thread MRAB via Python-list

On 2024-02-16 20:07, Gabor Urban via Python-list wrote:

Hi guys,

I need something about modules to be clarified.

Suppose I have written a module eg: ModuleA which imports an other
module, let us say the datetime.

If I import ModuleA in a script, will be datetime imported automatically?


Yes. When a module is imported it can import other modules.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Using __new__

2024-02-17 Thread MRAB via Python-list

On 2024-02-17 22:35, Jonathan Gossage via Python-list wrote:

I am attempting to use the __new__ method in the following code:
class SingletonExample(object):

 _instance = None

 def __new__(cls, **kwargs):
 if cls._instance is None:
 cls._instance = super().__new__(cls, **kwargs)
 return cls._instance

 def __init__(self, **kwargs) -> None:
 our_attributes = ('h', 'x')
 if kwargs is not None:
 for k, v in kwargs.items():
 if k in our_attributes:
 setattr(self, k, v)

a = SingletonExample(h=1)

and I get the following result:

(PRV) jonathan@jfgdev:/PR$ python -m Library.Testing.test2
Traceback (most recent call last):
   File "", line 198, in _run_module_as_main
   File "", line 88, in _run_code
   File "/mnt/ProgrammingRenaissance/Library/Testing/test2.py", line 16, in

 a = SingletonExample(h=1)
 ^
   File "/mnt/ProgrammingRenaissance/Library/Testing/test2.py", line 6, in
__new__
 cls._instance = super().__new__(cls, **kwargs)
 ^^
TypeError: object.__new__() takes exactly one argument (the type to
instantiate)

I am quite puzzled as it looks as if this code will not work if the
super-class is 'object'. Any suggestions on how to proceed?


Don't pass kwargs to object.__new__ because it doesn't expect it.

Incidentally, kwargs will never be None, and there's no point in giving 
a return type for __init__ because it can only ever return None.

--
https://mail.python.org/mailman/listinfo/python-list


Re: Problem resizing a window and button placement

2024-02-23 Thread MRAB via Python-list

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<

import tkinter as tk

def on_configure(*args):
print(args)

root = tk.Tk()
root.bind('', on_configure)
root.mainloop()

8<

Are you placing the buttons yourself? I always use layouts and they 
handle such things automatically.


--
https://mail.python.org/mailman/listinfo/python-list


Re: Problem resizing a window and button placement

2024-02-24 Thread MRAB via Python-list

On 2024-02-25 00:33, Steve GS via Python-list wrote:

"Well, yes, in Python a
variable created inside a
function or method is local to
that function unless you
declare it global."

Yes, I knew that. I tried to
global it both before the
function call and within it.
Same for when I created the
variable. If I try to use it
in the rest of the code, it
keeps coming up as not
declared.  In other functions,
I can 'return' the variable
but that apparently would not
work for this function.

Is this type of function any
different that that which I
have been using?


Please post a short example that shows the problem.

--
https://mail.python.org/mailman/listinfo/python-list


Re: Problem resizing a window and button placement

2024-02-24 Thread MRAB via Python-list

On 2024-02-25 02:51, Steve GS wrote:

import tkinter as tk

#global Ww  Neither global helps
def on_configure(*args):
# print(args)
  #global Ww  Neither global helps
  Ww = root.winfo_width()
  print("WwInside = <" + str(Ww) + ">")

root = tk.Tk()
root.bind('', on_configure)
print("WwOutside = <" + str(Ww) + ">")
#NameError: name 'Ww' is not defined
root.mainloop()
'Ww' won't exist until 'on_configure' assigns to it, and that won't 
happen until `mainloop` starts.


Also, 'global' works only within a function.

8<

import tkinter as tk

def on_configure(event):
    print(f'{event.width=}, {event.height=}')

root = tk.Tk()
root.bind('',on_configure)
root.mainloop()

8<

--
https://mail.python.org/mailman/listinfo/python-list


Re: Problem resizing a window and button placement

2024-02-25 Thread MRAB via Python-list

On 2024-02-25 21:19, Steve GS via Python-list wrote:

SOLUTION FOUND!

The fix was to write the code that uses the width value and to place it into 
the function itself.
Kluge? Maybe but it works.

Mischief Managed.


As for the most recent suggestion, it fails for me:

Traceback (most recent call last):
   File "F:/___zInsulin Code A 08-02-23/WinPic/IOWw.pyw", line 14, in 
 print("Ww Outside = <" + str(Ww) > + ">")
TypeError: bad operand type for unary +: 'str'


It fails because there's a mistake. It should be:

print("Ww Outside = <" + str(Ww) + ">")


With the need to close the window, it adds an extra step and intervention to 
the program to use. I am not sure how this help[s.

As a curio, it would be interesting to see how to use the value of a variable, 
created in the function used here, and make it available to the code outside 
the function.


[snip]


--
https://mail.python.org/mailman/listinfo/python-list


Re: Can u help me?

2024-03-05 Thread MRAB via Python-list

On 2024-03-06 00:06, Chano Fucks via Python-list wrote:

[image: image.png]


This list removes all images.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Can u help me?

2024-03-05 Thread MRAB via Python-list

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?
--
https://mail.python.org/mailman/listinfo/python-list


Re: Can u help me?

2024-03-05 Thread MRAB via Python-list

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

--
https://mail.python.org/mailman/listinfo/python-list


Re: If a dictionary key has a Python list as its value!

2024-03-07 Thread MRAB via Python-list

On 2024-03-07 14:11, Varuna Seneviratna via Python-list wrote:

If a dictionary key has a Python list as its value, you can read the values
one by one in the list using a for-loop like in the following.

d = {k: [1,2,3]}



for v in d[k]:
 print(v)



No tutorial describes this, why?
What is the Python explanation for this behaviour?


If the value is a list, you can do list things to it.

If the value is a number, you can do number things to it.

If the value is a string, you can do string things to it.

And so on.

It's not mentioned in tutorials because it's not special. It just 
behaves how you'd expect it to behave.

--
https://mail.python.org/mailman/listinfo/python-list


Re: the name ``wheel''

2024-03-21 Thread MRAB via Python-list

On 2024-03-21 11:36, Johanne Fairchild via Python-list wrote:

Why is a whl-package called a ``wheel''?  Is it just a pronunciation for
the extension WHL or is it really a name?

Also, it seems that when I install Python on Windows, it doesn't come
with pip ready to run.  I had to say

   python -m ensurepip

and then I saw that a pip on a whl-package was installed.  Why doesn't
the official distribution make pip ready to run by default?  Thank you!


When I install Python on Windows, I always get pip by default, although 
it might not be on the system search path.


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.

--
https://mail.python.org/mailman/listinfo/python-list


Re: xkcd.com/353 ( Flying with Python )

2024-03-30 Thread MRAB via Python-list

On 2024-03-30 11:25, Skip Montanaro via Python-list wrote:


> https://xkcd.com/1306/
>   what does  SIGIL   mean?

I think its' a Perl term, referring to the $/@/# symbols in front of
identifiers.



I had a vague recollection of hearing it elsewhere (*Game of Thrones,* on
the armies' battle flags?), but didn't know what it meant. Google tells me:

*an inscribed or painted symbol considered to have magical power.*

So, they're more than just line noise. They confer power on their users...

Perhaps '@' in the context of decorators is the most prominent example in
Python, since decorators technically don't allow the programmer to do
something they couldn't before, but are now are used everywhere, a key
feature of many applications and modules.

Magical-ly, y'rs,


I wouldn't consider '@' to be a sigil any more than I would a unary minus.
In Perl there's the prefixes $ (scalar), @ (array) and % 
(hash/dictionary), but also & (function), although it's rare because 
there's also the () afterwards.


Variables in PHP have the prefix $ and only $.

In old versions of BASIC, string variables had the suffix $, and integer 
variables the suffix %. Some versions also had the suffix # (for double 
precision, I think).

--
https://mail.python.org/mailman/listinfo/python-list


Re: Can you help me with this memoization simple example?

2024-03-30 Thread MRAB via Python-list

On 2024-03-31 00:09, marc nicole via Python-list wrote:

I am creating a memoization example with a function that adds up / averages
the elements of an array and compares it with the cached ones to retrieve
them in case they are already stored.

In addition, I want to store only if the result of the function differs
considerably (passes a threshold e.g. 50 below).

I created an example using a decorator to do so, the results using the
decorator is slightly faster than without the memoization which is OK, but
is the logic of the decorator correct ? anybody can tell me ?

My code is attached below:



import time


def memoize(f):
 cache = {}

 def g(*args):
 if args[1] == "avg":
 sum_key_arr = sum(list(args[0])) / len(list(args[0]))


'list' will iterate over args[0] to make a list, and 'sum' will iterate 
over that list.


It would be simpler to just let 'sum' iterate over args[0].


 elif args[1] == "sum":
 sum_key_arr = sum(list(args[0]))
 if sum_key_arr not in cache:
 for (
 key,
 value,
 ) in (
 cache.items()
 ):  # key in dict cannot be an array so I use the sum of the
array as the key


You can't use a list as a key, but you can use a tuple as a key, 
provided that the elements of the tuple are also immutable.



 if (
 abs(sum_key_arr - key) <= 50
 ):  # threshold is great here so that all values are
approximated!
 # print('approximated')
 return cache[key]
 else:
 # print('not approximated')
 cache[sum_key_arr] = f(args[0], args[1])
 return cache[sum_key_arr]

 return g


@memoize
def aggregate(dict_list_arr, operation):
 if operation == "avg":
 return sum(list(dict_list_arr)) / len(list(dict_list_arr))
 if operation == "sum":
 return sum(list(dict_list_arr))
 return None


t = time.time()
for i in range(200, 15000):
 res = aggregate(list(range(i)), "avg")

elapsed = time.time() - t
print(res)
print(elapsed)



--
https://mail.python.org/mailman/listinfo/python-list


Re: Can you help me with this memoization simple example?

2024-03-31 Thread MRAB via Python-list

On 2024-03-31 09:04, marc nicole wrote:

Thanks for the first comment which I incorporated

but when you say "You can't use a list as a key, but you can use a 
tuple as a key,

provided that the elements of the tuple are also immutable."

does it mean  the result of sum of the array is not convenient to use 
as key as I do?
Which tuple I should use to refer to the underlying list value as you 
suggest?



I was suggesting using `tuple` on the argument:

def memoize(f):
 cache = {}

 def g(*args):
 key = tuple(args[0]), args[1]

 if key not in cache:
 cache[key] = f(args[0], args[1])

 return cache[key]

 return g


Anything else is good in my code ?

Thanks

Le dim. 31 mars 2024 à 01:44, MRAB via Python-list 
 a écrit :


On 2024-03-31 00:09, marc nicole via Python-list wrote:
> I am creating a memoization example with a function that adds up
/ averages
> the elements of an array and compares it with the cached ones to
retrieve
> them in case they are already stored.
>
> In addition, I want to store only if the result of the function
differs
> considerably (passes a threshold e.g. 50 below).
>
> I created an example using a decorator to do so, the results
using the
> decorator is slightly faster than without the memoization which
is OK, but
> is the logic of the decorator correct ? anybody can tell me ?
>
> My code is attached below:
>
>
>
> import time
>
>
> def memoize(f):
>      cache = {}
>
>      def g(*args):
>          if args[1] == "avg":
>              sum_key_arr = sum(list(args[0])) / len(list(args[0]))

'list' will iterate over args[0] to make a list, and 'sum' will
iterate
over that list.

It would be simpler to just let 'sum' iterate over args[0].

>          elif args[1] == "sum":
>              sum_key_arr = sum(list(args[0]))
>          if sum_key_arr not in cache:
>              for (
>                  key,
>                  value,
>              ) in (
>                  cache.items()
>              ):  # key in dict cannot be an array so I use the
sum of the
> array as the key

You can't use a list as a key, but you can use a tuple as a key,
provided that the elements of the tuple are also immutable.

>                  if (
>                      abs(sum_key_arr - key) <= 50
>                  ):  # threshold is great here so that all
values are
> approximated!
>                      # print('approximated')
>                      return cache[key]
>              else:
>                  # print('not approximated')
>                  cache[sum_key_arr] = f(args[0], args[1])
>          return cache[sum_key_arr]
>
>      return g
>
>
> @memoize
> def aggregate(dict_list_arr, operation):
>      if operation == "avg":
>          return sum(list(dict_list_arr)) / len(list(dict_list_arr))
>      if operation == "sum":
>          return sum(list(dict_list_arr))
>      return None
>
>
> t = time.time()
> for i in range(200, 15000):
>      res = aggregate(list(range(i)), "avg")
>
> elapsed = time.time() - t
> print(res)
> print(elapsed)


-- 
https://mail.python.org/mailman/listinfo/python-list



--
https://mail.python.org/mailman/listinfo/python-list


Re: Running issues

2024-04-05 Thread MRAB via Python-list

On 2024-04-05 22:32, shannon makasale via Python-list wrote:

Hi there,
My name is Shannon. I installed Python 3.12 on my laptop a couple months ago, 
but realised my school requires me to use 3.11.1.

I uninstalled 3.12 and installed 3.11.1.

Unfortunately, I am unable to run python now. It keeps asking to be modified, 
repaired or uninstalled.

Do you have any suggestions on how to fix this?

Any help you can offer is greatly appreciated. Thank you for your time.


Hope to hear from you soon.


That’s the installer. All it does is install the software.

There isn’t an IDE as such, although there is IDLE, which you should be 
able to find on the Start Menu under Python (assuming you’re using Windows).


There are a number of 3rd-party editors available that you can use when 
working with Python, or you can use Visual Studio Code from Microsoft.


--
https://mail.python.org/mailman/listinfo/python-list


Re: Version of NymPy

2024-05-15 Thread MRAB via Python-list

On 2024-05-15 19:42, Popov, Dmitry Yu via Python-list wrote:

What would be the easiest way to learn which version of NumPy I have with my 
Anaconda distribution?


Import numpy and print its '__version__' attribute.

--
https://mail.python.org/mailman/listinfo/python-list


Re: Terminal Emulator (Posting On Python-List Prohibited)

2024-05-19 Thread MRAB via Python-list

On 2024-05-19 19:13, 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?


[snip]
From https://pip.pypa.io/en/stable/:

"pip is the package installer for Python."

It's an acronym.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Flubbed it in the second interation through the string: range error... HOW?

2024-05-29 Thread MRAB via Python-list

On 2024-05-29 05:33, Kevin M. Wilson via Python-list wrote:

The following is my effort to understand how to process a string, letter, by 
letter:
def myfunc(name):        index = 0    howmax = len(name)    # while (index <= 
howmax):    while (index < howmax):        if (index % 2 == 0):            
print('letter to upper = {}, index {}!'.format(name[index], index))            name = 
name[index].upper()            print('if block {} and index {}'.format(name[index], 
index))        elif (index % 2 > 0):            print(index)            print('Start: 
elseif block, index is {}, letter is {}'.format(index, name))            # print('letter 
to lower = {}'.format(name[index]))            # print('Already lowercase do noting: 
name = {}'.format(name[index]))        index += 1        # index = name.upper()
     return name
myfunc('capitalism')
Error message:                        Not making sense, index is 1, letter s/b 
'a'letter to upper = c, index 0!
if block C and index 0
1
Start: elseif block, index is 1, letter is C
---
IndexErrorTraceback (most recent call last)
Cell In[27], line 21
  17 # index = name.upper()
  19 return name
---> 21 myfunc('capitalism')

Cell In[27], line 8, in myfunc(name)
   6 while (index < howmax):
   7 if (index % 2 == 0):
> 8 print('letter to upper = {}, index {}!'.format(name[index], 
index))
   9 name = name[index].upper()
  10 print('if block {} and index {}'.format(name[index], index))

IndexError: string index out of 
range***
So, I'm doing something... Stupid!!
***
"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


I think the code is this:

def myfunc(name):
index = 0
howmax = len(name)
# while (index <= howmax):
while (index < howmax):
if (index % 2 == 0):
print('letter to upper = {}, index {}!'.format(name[index], 
index))

name = name[index].upper()
print('if block {} and index {}'.format(name[index], index))
elif (index % 2 > 0):
print(index)
print('Start: elseif block, index is {}, letter is 
{}'.format(index, name))

# print('letter to lower = {}'.format(name[index]))
# print('Already lowercase do noting: name = 
{}'.format(name[index]))

index += 1
# index = name.upper()
return name

myfunc('capitalism')


What is:

name = name[index].upper()

meant to be doing?

What it's _actually_ doing is getting the character at a given index, 
converting it to uppercase, and then assigning it to `name`, so `name` 
is now 1 character long.


It doesn't this when 'index' is 0, so after the first iteration, `name` 
is a single-character string.


On the second iteration it raises IndexError because the string is only 
1 character long and you're asking for `name[1]`.


--
https://mail.python.org/mailman/listinfo/python-list


Re: Flubbed it in the second interation through the string: range error... HOW?

2024-05-29 Thread MRAB via Python-list

On 2024-05-29 15:32, Thomas Passin via Python-list wrote:

On 5/29/2024 8:55 AM, Kevin M. Wilson wrote:
Please recall, I said the format for the email failed to retain the 
proper indents.

I'll attach a picture of the code!
Purpose; to uppercase every other letter in a string.

Thanks all, KMW


Simpler is good, and readability is good.  For a simple conversion that
has a little touch of generality:

s1 = 'this is a test'
def convert(i, ch):
  return ch.upper() if i % 2 else ch

result = ''.join([convert(i, ch) for i, ch in enumerate(s1)])
print(result)  # tHiS Is a tEsT


[snip]
Small mistake there. The original code converted to uppercase on even 
indexes, whereas your code does it on odd ones.



However, this has a weakness: what to do about spaces.  Should they be
counted among the characters to be uppercased? or should they not be
included in the count of the alternation?  If you want to uppercase
every other letter that is not a space, things become a little more
complicated.  And then do you want this to apply to all whitespace or
only spaces?

If you want to skip changing spaces, then you need to track the state of
converted characters in some way.  It would probably be easier (and more
readable) to use a "for x in t:" construction:

def convert(convert_this, ch):
  """Convert character ch if convert_this is True.
  Don't convert spaces.
  """
  if convert_this:
  if ch == ' ':
  return (convert_this, ch)
  elif convert_this:
  return (False, ch.upper())
  return (True, ch)

convert_next = False
result = ''
for ch in s1:
  convert_next, ch = convert(convert_next, ch)
  result += ch
print(result)  # tHiS Is A TeSt

There could be even more complications if you allow non-ascii characters
but you were asking about processing character by character so I won't
get into that.

(You haven't specified the problem in enough detail to answer questions
like those).


[snip]


--
https://mail.python.org/mailman/listinfo/python-list


Re: in Python? -- Chunk -- (ChunkC '(a a b b b)), ==> ((a 2) (b 3))

2024-06-09 Thread MRAB via Python-list

On 2024-06-09 22:20, HenHanna via Python-list wrote:


Chunk, ChunkC -- nice simple way(s) to write these in Python?


(Chunk  '(a a   ba a a   b b))
  ==> ((a a) (b)  (a a a) (b b))


(Chunk  '(a a a a   b   c c   a a   d   e e e e))
  ==> ((a a a a) (b) (c c) (a a) (d) (e e e e))


(Chunk  '(2 2   foo   bar bar   j j j   k   baz baz))
  ==> ((2 2) (foo) (bar bar) (j j j) (k) (baz baz))

_

(ChunkC  '(a a   b b b))
   ==> ((a 2)  (b 3))

(ChunkC  '(a a   b  a a a   b b))
   ==> ((a 2)  (b 1)  (a 3)   (b 2))


You can make use of itertools.groupby.

--
https://mail.python.org/mailman/listinfo/python-list


Re: Couldn't install numpy on Python 2.7

2024-06-12 Thread MRAB via Python-list

On 2024-06-12 17:31, AVI GROSS via Python-list wrote:

I am sure there is inertia to move from an older product and some people
need a reason like this where the old becomes untenable.

It seems Microsoft is having a problem where something lik 2/3 of Windows
users have not upgraded from Windows 10 after many years and have set a
deadline in a year or so for stopping updates. In that case, hardware was a
concern for some as Windows 11 did not work on their machines. With
upgrading python, the main concern is having to get someone to examine old
code and try to make it compatible.

In the case of Windows, my PC is over 10 years old yet performs 
perfectly well for my needs. It can't run Windows 11. Therefore, I'm in 
the process of migrating to Linux, and I still have over a year to 
achieve that before support ends.



But anyone doing new code in Python 2 in recent years should ...


Indeed...


-Original Message-
From: Python-list  On
Behalf Of Gordinator via Python-list
Sent: Wednesday, June 12, 2024 10:19 AM
To: python-list@python.org
Subject: Re: Couldn't install numpy on Python 2.7

On 12/06/2024 12:30, marc nicole wrote:

I am trying to install numpy library on Python 2.7.15 in PyCharm but the
error message I get is:

ERROR: Could not find a version that satisfies the requirement numpy (from

versions: none)
ERROR: No matching distribution found for numpy
c:\python27\lib\site-packages\pip\_vendor\urllib3\util\ssl_.py:164:
InsecurePlatformWarning: A true SSLContext object is not available. This
prevents urllib3 fro
m configuring SSL appropriately and may cause certain SSL connections to
fail. You can upgrade to a newer version of Python to solve this. For

more

information, see
https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
   InsecurePlatformWarning,



Any clues?


Why are you using Python 2? Come on, it's been 16 years. Ya gotta move
on at some point.


--
https://mail.python.org/mailman/listinfo/python-list


Re: win32clipboard writing to clipboard on Windows 11

2024-06-17 Thread MRAB via Python-list

On 2024-06-17 20:27, Rob Cliffe via Python-list wrote:

Recently I acquired a new laptop running WIndows 11; my previous one
uses WIndows 10.  I encountered a strange problem:
I am using the win32clipboard backage (part of pywin32), and when I use
SetClipboardData() to write text which consists ***entirely of digits***
to the clipboard, I either get an error (not always the same error
message) or a program crash.  The problem does not appear if I use
SetClipboardText() instead.  The problem does not occur on my old
machine (where I used the feature extensively).

Sample program:

from win32clipboard import *
OpenClipboard()
SetClipboardData(CF_UNICODETEXT, "A")
SetClipboardData(CF_UNICODETEXT, "A0")
SetClipboardData(CF_UNICODETEXT, "0A")
SetClipboardText("0", CF_UNICODETEXT)
print("OK so far")
SetClipboardData(CF_UNICODETEXT, "0")
CloseClipboard()

Sample output:

OK so far
Traceback (most recent call last):
    File "C:\TEST*.PY", line 8, in 
      SetClipboardData(CF_UNICODETEXT, "0")
pywintypes.error: (0, 'SetClipboardData', 'No error message is available')

Can anyone shed light on this?
Best wishes
Rob Cliffe


I tried it on Windows 10 and got this:

>>> from win32clipboard import *
>>> OpenClipboard()
>>> SetClipboardData(CF_UNICODETEXT, "A")
1830508101640
>>> CloseClipboard()
>>> OpenClipboard()
>>> SetClipboardData(CF_UNICODETEXT, "0")
Traceback (most recent call last):
  File "", line 1, in 
pywintypes.error: (6, 'SetClipboardData', 'The handle is invalid.')
>>> CloseClipboard()

It looks like it's something to memory ownership:

https://stackoverflow.com/questions/1264137/how-to-copy-string-to-clipboard-in-c

If you're putting text on the clipboard, why not just use 
SetClipboardText()? That's what I do.

--
https://mail.python.org/mailman/listinfo/python-list


Re: Timezone in HH:MM Format

2024-06-18 Thread MRAB via Python-list

On 2024-06-19 00:32, Ivan "Rambius" Ivanov via Python-list wrote:

Hello,

How can I convert a date, usually datetime.now(), into a format where
the timezone is in hours:minutes format. I was able to get that format
in shell:

$ date +%Y-%m-%dT%H:%M:%S%:z
2024-06-18T19:24:09-04:00

The closest I got in python is

from datetime import datetime
from zoneinfo import ZoneInfo

s = datetime.strftime(datetime.now(ZoneInfo("America/New_York")),
"%Y-%m-%dT%H:%M:%S%z")
print(s)

This prints the same as the shell command above except the last column:
2024-06-18T19:28:56-0400

Starting from Python 3.12, you can use "%:z" in the format string. For 
earlier versions of Python, you need to do some string slicing.

--
https://mail.python.org/mailman/listinfo/python-list


Re: Decoding bytes to text strings in Python 2

2024-06-23 Thread MRAB via Python-list

On 2024-06-24 00:30, Chris Angelico via Python-list wrote:

On Mon, 24 Jun 2024 at 08:20, Rayner Lucas via Python-list
 wrote:


In article ,
ros...@gmail.com says...
>
> If you switch to a Linux system, it should work correctly, and you'll
> be able to migrate the rest of the way onto Python 3. Once you achieve
> that, you'll be able to operate on Windows or Linux equivalently,
> since Python 3 solved this problem. At least, I *think* it will; my
> current system has a Python 2 installed, but doesn't have tkinter
> (because I never bothered to install it), and it's no longer available
> from the upstream Debian repos, so I only tested it in the console.
> But the decoding certainly worked.

Thank you for the idea of trying it on a Linux system. I did so, and my
example code generated the error:

_tkinter.TclError: character U+1f40d is above the range (U+-U+)
allowed by Tcl

So it looks like the problem is ultimately due to a limitation of
Tcl/Tk.

Yep, that seems to be the case. Not sure if that's still true on a
more recent Python, but it does look like you won't get astral
characters in tkinter on the one you're using.


[snip]
Tkinter in recent versions of Python can handle astral characters, at 
least back to Python 3.8, the oldest I have on my Windows PC.

--
https://mail.python.org/mailman/listinfo/python-list


Re: Best (simplest) way to share data between processes

2024-07-07 Thread MRAB via Python-list

On 2024-07-07 23:27, Barry via Python-list wrote:




On 7 Jul 2024, at 22:13, Chris Green via Python-list  
wrote:

a simple file lock can then
be used to prevent simultaneous access (well, simultaneous access when
the writing process is writing).


There is a simple pattern to make this robust.

Write new values to a tmp file.
Close the tmp file.
Then use os.rename(tmpfile, productionfile).

This is guaranteed that any process that reads the file will only see all the 
old file contents or all the new file contents,  never a mix of both.

For clarity I'd recommend os.replace instead. This is because on Windows 
os.rename it would complain if the target file already exists, but 
os.replace has the same behaviour on both Linux and Windows.

--
https://mail.python.org/mailman/listinfo/python-list


Re: Issue with pip Installation on My Laptop

2024-07-27 Thread MRAB via Python-list

On 2024-07-27 21:58, Mats Wichmann via Python-list wrote:

On 7/26/24 16:28, Thomas Passin via Python-list wrote:

On 7/26/2024 7:25 AM, Lizna Shah via Python-list wrote:
OSError: [WinError 225] Operation did not complete successfully 
because the

file contains a virus or potentially unwanted software


That part of the error message tells you the story.  Windows thinks some 
file in the install has been corrupted with malware.





The Windows installer comes with pip, there's no need to do an extra
install to get it:

python -m pip --version


On Windows it's recommended that you use the Python Launcher 'py':

py -m pip --version


If you can't find the pip *command*, that's a problem with yout PATH
settings.  The Python installer offers to add the location of Python
itself to PATH, and you've apparently taken it up on that offer, but
that's not the same directory that pip goes to.  Just use it as a module
and you should be fine.


===

The typical paths will be something like

C:\Users\you\AppData\Local\Programs\Python\Python310   # python executable
C:\Users\you\AppData\Local\Programs\Python\Python310\Scripts   # pip
"executable"


--
https://mail.python.org/mailman/listinfo/python-list


Re: new here

2024-08-20 Thread MRAB via Python-list

On 2024-08-20 23:26, Daniel via Python-list wrote:

Hi folks -

New here. I've perused some posts and haven't seen a posting FAQ for
this NG. I'm learning python right now to realize some hobby goals I
have regarding some smolnet services. What are the NG standards on
pasting code in messages? Do yall prefer I post a pastebin link if it's
over a certain number of lines? I know this isn't IRC - just asking.


You'll find it rather quiet here because most activity has moved to here:

https://discuss.python.org/
--
https://mail.python.org/mailman/listinfo/python-list


Re: Is there a better way? [combining f-string, thousands separator, right align]

2024-08-25 Thread MRAB via Python-list

On 2024-08-25 16:12, Gilmeh Serda via Python-list wrote:

Subject explains it, or ask.

This is a bloody mess:


s = "123456789" # arrives as str
f"{f'{int(s):,}': >20}"

' 123,456,789'


You don't need to format twice; you can combine them:

>>> s = "123456789"
>>> f'{int(s): >20,}'
' 123,456,789'

or if you rely on default behaviour:

>>> f'{int(s):20,}'
' 123,456,789'

--
https://mail.python.org/mailman/listinfo/python-list


Re: new here

2024-08-25 Thread MRAB via Python-list

On 2024-08-26 02:29, AVI GROSS via Python-list wrote:

If everyone will pardon my curiosity, who and what purposes are these
smaller environments for and do many people use them?

I mean the price of a typical minimal laptop is not a big deal today. So are
these for some sort of embedded uses?

I read about them ages ago but wonder ...

A Raspberry Pi Pico W costs less than £5, is a lot smaller, and has a 
much lower power consumption than a laptop, so if it's good enough for 
the purpose (embedded controller), why use a laptop? That's overkill!


-Original Message-
From: Python-list  On
Behalf Of rbowman via Python-list
Sent: Friday, August 23, 2024 1:22 AM
To: python-list@python.org
Subject: Re: new here

On Fri, 23 Aug 2024 16:23:42 +1200, dn wrote:


Adding a display to the Pico-W is my next project... After that, gyros
(am thinking it may not go so well, on balance... hah!).


https://toptechboy.com/two-axis-tilt-meter-displaying-pitch-and-roll-
using-an-mpu6050-on-the-raspberry-pi-pico-w/

You might have to go back a lesson or two for the lead up. As he generally
says in the intro most of what he uses is from the Sunfounder Kepler kit.
It has a standard LCD display but he suggested buying the OLED separately
and used it for Lissajous patterns and other fancier stuff.

It's not a bad series although he can be long-winded and his Python style
definitely isn't PEP8 friendly.

https://toptechboy.com/

He switched to the Arduino Uno R4 after the IR controller/NeoPixel Pico
project and I don't know if he intends to go back to the Pico. He uses
Thonny but I use the MicroPython extension in VS Code. Lately I've been
using Code for everything. Mostly I work on Linux boxes but it's all the
same on Windows. There is a PlatformIO extension that works with Arduino
and other boards. PyLance upsets some because it's a MS product but it
works well too.  I've used PyCharm and like it but I also work on C, .NET,
Angular, and other projects and Code gives me a uniform IDE.


--
https://mail.python.org/mailman/listinfo/python-list


Re: Formatting a str as a number - Okay, one more related thing...

2024-08-31 Thread MRAB via Python-list

On 2024-08-31 06:31, Gilmeh Serda via Python-list wrote:

On Fri, 30 Aug 2024 05:22:17 GMT, Gilmeh Serda wrote:


f"{int(number):>20,}"


I can find "," (comma) and I can find "_" (underscore) but how about " "
(space)?

Or any other character, for that matter?

Any ideas?

Of course I can do f"{123456:>20_}".replace("_", " "), just thought there
might be something else my search mojo fails on.


The format is described here:

https://docs.python.org/3/library/string.html#formatspec

A space is counted as a fill character.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Correct syntax for pathological re.search()

2024-10-08 Thread MRAB via Python-list

On 2024-10-08 21:59, Alan Bawden via Python-list wrote:

Karsten Hilbert  writes:

Python 3.11.2 (main, Aug 26 2024, 07:20:54) [GCC 12.2.0] on linux
Type "help", "copyright", "credits" or "license" for more 
information.
>>> tex = '\sout{'
>>> tex
'\\sout{'
>>>

Am I missing something ?

You're missing the warning it generates:

 > python -E -Wonce
 Python 3.11.2 (main, Aug 26 2024, 07:20:54) [GCC 12.2.0] on linux
 Type "help", "copyright", "credits" or "license" for more information.
 >>> tex = '\sout{'
 :1: DeprecationWarning: invalid escape sequence '\s'
 >>>


You got lucky that \s in invalid. If it had been \t you would've got a 
tab character.


Historically, Python treated invalid escape sequences as literals, but 
it's deprecated now and will become an outright error in the future 
(probably) because it often hides a mistake, such as the aforementioned 
\t being treated as a tab character when the user expected it to be a 
literal backslash followed by letter t. (This can occur within Windows 
file paths written in plain string literals.)

--
https://mail.python.org/mailman/listinfo/python-list


Re: Correct syntax for pathological re.search()

2024-10-11 Thread MRAB via Python-list

On 2024-10-11 22:13, AVI GROSS via Python-list wrote:

Is there some utility function out there that can be called to show what the
regular expression you typed in will look like by the time it is ready to be
used?

Obviously, life is not that simple as it can go through multiple layers with
each dealing with a layer of backslashes.

But for simple cases, ...


Yes. It's called 'print'. :-)



-Original Message-
From: Python-list  On
Behalf Of Gilmeh Serda via Python-list
Sent: Friday, October 11, 2024 10:44 AM
To: python-list@python.org
Subject: Re: Correct syntax for pathological re.search()

On Mon, 7 Oct 2024 08:35:32 -0500, Michael F. Stemper wrote:


I'm trying to discard lines that include the string "\sout{" (which is
TeX, for those who are curious. I have tried:
   if not re.search("\sout{", line): if not re.search("\sout\{", line):
   if not re.search("\\sout{", line): if not re.search("\\sout\{",
   line):

But the lines with that string keep coming through. What is the right
syntax to properly escape the backslash and the left curly bracket?


$ python
Python 3.12.6 (main, Sep  8 2024, 13:18:56) [GCC 14.2.1 20240805] on linux
Type "help", "copyright", "credits" or "license" for more information.

import re
s = r"testing \sout{WHADDEVVA}"
re.search(r"\\sout{", s)



You want a literal backslash, hence, you need to escape everything.

It is not enough to escape the "\s" as "\\s", because that only takes care
of Python's demands for escaping "\". You also need to escape the "\" for
the RegEx as well, or it will read it like it means "\s", which is the
RegEx for a space character and therefore your search doesn't match,
because it reads it like you want to search for " out{".

Therefore, you need to escape it either as per my example, or by using
four "\" and no "r" in front of the first quote, which also works:


re.search("sout{", s)



You don't need to escape the curly braces. We call them "seagull wings"
where I live.



--
https://mail.python.org/mailman/listinfo/python-list


Re: Correct syntax for pathological re.search()

2024-10-08 Thread MRAB via Python-list

On 2024-10-08 19:30, Karsten Hilbert via Python-list wrote:

Am Mon, Oct 07, 2024 at 08:35:32AM -0500 schrieb Michael F. Stemper via 
Python-list:


I'm trying to discard lines that include the string "\sout{" (which is TeX, for
those who are curious. I have tried:
  if not re.search("\sout{", line):
  if not re.search("\sout\{", line):
  if not re.search("\\sout{", line):
  if not re.search("\\sout\{", line):


unwanted_tex = '\sout{'
if unwanted_tex not in line: do_something_with_libreoffice()


That should be:

unwanted_tex = r'\sout{'

or:

unwanted_tex = '\\sout{'

--
https://mail.python.org/mailman/listinfo/python-list


Re: Correct syntax for pathological re.search()

2024-10-08 Thread MRAB via Python-list

On 2024-10-07 14:35, Michael F. Stemper via Python-list wrote:

I'm trying to discard lines that include the string "\sout{" (which is TeX, for
those who are curious. I have tried:
if not re.search("\sout{", line):
if not re.search("\sout\{", line):
if not re.search("\\sout{", line):
if not re.search("\\sout\{", line):

But the lines with that string keep coming through. What is the right syntax to
properly escape the backslash and the left curly bracket?

String literals use backslash is an escape character, so it needs to be 
escaped, or you need to use a "raw" string.


However, regex also uses backslash as an escape character.

That means that a literal backslash in a regex that's in a plain string 
literal needs to be doubly-escaped, once for the string literal and 
again for the regex.

--
https://mail.python.org/mailman/listinfo/python-list


Re: shutil.rmtree() fails when used in Fedora (rpm) "mock" environment

2024-10-24 Thread MRAB via Python-list

On 2024-10-24 20:21, Left Right wrote:

> > > The stack is created on line 760 with os.lstat and entries are appended
> > > on lines 677 (os.rmdir), 679 (os.close) and 689 (os.lstat).
> > >
> > > 'func' is popped off the stack on line 651 and check in the following 
lines.
> > >
> > > I can't see anywhere else where something else is put onto the stack or
> > > an entry is replaced.

But the _rmtree_safe_fd() compares func to a *dynamically* resolved
reference: os.lstat. If the reference to os changed (or os object was
modified to have new reference at lstat) between the time os.lstat was
added to the stack and the time of comparison, then comparison
would've failed.  To illustrate my idea:

os.lstat = lambda x: x # thread 1
stack.append((os.lstat, ...)) # thread 1
os.lstat = lambda x: x # thread 2
func, *_ = stack.pop() # thread 1
assert func is os.lstat # thread 1 (failure!)

The only question is: is it possible to modify os.lstat like that, and
if so, how?

Other alternatives include a malfunctioning "is" operator,
malfunctioning module cache... all those are a lot less likely.
What is the probability of replacing os.lstat, os.close or os.rmdir from 
another thread at just the right time?

--
https://mail.python.org/mailman/listinfo/python-list


Re: shutil.rmtree() fails when used in Fedora (rpm) "mock" environment

2024-10-24 Thread MRAB via Python-list

On 2024-10-24 17:30, Left Right wrote:

> The stack is created on line 760 with os.lstat and entries are appended
> on lines 677 (os.rmdir), 679 (os.close) and 689 (os.lstat).
>
> 'func' is popped off the stack on line 651 and check in the following lines.
>
> I can't see anywhere else where something else is put onto the stack or
> an entry is replaced.

But how do you know this code isn't executed from different threads?
What I anticipate to be the problem is that the "os" module is
imported twice, and there are two references to "os.lstat".  Normally,
this wouldn't cause a problem, because they are the same function that
doesn't have any state, but once you are trying to compare them, the
identity test will fail, because those functions were loaded multiple
times into different memory locations.

I don't know of any specific mechanism for forcing the interpreter to
import the same module multiple times, but if that was possible (which
in principle it is), then it would explain the behavior.
The stack is a local variable and os.lstat, etc, are pushed and popped 
in one function and then another that it calls, so they're in the same 
thread.

--
https://mail.python.org/mailman/listinfo/python-list


Re: shutil.rmtree() fails when used in Fedora (rpm) "mock" environment

2024-10-24 Thread MRAB via Python-list

On 2024-10-24 16:17, Left Right via Python-list wrote:

 From reading the code where the exception is coming from, this is how
I interpret the intention of the author: they build a list (not sure
why they used list, when there's a stack datastructure in Python)
which they use as a stack, where the elements of the stack are
4-tuples, the important part about these tuples is that the first
element is the operation to be performed by rmtree() has to be one of
the known filesystem-related functions. The code raising the exception
checks that it's one of those kinds and if it isn't, crashes.

There is, however, a problem with testing equality (more strictly,
identity in this case) between functions.  I.e. it's possible that a
function isn't identical to itself is, eg. "os" module was somehow
loaded twice.  I'm not sure if that's a real possibility with how
Python works... but maybe in some cases, like, multithreaded
environments it could happen...

To investigate this, I'd edit the file with the assertion and make it
print the actual value found in os.lstat and func.  My guess is that
they are both somehow "lstat", but with different memory addresses.

The stack is created on line 760 with os.lstat and entries are appended 
on lines 677 (os.rmdir), 679 (os.close) and 689 (os.lstat).


'func' is popped off the stack on line 651 and check in the following lines.

I can't see anywhere else where something else is put onto the stack or 
an entry is replaced.



On Thu, Oct 24, 2024 at 4:06 PM Christian Buhtz via Python-list
 wrote:


Hello,
I am upstream maintainer of "Back In Time" [1] investigating an issue a
distro maintainer from Fedora reported [2] to me.

On one hand Fedora seems to use a tool called "mock" to build packages
in a chroot environment.
On the other hand the test suite of "Back In Time" does read and write
to the real file system.
One test fails because a temporary directory is cleaned up using
shutil.rmtree(). Please see the output below.

I am not familiar with Fedora and "mock". So I am not able to reproduce
this on my own.
It seems the Fedora maintainer also has no clue how to solve it or why
it happens.

Can you please have a look (especially at the line "assert func is
os.lstat").
Maybe you have an idea what is the intention behind this error raised by
an "assert" statement inside "shutil.rmtree()".

Thanks in advance,
Christian Buhtz

[1] -- 
[2] -- 

__ General.test_ctor_defaults
__
self = 
 def test_ctor_defaults(self):
 """Default values in constructor."""
>   with TemporaryDirectory(prefix='bit.') as temp_name:
test/test_uniquenessset.py:47:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
_ _ _ _
/usr/lib64/python3.13/tempfile.py:946: in __exit__
 self.cleanup()
/usr/lib64/python3.13/tempfile.py:950: in cleanup
 self._rmtree(self.name, ignore_errors=self._ignore_cleanup_errors)
/usr/lib64/python3.13/tempfile.py:930: in _rmtree
 _shutil.rmtree(name, onexc=onexc)
/usr/lib64/python3.13/shutil.py:763: in rmtree
 _rmtree_safe_fd(stack, onexc)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
_ _ _ _
stack = []
onexc = .onexc at
0xb39bc860>
 def _rmtree_safe_fd(stack, onexc):
 # Each stack item has four elements:
 # * func: The first operation to perform: os.lstat, os.close or
os.rmdir.
 #   Walking a directory starts with an os.lstat() to detect
symlinks; in
 #   this case, func is updated before subsequent operations and
passed to
 #   onexc() if an error occurs.
 # * dirfd: Open file descriptor, or None if we're processing the
top-level
 #   directory given to rmtree() and the user didn't supply
dir_fd.
 # * path: Path of file to operate upon. This is passed to
onexc() if an
 #   error occurs.
 # * orig_entry: os.DirEntry, or None if we're processing the
top-level
 #   directory given to rmtree(). We used the cached stat() of
the entry to
 #   save a call to os.lstat() when walking subdirectories.
 func, dirfd, path, orig_entry = stack.pop()
 name = path if orig_entry is None else orig_entry.name
 try:
 if func is os.close:
 os.close(dirfd)
 return
 if func is os.rmdir:
 os.rmdir(name, dir_fd=dirfd)
 return

 # Note: To guard against symlink races, we use the standard
 # lstat()/open()/fstat() trick.
>   assert func is os.lstat
E   AssertionError
/usr/lib64/python3.13/shutil.py:663: AssertionError

--
https://mail.python.org/mailman/listinfo/python-list


--
https://mail.python.org/mailman/listinfo/python-list


Re: Using 'with open(...) as ...' together with configparser.ConfigParser.read

2024-10-29 Thread MRAB via Python-list

On 2024-10-29 13:56, Loris Bennett via Python-list wrote:

Hi,

With Python 3.9.18, if I do

 try:
 with open(args.config_file, 'r') as config_file:
 config = configparser.ConfigParser()
 config.read(config_file)
 print(config.sections())

i.e try to read the configuration with the variable defined via 'with
... as', I get

[]

whereas if I use the file name directly

 try:
 with open(args.config_file, 'r') as config_file:
 config = configparser.ConfigParser()
 config.read(args.config_file)
 print(config.sections())
I get

   ['loggers', 'handlers', 'formatters', 'logger_root', 'handler_fileHandler', 
'handler_consoleHandler', 'formatter_defaultFormatter']

which is what I expect.

If I print type of 'config_file' I get

   

whereas 'args.config_file' is just

   

Should I be able to use the '_io.TextIOWrapper' object variable here?  If so 
how?

Here

   https://docs.python.org/3.9/library/configparser.html

there are examples which use the 'with open ... as' variable for writing
a configuration file, but not for reading one.

Cheers,

Loris

'config.read' expects a path or paths. If you give it a file handle, it 
treats it as an iterable. (It might be reading the line as paths of 
files, but I haven't tested it).


If you want to read from an open file, use 'config.read_file' instead.

--
https://mail.python.org/mailman/listinfo/python-list


Re: shutil.rmtree() fails when used in Fedora (rpm) "mock" environment

2024-10-25 Thread MRAB via Python-list

On 2024-10-24 08:33, Christian Buhtz via Python-list wrote:

Hello,
I am upstream maintainer of "Back In Time" [1] investigating an issue a
distro maintainer from Fedora reported [2] to me.

On one hand Fedora seems to use a tool called "mock" to build packages
in a chroot environment.
On the other hand the test suite of "Back In Time" does read and write
to the real file system.
One test fails because a temporary directory is cleaned up using
shutil.rmtree(). Please see the output below.

I am not familiar with Fedora and "mock". So I am not able to reproduce
this on my own.
It seems the Fedora maintainer also has no clue how to solve it or why
it happens.

Can you please have a look (especially at the line "assert func is
os.lstat").
Maybe you have an idea what is the intention behind this error raised by
an "assert" statement inside "shutil.rmtree()".

Thanks in advance,
Christian Buhtz

[1] -- 
[2] -- 

__ General.test_ctor_defaults
__
self = 
  def test_ctor_defaults(self):
  """Default values in constructor."""

  with TemporaryDirectory(prefix='bit.') as temp_name:

test/test_uniquenessset.py:47:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
_ _ _ _
/usr/lib64/python3.13/tempfile.py:946: in __exit__
  self.cleanup()
/usr/lib64/python3.13/tempfile.py:950: in cleanup
  self._rmtree(self.name, ignore_errors=self._ignore_cleanup_errors)
/usr/lib64/python3.13/tempfile.py:930: in _rmtree
  _shutil.rmtree(name, onexc=onexc)
/usr/lib64/python3.13/shutil.py:763: in rmtree
  _rmtree_safe_fd(stack, onexc)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
_ _ _ _
stack = []
onexc = .onexc at
0xb39bc860>
  def _rmtree_safe_fd(stack, onexc):
  # Each stack item has four elements:
  # * func: The first operation to perform: os.lstat, os.close or
os.rmdir.
  #   Walking a directory starts with an os.lstat() to detect
symlinks; in
  #   this case, func is updated before subsequent operations and
passed to
  #   onexc() if an error occurs.
  # * dirfd: Open file descriptor, or None if we're processing the
top-level
  #   directory given to rmtree() and the user didn't supply
dir_fd.
  # * path: Path of file to operate upon. This is passed to
onexc() if an
  #   error occurs.
  # * orig_entry: os.DirEntry, or None if we're processing the
top-level
  #   directory given to rmtree(). We used the cached stat() of
the entry to
  #   save a call to os.lstat() when walking subdirectories.
  func, dirfd, path, orig_entry = stack.pop()
  name = path if orig_entry is None else orig_entry.name
  try:
  if func is os.close:
  os.close(dirfd)
  return
  if func is os.rmdir:
  os.rmdir(name, dir_fd=dirfd)
  return

  # Note: To guard against symlink races, we use the standard
  # lstat()/open()/fstat() trick.

  assert func is os.lstat

E   AssertionError
/usr/lib64/python3.13/shutil.py:663: AssertionError


What does "mock" do?

func should be either os.close, os.rmdir or os.lstat.

If mock is somehow replacing one of those functions, then it might break 
the code.

--
https://mail.python.org/mailman/listinfo/python-list


Re: How to check whether audio bytes contain empty noise or actual voice/signal?

2024-10-26 Thread MRAB via Python-list

On 2024-10-25 17:25, marc nicole via Python-list wrote:

Hello Python fellows,

I hope this question is not very far from the main topic of this list, but
I have a hard time finding a way to check whether audio data samples are
containing empty noise or actual significant voice/noise.

I am using PyAudio to collect the sound through my PC mic as follows:

FRAMES_PER_BUFFER = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 48000
RECORD_SECONDS = 2import pyaudio
audio = pyaudio.PyAudio()
stream = audio.open(format=FORMAT,
 channels=CHANNELS,
 rate=RATE,
 input=True,
 frames_per_buffer=FRAMES_PER_BUFFER,
 input_device_index=2)
data = stream.read(FRAMES_PER_BUFFER)


I want to know whether or not data contains voice signals or empty sound,
To note that the variable always contains bytes (empty or sound) if I print
it.

Is there an straightforward "easy way" to check whether data is filled with
empty noise or that somebody has made noise/spoke?

Thanks.
If you do a spectral analysis and find peaks at certain frequencies, 
then there might be a "significant" sound.


--
https://mail.python.org/mailman/listinfo/python-list


Re: Using 'with open(...) as ...' together with configparser.ConfigParser.read

2024-10-31 Thread MRAB via Python-list

On 2024-10-31 06:47, Loris Bennett via Python-list wrote:

Jon Ribbens  writes:


On 2024-10-30, Loris Bennett  wrote:

Jon Ribbens  writes:

On 2024-10-30, Loris Bennett  wrote:

Jon Ribbens  writes:

As per the docs you link to, the read() method only takes filename(s)
as arguments, if you have an already-open file you want to read then
you should use the read_file() method instead.


As you and others have pointed out, this is indeed covered in the docs,
so mea culpa.

However, whereas I can see why you might want to read the config from a
dict or a string, what would be a use case in which I would want to
read from an open file rather than just reading from a file(name)?


The ConfigParser module provides read(), read_file(), read_string(),
and read_dict() methods. I think they were just trying to be
comprehensive. It's a bit non-Pythonic really.


OK, but is there a common situation might I be obliged to use
'read_file'?  I.e. is there some common case where the file name is not
available, only a corresponding file-like object or stream?


Well, sure - any time it's not being read from a file. A bit ironic
that the method to use in that situation is "read_file", of course.
In my view the read() and read_file() methods have their names the
wrong way round. But bear in mind this code is 27 years old, and
the read() function came first.


Yes, I suppose history has a lot to answer for :-)

However I didn't make myself clear: I understand that there are
different functions, depending on whether I have a file name or a
stream.  Nevertheless, I just can't think of a practical example where I
might just have *only* a stream, especially one containing my
configuration data.  I was just interested to know if anyone can give an
example.


What if the config file was inside a zipped folder?

Although I haven't used ConfigParser like that, I have read the contents 
of files that are in a zipped folder. It means that I don't have to 
extract the file first.

--
https://mail.python.org/mailman/listinfo/python-list


Re: Old matplotlib animation now fails

2024-10-15 Thread MRAB via Python-list

On 2024-10-15 21:16, Martin Schöön via Python-list wrote:

Some years ago I created a Python program that reads GPS data and
creates an animation stored in an mp4 file. Not very elegant but it
worked. Not very original as it was based on the example found here:

https://shorturl.at/dTCZZ

Last time it worked was about a year ago. Since then I have moved to a
later version of Debian and Conda and as a consequence a later version
of Python 3 (now 3.12.2).

Now my code fails. I have downloaded the latest version of the example
and it also fails.

It is the second to last line that throws an error:

l.set_data(x0, y0)

The error messages drills down to something called
"/home/.../matplotlib/lines.py", line 1289, in set_xdata

and tells me 'x must be a sequence'

I have started to dig around in matplotlib's documentation but my
strategy is clearly wanting. I don't really know where to start
looking for information on how to correct my code. Hence, this
call for help.

Any ideas?


This is from the help:

"""
Help on function set_data in module matplotlib.lines:

set_data(self, *args)
Set the x and y data.

Parameters
--
*args : (2, N) array or two 1D arrays

See Also

set_xdata
set_ydata
"""

So, the arguments should be arrays:

For example:

x0, y0 = np.array([0.0]), np.array([0.0])

Has the API changed at some point?

--
https://mail.python.org/mailman/listinfo/python-list


Re: subprocess.Popen does not launch audacity

2025-01-10 Thread MRAB via Python-list

On 2025-01-10 19:15, Tim Johnson via Python-list wrote:

Using Python 3.12.3 on Ubuntu 24.04

I've converted a legacy python2 script to python3. All went well.
However, a glitch from python2 remains.

The script uses dmenu to create menus to pick applications. Applications
are then invoked from python

using subprocess.Popen(). I have never been able to successfully launch
audacity using this approach,

which does work for other apps.

I can launch audacity successfully using dmenu_run (on its own, outside
of the script)

Below is the pertinent code:

   Popen(choice, stdout=PIPE, stderr=PIPE,
    stdin=PIPE, close_fds=True)

My guess is my argument list is either insufficient or an argument is
causing the problem, but am unsure of which.

I have been retired from python programming for ten years, and am pretty
rusty, but it is still fun. There are plenty

of other ways to successfully launch audacity but it would be great to
make it work from this script.



What is the value of 'choice'?

You could try printing out the value of 'choice' for one that works and 
the one that doesn't and then try them again interactively from the 
Python prompt with the given values. That should eliminate all but the 
essential code for easier debugging.

--
https://mail.python.org/mailman/listinfo/python-list