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

2024-05-29 Thread Thomas Passin via Python-list

On 5/29/2024 10:59 AM, MRAB via Python-list wrote:

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.


I wondered if anyone would catch that :)  Anyway, I don't think the 
original question was whether to start with even or odd but ways to 
iterate character by character and do something, right?



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:


Actually, I did mess up the action for a space.  It should be:

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

We should never get two printable uppercased characters in a row, even 
if there is a space between them, but my original convert(convert_this, 
ch) did.



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: Flubbed it in the second interation through the string: range error... HOW?

2024-05-29 Thread Grant Edwards via Python-list
On 2024-05-29, Mats Wichmann via Python-list  wrote:
> On 5/29/24 08:02, Grant Edwards via Python-list wrote:
>> On 2024-05-29, Chris Angelico via Python-list  wrote:
>> 
>>> print(f"if block {name[index]=} {index=}")
>> 
>> Holy cow!  How did I not know about the f-string {=} thing?
>
> It's more recent than f-strings in general, so it's not that hard to miss.

I really should make a habit of reading through the "what's new" pages
when new releases come out...

--
Grant
-- 
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: Flubbed it in the second interation through the string: range error... HOW?

2024-05-29 Thread Barry Scott via Python-list



> On 29 May 2024, at 05:38, Kevin M. Wilson via Python-list 
>  wrote:
> 
> The format in this email is not of my making, should someone know, how to do 
> this so that it's a readable script do tell!
> KMW


Your mail program may have a plain-text mode to compose messages in try using 
that.

Barry

-- 
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 Thomas Passin via Python-list

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

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).





***
"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
*


On Wednesday, May 29, 2024 at 06:19:56 AM MDT, Thomas Passin via 
Python-list  wrote:



On 5/29/2024 3:14 AM, Chris Angelico via Python-list wrote:
 > On Wed, 29 May 2024 at 16:03, Cameron Simpson via Python-list
 > mailto:python-list@python.org>> wrote:
 >> By which Thomas means stuff like this:
 >>
 >>      print(f'if block {name[index]} and index {index}')
 >>
 >> Notice the leading "f'". Personally I wouldn't even go that far, just:
 >>
 >>      print('if block', name[index], 'and index', index)
 >>
 >> But there are plenty of places where f-strings are very useful.
 >
 > I wouldn't replace str.format() everywhere, nor would I replace
 > percent encoding everywhere - but in this case, I think Thomas is
 > correct. Not because it's 2024 (f-strings were brought in back in
 > 2015, so they're hardly chronologically special),

I only meant that they have been around for 9 years and are usually more
readable, so just change over already.  I had some inertia over them
myself (imagine sticking with % formatting!) so I understand.


 > but because most of
 > this looks like debugging output that can take advantage of this
 > feature:
 >
 > print(f"if block {name[index]=} {index=}")
 >
 > ChrisA

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



--
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 Mats Wichmann via Python-list

On 5/29/24 08:02, Grant Edwards via Python-list wrote:

On 2024-05-29, Chris Angelico via Python-list  wrote:


print(f"if block {name[index]=} {index=}")


Holy cow!  How did I not know about the f-string {=} thing?



It's more recent than f-strings in general, so it's not that hard to miss.
--
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 Grant Edwards via Python-list
On 2024-05-29, Chris Angelico via Python-list  wrote:

> print(f"if block {name[index]=} {index=}")

Holy cow!  How did I not know about the f-string {=} thing?

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


Re: Formatted Output and Argument Parsing (was: Re: Flubbed it in the second interation through the string: range error... HOW?)

2024-05-29 Thread Chris Angelico via Python-list
On Wed, 29 May 2024 at 23:06, Dan Sommers via Python-list
 wrote:
> (For the history-impaired, getopt existed long before Python and will
> likely exist long after it, but getopt's "replacement" optparse lasted
> only from 2003 until 2011.)

Depends on your definition of "lasted". It's not getting developed
further, but it's still there. If you started using it, you're welcome
to keep going.

https://docs.python.org/3/library/optparse.html

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


Formatted Output and Argument Parsing (was: Re: Flubbed it in the second interation through the string: range error... HOW?)

2024-05-29 Thread Dan Sommers via Python-list
On 2024-05-29 at 17:14:51 +1000,
Chris Angelico via Python-list  wrote:

> I wouldn't replace str.format() everywhere, nor would I replace
> percent encoding everywhere - but in this case, I think Thomas is
> correct. Not because it's 2024 (f-strings were brought in back in
> 2015, so they're hardly chronologically special), but because most of
> this looks like debugging output that can take advantage of this
> feature:
> 
> print(f"if block {name[index]=} {index=}")

defsnark:

After years of getopt (and even more, if you include non-Python
experience), I'm glad I decided to wait a decade before chugging the
optparse koolaid.

(For the history-impaired, getopt existed long before Python and will
likely exist long after it, but getopt's "replacement" optparse lasted
only from 2003 until 2011.)

That said, I agree that the = thing makes f-strings eminently useful for
debugging, and I wholeheartedly agree with not fixing things that aren't
broken.
-- 
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 Thomas Passin via Python-list

On 5/29/2024 3:14 AM, Chris Angelico via Python-list wrote:

On Wed, 29 May 2024 at 16:03, Cameron Simpson via Python-list
 wrote:

By which Thomas means stuff like this:

  print(f'if block {name[index]} and index {index}')

Notice the leading "f'". Personally I wouldn't even go that far, just:

  print('if block', name[index], 'and index', index)

But there are plenty of places where f-strings are very useful.


I wouldn't replace str.format() everywhere, nor would I replace
percent encoding everywhere - but in this case, I think Thomas is
correct. Not because it's 2024 (f-strings were brought in back in
2015, so they're hardly chronologically special),


I only meant that they have been around for 9 years and are usually more 
readable, so just change over already.  I had some inertia over them 
myself (imagine sticking with % formatting!) so I understand.



but because most of
this looks like debugging output that can take advantage of this
feature:

print(f"if block {name[index]=} {index=}")

ChrisA


--
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 Chris Angelico via Python-list
On Wed, 29 May 2024 at 16:03, Cameron Simpson via Python-list
 wrote:
> By which Thomas means stuff like this:
>
>  print(f'if block {name[index]} and index {index}')
>
> Notice the leading "f'". Personally I wouldn't even go that far, just:
>
>  print('if block', name[index], 'and index', index)
>
> But there are plenty of places where f-strings are very useful.

I wouldn't replace str.format() everywhere, nor would I replace
percent encoding everywhere - but in this case, I think Thomas is
correct. Not because it's 2024 (f-strings were brought in back in
2015, so they're hardly chronologically special), but because most of
this looks like debugging output that can take advantage of this
feature:

print(f"if block {name[index]=} {index=}")

ChrisA
-- 
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 Cameron Simpson via Python-list

On 29May2024 01:14, Thomas Passin  wrote:
Also, it's 2024 ... time to start using f-strings (because they are 
more readable than str.format())


By which Thomas means stuff like this:

print(f'if block {name[index]} and index {index}')

Notice the leading "f'". Personally I wouldn't even go that far, just:

print('if block', name[index], 'and index', index)

But there are plenty of places where f-strings are very useful.
--
https://mail.python.org/mailman/listinfo/python-list


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

2024-05-28 Thread Thomas Passin via Python-list
Your code is unreadable. The lines have all run together.  And after 
that, kindly explain what you want your code sample to do.  "Process" 
doesn't say much.


From what I can make out about what you are trying to do, you would do 
better to index through your string with


for i, chr in enumerate(name):
# do something with the character

Also, it's 2024 ... time to start using f-strings (because they are more 
readable than str.format())


On 5/29/2024 12:33 AM, 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


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


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

2024-05-28 Thread Kevin M. Wilson via Python-list
The format in this email is not of my making, should someone know, how to do 
this so that it's a readable script do tell!
KMW

***
"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
 

   - Forwarded Message - From: Kevin M. Wilson via Python-list 
To: python-list@python.org 
Sent: Tuesday, May 28, 2024 at 10:35:23 PM MDTSubject: 
Flubbed it in the second interation through the string: range error... HOW?
 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
---
IndexError                                Traceback (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
-- 
https://mail.python.org/mailman/listinfo/python-list
  
-- 
https://mail.python.org/mailman/listinfo/python-list


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

2024-05-28 Thread Kevin M. Wilson via Python-list
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
-- 
https://mail.python.org/mailman/listinfo/python-list


Can't trap paramiko runtime trace-back error

2024-05-22 Thread Vinode Singh Ujlain via Python-list
When running the code below , I get error as enumerated below. Why am I 
not able to trap this paramiko runtime traceback in try-except block ?


Exception (client): Error reading SSH protocol banner
Traceback (most recent call last):
  File 
"/home/uzi/.local/lib/python3.8/site-packages/paramiko/transport.py", 
line 2327, in _check_banner

    buf = self.packetizer.readline(timeout)
  File 
"/home/uzi/.local/lib/python3.8/site-packages/paramiko/packet.py", line 
381, in readline

    buf += self._read_timeout(timeout)
  File 
"/home/uzi/.local/lib/python3.8/site-packages/paramiko/packet.py", line 
626, in _read_timeout

    raise socket.timeout()
socket.timeout

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File 
"/home/uzi/.local/lib/python3.8/site-packages/paramiko/transport.py", 
line 2143, in run

    self._check_banner()
  File 
"/home/uzi/.local/lib/python3.8/site-packages/paramiko/transport.py", 
line 2331, in _check_banner

    raise SSHException(
paramiko.ssh_exception.SSHException: Error reading SSH protocol banner

SSH error: No existing session

importparamiko
importtime
defexecute():
try:
# Define the server and credentials
ip='p.q.r.s'
un, up, po='name', "passwd", 22
bto, sto=60, 60
ssh_client=paramiko.SSHClient()
ssh_client.load_system_host_keys()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(hostname=ip, port=po, username=un, password=up, 
banner_timeout=bto, timeout=sto)

shell=ssh_client.invoke_shell()
defsend_command(command, wait_time=1):
shell.send(command+'\n')
time.sleep(wait_time) # Give the command some time to execute
whilenotshell.recv_ready():
time.sleep(0.1)
returnshell.recv(8192).decode()
output=send_command('date')
print("Output:\n", output)
delssh_client
exceptparamiko.SSHExceptionase:
print(f"SSH error: {e}")
exceptExceptionase:
print(f"Error: {e}")
finally:
# Close the SSH client connection
delssh_client
execute()

--
Warm Regards,
Vinode Singh Ujlain | https://www.linkedin.com/in/ujlain/

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


Re: Trying to use pyinstaller under python 3.11, and, recently started receiving error message about specific module/distribution

2024-04-04 Thread Jacob Kruger via Python-list
Ok, had received response on pyinstaller mailing list, but, also just 
related to trying clean uninstall/reinstall of modules, but, while 
checking that out, something else occurred to me, and, it now operates 
as it should.



Anyway, what seemed to be causing issue was actually that, since, while 
am working under windows 11, quite often you might need to work with 
case-sensitivity in file names, not by choice, but, since a lot of 
target platforms, like linux, etc. are case-sensitive, and, at times, 
when working with external modules, this might cause hassles, etc.



In other words, the folder/directory where all my python source code is 
stored is set to be case-sensitive - there are a couple of ways to 
implement this under windows 10 and windows 11, via some external 
utilities, or by running the following command from a 
terminal/power-shell window, running it as administrator:


fsutil.exe file SetCaseSensitiveInfo C:\folder\path enable


If you instead use disable argument at the end, it then disables 
case-sensitivity, and, what did now was, under current project/test 
code, I created an additional sub-folder, copied code files, etc. over 
into it, disabled case-sensitivity on it, recreated the virtual 
environment, and installed all required modules, including pyinstaller 
using pip, and, when I then run pyinstaller from there, it works fine, 
and, does what I want it to.



In other words, something to do with having case-sensitivity enabled 
recursively on the folder/directory containing the code and the virtual 
environment seemed to be causing these errors/issues, specific to 
altgraph, which doesn't really make sense to me, but, it's now working, 
so, will archive this to memory, for later reference.



Jacob Kruger
+2782 413 4791
"Resistance is futile!...Acceptance is versatile..."


On 2024/04/02 17:11, Barry wrote:



On 1 Apr 2024, at 15:52, Jacob Kruger via Python-list  
wrote:

Found many, many mentions of errors, with some of the same keywords, but, no 
resolutions that match my exact issue at all.

Try asking the pyinstaller developers. I think there is a mailing list.

Barry


As in, most of them are mentioning older versions of python, and, mainly 
different platforms - mac and linux, but, various google searches have not 
mentioned much of using it on windows, and having it just stop working.


Now did even try shifting over to python 3.12, but, still no-go.


If launch pyinstaller under python 3.10 on this exact same machine, pyinstaller 
runs - just keep that older version hovering around for a couple of occasional 
tests, partly since some of my target environments are still running older 
versions of python, but anyway.


Also, not really relevant, but, cx_freeze is perfectly able to generate 
executables for this same code, but, then not combining all output into a 
single file - will stick to that for now, but, not always as convenient, and, 
still wondering what changed here.


Jacob Kruger
+2782 413 4791
"Resistance is futile!...Acceptance is versatile..."



On 2024/03/31 14:51, Barry wrote:


On 31 Mar 2024, at 13:24, Jacob Kruger via Python-list  
wrote:

pkg_resources.DistributionNotFound: The 'altgraph' distribution was not found 
and is required by the application

I think I have seen this error being discussed before…

A web search for pyinstaller and that error leads to people discussing why it 
happens it looks like.

Barry



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

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


Re: Trying to use pyinstaller under python 3.11, and, recently started receiving error message about specific module/distribution

2024-04-03 Thread Jacob Kruger via Python-list
Ok, last update for now - checked out the following page on 
pyinstaller.org, and, ended up posting to the mailing list, so, let's see:


https://pyinstaller.org/en/latest/when-things-go-wrong.html


Jacob Kruger
+2782 413 4791
"Resistance is futile!...Acceptance is versatile..."


On 2024/04/02 17:11, Barry wrote:



On 1 Apr 2024, at 15:52, Jacob Kruger via Python-list  
wrote:

Found many, many mentions of errors, with some of the same keywords, but, no 
resolutions that match my exact issue at all.

Try asking the pyinstaller developers. I think there is a mailing list.

Barry


As in, most of them are mentioning older versions of python, and, mainly 
different platforms - mac and linux, but, various google searches have not 
mentioned much of using it on windows, and having it just stop working.


Now did even try shifting over to python 3.12, but, still no-go.


If launch pyinstaller under python 3.10 on this exact same machine, pyinstaller 
runs - just keep that older version hovering around for a couple of occasional 
tests, partly since some of my target environments are still running older 
versions of python, but anyway.


Also, not really relevant, but, cx_freeze is perfectly able to generate 
executables for this same code, but, then not combining all output into a 
single file - will stick to that for now, but, not always as convenient, and, 
still wondering what changed here.


Jacob Kruger
+2782 413 4791
"Resistance is futile!...Acceptance is versatile..."



On 2024/03/31 14:51, Barry wrote:


On 31 Mar 2024, at 13:24, Jacob Kruger via Python-list  
wrote:

pkg_resources.DistributionNotFound: The 'altgraph' distribution was not found 
and is required by the application

I think I have seen this error being discussed before…

A web search for pyinstaller and that error leads to people discussing why it 
happens it looks like.

Barry



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

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


Re: Trying to use pyinstaller under python 3.11, and, recently started receiving error message about specific module/distribution

2024-04-02 Thread Barry via Python-list


> On 1 Apr 2024, at 15:52, Jacob Kruger via Python-list 
>  wrote:
> 
> Found many, many mentions of errors, with some of the same keywords, but, no 
> resolutions that match my exact issue at all.

Try asking the pyinstaller developers. I think there is a mailing list.

Barry
> 
> 
> As in, most of them are mentioning older versions of python, and, mainly 
> different platforms - mac and linux, but, various google searches have not 
> mentioned much of using it on windows, and having it just stop working.
> 
> 
> Now did even try shifting over to python 3.12, but, still no-go.
> 
> 
> If launch pyinstaller under python 3.10 on this exact same machine, 
> pyinstaller runs - just keep that older version hovering around for a couple 
> of occasional tests, partly since some of my target environments are still 
> running older versions of python, but anyway.
> 
> 
> Also, not really relevant, but, cx_freeze is perfectly able to generate 
> executables for this same code, but, then not combining all output into a 
> single file - will stick to that for now, but, not always as convenient, and, 
> still wondering what changed here.
> 
> 
> Jacob Kruger
> +2782 413 4791
> "Resistance is futile!...Acceptance is versatile..."
> 
> 
>> On 2024/03/31 14:51, Barry wrote:
>> 
>>>> On 31 Mar 2024, at 13:24, Jacob Kruger via Python-list 
>>>>  wrote:
>>> 
>>> pkg_resources.DistributionNotFound: The 'altgraph' distribution was not 
>>> found and is required by the application
>> I think I have seen this error being discussed before…
>> 
>> A web search for pyinstaller and that error leads to people discussing why 
>> it happens it looks like.
>> 
>> Barry
>> 
>> 
> --
> https://mail.python.org/mailman/listinfo/python-list

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


Re: Trying to use pyinstaller under python 3.11, and, recently started receiving error message about specific module/distribution

2024-04-01 Thread Jacob Kruger via Python-list
Found many, many mentions of errors, with some of the same keywords, 
but, no resolutions that match my exact issue at all.



As in, most of them are mentioning older versions of python, and, mainly 
different platforms - mac and linux, but, various google searches have 
not mentioned much of using it on windows, and having it just stop working.



Now did even try shifting over to python 3.12, but, still no-go.


If launch pyinstaller under python 3.10 on this exact same machine, 
pyinstaller runs - just keep that older version hovering around for a 
couple of occasional tests, partly since some of my target environments 
are still running older versions of python, but anyway.



Also, not really relevant, but, cx_freeze is perfectly able to generate 
executables for this same code, but, then not combining all output into 
a single file - will stick to that for now, but, not always as 
convenient, and, still wondering what changed here.



Jacob Kruger
+2782 413 4791
"Resistance is futile!...Acceptance is versatile..."


On 2024/03/31 14:51, Barry wrote:



On 31 Mar 2024, at 13:24, Jacob Kruger via Python-list  
wrote:

pkg_resources.DistributionNotFound: The 'altgraph' distribution was not found 
and is required by the application

I think I have seen this error being discussed before…

A web search for pyinstaller and that error leads to people discussing why it 
happens it looks like.

Barry



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


Re: Trying to use pyinstaller under python 3.11, and, recently started receiving error message about specific module/distribution

2024-03-31 Thread Barry via Python-list


> On 31 Mar 2024, at 13:24, Jacob Kruger via Python-list 
>  wrote:
> 
> pkg_resources.DistributionNotFound: The 'altgraph' distribution was not found 
> and is required by the application

I think I have seen this error being discussed before…

A web search for pyinstaller and that error leads to people discussing why it 
happens it looks like.

Barry


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


Trying to use pyinstaller under python 3.11, and, recently started receiving error message about specific module/distribution

2024-03-31 Thread Jacob Kruger via Python-list
This started happening this past week, and, while it's worked fine in 
the past, the moment I try to launch the pyinstaller process at all, to 
generate compiled output, or even if just launch it with no command line 
options, I receive the following error message:


pkg_resources.DistributionNotFound: The 'altgraph' distribution was not 
found and is required by the application



The full contents of the output string when I even try to just launch 
pyinstaller with no commands/arguments is the following:


Traceback (most recent call last):
  File "", line 198, in _run_module_as_main
  File "", line 88, in _run_code
  File 
"C:\pythonScripts\monitoring_nssm\venv\Scripts\pyinstaller.exe\__main__.py", 
line 7, in 
  File 
"C:\pythonScripts\monitoring_nssm\venv\Lib\site-packages\PyInstaller\__main__.py", 
line 228, in _console_script_run

run()
  File 
"C:\pythonScripts\monitoring_nssm\venv\Lib\site-packages\PyInstaller\__main__.py", 
line 170, in run

    parser = generate_parser()
^
  File 
"C:\pythonScripts\monitoring_nssm\venv\Lib\site-packages\PyInstaller\__main__.py", 
line 136, in generate_parser

    import PyInstaller.building.build_main
  File 
"C:\pythonScripts\monitoring_nssm\venv\Lib\site-packages\PyInstaller\building\build_main.py", 
line 28, in 

    from PyInstaller.building.api import COLLECT, EXE, MERGE, PYZ
  File 
"C:\pythonScripts\monitoring_nssm\venv\Lib\site-packages\PyInstaller\building\api.py", 
line 32, in 
    from PyInstaller.building.splash import Splash  # argument type 
validation in EXE

^^
  File 
"C:\pythonScripts\monitoring_nssm\venv\Lib\site-packages\PyInstaller\building\splash.py", 
line 23, in 

    from PyInstaller.depend import bindepend
  File 
"C:\pythonScripts\monitoring_nssm\venv\Lib\site-packages\PyInstaller\depend\bindepend.py", 
line 25, in 

    from PyInstaller.depend import dylib, utils
  File 
"C:\pythonScripts\monitoring_nssm\venv\Lib\site-packages\PyInstaller\depend\utils.py", 
line 31, in 

    from PyInstaller.lib.modulegraph import modulegraph
  File 
"C:\pythonScripts\monitoring_nssm\venv\Lib\site-packages\PyInstaller\lib\modulegraph\modulegraph.py", 
line 34, in 

    from altgraph.ObjectGraph import ObjectGraph
  File 
"C:\pythonScripts\monitoring_nssm\venv\Lib\site-packages\altgraph\__init__.py", 
line 144, in 

    __version__ = pkg_resources.require("altgraph")[0].version
^
  File 
"C:\pythonScripts\monitoring_nssm\venv\Lib\site-packages\pkg_resources\__init__.py", 
line 952, in require

    needed = self.resolve(parse_requirements(requirements))
^^
  File 
"C:\pythonScripts\monitoring_nssm\venv\Lib\site-packages\pkg_resources\__init__.py", 
line 813, in resolve

    dist = self._resolve_dist(
^^^
  File 
"C:\pythonScripts\monitoring_nssm\venv\Lib\site-packages\pkg_resources\__init__.py", 
line 854, in _resolve_dist

    raise DistributionNotFound(req, requirers)
pkg_resources.DistributionNotFound: The 'altgraph' distribution was not 
found and is required by the application


# ---end of output---


I have tried completely removing python's installation, and, 
reinstalling it, but, same issue more or less immediately.



If I freeze pip's installed list within this specific virtual 
environment, it lists the following:


altgraph==0.17.4
packaging==24.0
pefile==2023.2.7
pyinstaller==6.5.0
pyinstaller-hooks-contrib==2024.3
pywin32-ctypes==0.2.2

# ---end of requirements.txt---


And, if, just for testing, I launch python interpreter, and, ask it to 
import altgraph, it provides the same last line of error output?



If relevant, running with python 3.11.8, under windows 11 64-bit, and, 
can't think of anything that specifically occurred/changed this past 
week, besides normal things like windows updates, etc., but, don't 
really think that's likely to be relevant, unless something to do with 
pywin32 has caused an issue?



Should I try installing python 3.12 version instead and see if it changes?


Also, if relevant, while running under latest up-to-date version of 
windows 11 64 bit, have in any case enabled case-sensitivity on the 
folder I store all my python code in, just in case.



TIA

--

Jacob Kruger
+2782 413 4791
"Resistance is futile!...Acceptance is versatile..."


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


Re: Error in Module

2024-03-11 Thread Sanskar Mukeshbhai Joshi via Python-list
Thank you for the information.

On Mon, Mar 11, 2024, 22:36  wrote:

> Sanskar Mukeshbhai Joshi wrote at 2024-3-10 18:08 +:
> >I had made my project in BCA in Python. When I had complete my project
> and run the program, at that time I got the error in runnig my project. The
> error was ModuleNotFoundError: No module named 'flask'.
>
> `flask` is not part of the Python library; it has to be installed
> separately.
>
> Apparently, you project is a `flask` project (a Web application platform).
> In this case, you must run your program in a special `flask`
> environment.
>
> I suggest you contact your project mentor to get help.
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Error in Module

2024-03-11 Thread Dieter Maurer via Python-list
Sanskar Mukeshbhai Joshi wrote at 2024-3-10 18:08 +:
>I had made my project in BCA in Python. When I had complete my project and run 
>the program, at that time I got the error in runnig my project. The error was 
>ModuleNotFoundError: No module named 'flask'.

`flask` is not part of the Python library; it has to be installed separately.

Apparently, you project is a `flask` project (a Web application platform).
In this case, you must run your program in a special `flask`
environment.

I suggest you contact your project mentor to get help.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Error in Module

2024-03-11 Thread Alan Gauld via Python-list
On 10/03/2024 18:08, Sanskar Mukeshbhai Joshi via Python-list wrote:

> I had made my project in BCA in Python. When I had complete my 
> project and run the program, at that time I got the error in 
> runnig my project. The error was ModuleNotFoundError: No module named 'flask'.

Flask is a third party package that you need to install separately
from Python. It does not come as standard. Have you installed Flask
on the computer where you are running your project? If so, how did you
download/install it?

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Error in Module

2024-03-11 Thread Sanskar Mukeshbhai Joshi via Python-list
Respected Sir/Ma'am

I had made my project in BCA in Python. When I had complete my project and run 
the program, at that time I got the error in runnig my project. The error was 
ModuleNotFoundError: No module named 'flask'.

I request you to check this problem and resolve it or guide me to solve this 
Error.
-- 
https://mail.python.org/mailman/listinfo/python-list


Matplotlib warning [error?] message

2024-02-19 Thread Leif Svalgaard via Python-list
now I get:
 File e:\getmodpot.py:40
fig,ax = initPlot()

  File E:\mystuff.py:272 in initPlot
fig,ax = plt.subplots(figsize=(xs,ys))

  File ~\anaconda3\Lib\site-packages\matplotlib\pyplot.py:1501 in subplots
fig = figure(**fig_kw)

  File ~\anaconda3\Lib\site-packages\matplotlib\_api\deprecation.py:454 in
wrapper
return func(*args, **kwargs)

  File ~\anaconda3\Lib\site-packages\matplotlib\pyplot.py:840 in figure
manager = new_figure_manager(

  File ~\anaconda3\Lib\site-packages\matplotlib\pyplot.py:384 in
new_figure_manager
return _get_backend_mod().new_figure_manager(*args, **kwargs)

  File ~\anaconda3\Lib\site-packages\matplotlib\backend_bases.py:3573 in
new_figure_manager

  File ~\anaconda3\Lib\site-packages\matplotlib\_api\deprecation.py:454 in
wrapper
return func(*args, **kwargs)

  File ~\anaconda3\Lib\site-packages\matplotlib\figure.py:2505 in __init__
"The Figure parameters 'layout' and 'constrained_layout' "

  File ~\anaconda3\Lib\site-packages\matplotlib\figure.py:213 in __init__
self.set(**kwargs)

  File ~\anaconda3\Lib\site-packages\matplotlib\artist.py:147 in 
cls.set = lambda self, **kwargs: Artist.set(self, **kwargs)

  File ~\anaconda3\Lib\site-packages\matplotlib\artist.py:1227 in set
return self._internal_update(cbook.normalize_kwargs(kwargs, self))

  File ~\anaconda3\Lib\site-packages\matplotlib\cbook\__init__.py:1771 in
normalize_kwargs
for canonical, alias_list in alias_mapping.items()

AttributeError: 'Figure' object has no attribute 'items'

-- 
Leif Svalgaard
l...@leif.org
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Matplotlib warning [error?] message

2024-02-19 Thread Zahraa Fadhil via Python-list
On Sunday, February 18, 2024 at 10:48:29 PM UTC+3, Leif Svalgaard wrote:
> The latest[?] version of Matplotlib cannot show a figure. I get the 
> annoying error message: "Matplotlib is currently using agg, which is a 
> non-GUI backend, so cannot show the figure" 
> I'm using Spyder python 3.11 on Windows 11. 
> What to do? 
> 
> -- 
> Leif Svalgaard 
> 
I have the same problem
try this
1) add this line first 
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt

2) delete this line from your cod.matplotlib.use('Agg')

3) save the result into png file 
plt.savefig('D:\data\mygraph.png')


another solution 
https://www.w3schools.com/python/trypandas.asp?filename=demo_ml_dtree4

import sys
import matplotlib
matplotlib.use('Agg')

import matplotlib.pyplot as plt

#Two  lines to make compiler able to draw:
plt.savefig(sys.stdout.buffer)
sys.stdout.flush()

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


Matplotlib warning [error?] message

2024-02-18 Thread Leif Svalgaard via Python-list
The latest[?] version of Matplotlib cannot show a figure. I get the
annoying error message: "Matplotlib is currently using agg, which is a
non-GUI backend, so cannot show the figure"
I'm using Spyder python 3.11 on Windows 11.
What to do?

-- 
Leif Svalgaard
l...@leif.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


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

2024-02-03 Thread gelukt gelukt via Python-list
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

Kind regards

Gelukt
-- 
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: error of opening Python

2023-09-29 Thread anthony.flury via Python-list




This isn't an error.


This is just a normal Python Header message announcing that you are 
using Python 3.11.3
The rest is just information from the build system : The build Id,  the 
date/time the build was made, and the version of the compiler.


There is nothing to fix.


-- Original Message --
From: "Abdelkhelk ashref salay eabakh via Python-list" 


To: python-list@python.org
Sent: Tuesday, 26 Sep, 23 At 13:27
Subject: error of opening Python
Dear Python team,
This is my not first time using Python, I tried to launch Python and it 
showed
"Python 3.11.3 (tags/v3.11.3:f3909b8, Apr  4 2023, 23:49:59) [MSC v.1934 
64 bit (AMD64)] on win32
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 
<https://mail.python.org/mailman/listinfo/python-list>


-- Anthony Fluryanthony.fl...@btinternet.com
--
https://mail.python.org/mailman/listinfo/python-list


Re: error of opening Python

2023-09-27 Thread Greg Ewing via Python-list

On 27/09/23 3:30 pm, Chris Roy-Smith wrote:
surely running a 64 bit version of python in a 23mbit version of windows 
will cause significant problems!


23 millibits? I don't think you'd be able to run much at all
with that few bits! :-)

--
Greg
--
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: error of opening Python

2023-09-26 Thread Chris Roy-Smith via Python-list

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!


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: error of opening Python

2023-09-26 Thread Michael F. Stemper via Python-list

On 26/09/2023 07.27, Abdelkhelk ashref salay eabakh wrote:

Dear Python team,

This is my not first time using Python, I tried to launch Python and it showed
"Python 3.11.3 (tags/v3.11.3:f3909b8, Apr  4 2023, 23:49:59) [MSC v.1934 64 bit 
(AMD64)] on win32
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?


What error did you encounter? Aside from the lack of line breaks, it looks
quite similar to what I get when I start up python:

 Python 3.6.9 (default, Mar 10 2023, 16:46:00)
 [GCC 8.4.0] on linux
 Type "help", "copyright", "credits" or "license" for more information.
 >>>

Didn't you get the ">>> " prompt? Once you get it, it shows that the
Read, Evaluate, Print Loop (REPL) is ready for you to type some python
statements. For instance:

 >>> x = 2**3
 >>> print(x)
 8
 >>>

--
Michael F. Stemper
Outside of a dog, a book is man's best friend.
Inside of a dog, it's too dark to read.

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


error of opening Python

2023-09-26 Thread Abdelkhelk ashref salay eabakh via Python-list
Dear Python team,

This is my not first time using Python, I tried to launch Python and it showed
"Python 3.11.3 (tags/v3.11.3:f3909b8, Apr  4 2023, 23:49:59) [MSC v.1934 64 bit 
(AMD64)] on win32
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: f-string error message

2023-08-30 Thread Random832 via Python-list
On Sun, Aug 27, 2023, at 17:19, Rob Cliffe via Python-list wrote:
> I understand that this is an error: I'm telling the f-string to expect 
> an integer when in fact I'm giving it a Decimal.
> And indeed f"{x:3}" gives ' 42' whether x is an int or a Decimal.
> However, to my mind it is not the format string that is invalid, but the 
> value supplied to it.
> Would it be possible to have a different error message, something like
>
> ValueError: int expected in format string but decimal.Decimal found
>
> Or am I missing something?

It's up to the type what format strings are valid for it, so you can't really 
go "int expected". However, a more detailed error string like "invalid format 
string '3d' for object Decimal('42')" might be useful.

right now we have some inconsistencies:
- float object [same for str, int, etc]
ValueError: Unknown format code 'd' for object of type 'float' [if it thinks 
it's identified a single-letter 'code' in the usual microlanguage]
ValueError: Invalid format specifier '???' for object of type '[type]'
- arbitrary object that doesn't override __format__, ipaddress
TypeError: unsupported format string passed to [type].__format__
- datetime, decimal
ValueError: Invalid format string

neither shows the value of the offending object, only its type. incidentally, 
ipaddress and object don't support the usual field width, padding, etc 
specifiers

[int supports code 'f' just fine, by the way, but has the same message as float 
if you give it 's']

Going beyond that, it *might* be viable to have some sort of "guess what 
numeric type the format string was intended for", shared across at least all 
numeric types of objects. Alternatively, we could require all numeric types to 
support all numeric formats, even ones that don't make a lot of sense.
-- 
https://mail.python.org/mailman/listinfo/python-list


f-string error message

2023-08-30 Thread Rob Cliffe via Python-list

I am currently using Python 3.11.4.
First I want to say: f-strings are great!  I use them all the time, 
mostly but by no means exclusively for debug messages.  And in 3.12 they 
will get even better.
And the improved error messages in Python (since 3.9) are great too!  
Keep up the good work.
However the following error message confused me for a while when it 
happened in real code:



import decimal
x=42
f"{x:3d}"

' 42'

x=decimal.Decimal('42')
f"{x:3d}"

Traceback (most recent call last):
  File "", line 1, in 
ValueError: invalid format string

I understand that this is an error: I'm telling the f-string to expect 
an integer when in fact I'm giving it a Decimal.

And indeed f"{x:3}" gives ' 42' whether x is an int or a Decimal.
However, to my mind it is not the format string that is invalid, but the 
value supplied to it.

Would it be possible to have a different error message, something like

ValueError: int expected in format string but decimal.Decimal found

Or am I missing something?
Best wishes
Rob Cliffe

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


Re: Where is the error?

2023-08-07 Thread Michael Agbenike via Python-list
When i try to open a python script it either says theres no ctk module or
no pip

On Sun, Aug 6, 2023, 3:51 PM Peter J. Holzer via Python-list <
python-list@python.org> wrote:

> Mostly, error messages got a lot better in Python 3.10, but this one had
> me scratching my head for a few minutes.
>
> Consider this useless and faulty script:
>
> 
> r = {
> "x": (1 + 2 + 3)
> "y": (4 + 5 + 6)
> "z": (7 + 8 + 9)
> }
> 
>
> Python 3.9 (and earlier) reports:
>
> 
>   File "/home/hjp/tmp/foo", line 3
> "y": (4 + 5 + 6)
> ^
> SyntaxError: invalid syntax
> ----
>
> This isn't great, but experience with lots of programming languages
> tells me that an error is noticed where or after it actually occurs, so
> it's easy to see that there is a comma missing just before the "y".
>
> Python 3.10 and 3.11 report:
>
> 
>   File "/home/hjp/tmp/foo", line 2
> "x": (1 + 2 + 3)
>   ^^
> SyntaxError: invalid syntax. Perhaps you forgot a comma?
> ----
>
> The error message is now a lot better, of course, but the fact that it
> points at the expression *before* the error completely threw me. The
> underlined expression is clearly not missing a comma, nor is there an
> error before that. My real program was a bit longer of course, so I
> checked the lines before that to see if I forgot to close any
> parentheses. Took me some time to notice the missing comma *after* the
> underlined expression.
>
> Is this "clairvoyant" behaviour a side-effect of the new parser or was
> that a deliberate decision?
>
> hp
>
> --
>_  | Peter J. Holzer| Story must make more sense than reality.
> |_|_) ||
> | |   | h...@hjp.at |-- Charles Stross, "Creative writing
> __/   | http://www.hjp.at/ |   challenge!"
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Where is the error?

2023-08-07 Thread Cameron Simpson via Python-list

On 07Aug2023 08:02, Barry  wrote:

On 7 Aug 2023, at 05:28, Cameron Simpson via Python-list 
 wrote:
Used to use a Pascal compiler once which was uncannily good at 
suggesting where you'd missing a semicolon.


Was that on DEC VMS? It was a goal at DEC for its compilers to do this well.


No, a PDP-11 using V7 UNIX.


They could output the errors in a machine readable format to allow editors to 
auto fix.
I am learning rust and it is very good at suggesting fixes.
There is a command to apply fixes automatically, cargo fix.


Neat.

Cheers,
Cameron Simpson 
--
https://mail.python.org/mailman/listinfo/python-list


Re: Where is the error?

2023-08-07 Thread Barry via Python-list



> On 7 Aug 2023, at 05:28, Cameron Simpson via Python-list 
>  wrote:
> 
> Used to use a Pascal compiler once which was uncannily good at suggesting 
> where you'd missing a semicolon.

Was that on DEC VMS? It was a goal at DEC for its compilers to do this well.
They could output the errors in a machine readable format to allow editors to 
auto fix.

I am learning rust and it is very good at suggesting fixes.
There is a command to apply fixes automatically, cargo fix.

Barry




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


Re: Where is the error?

2023-08-06 Thread Cameron Simpson via Python-list

On 06Aug2023 22:41, Peter J. Holzer  wrote:

Mostly, error messages got a lot better in Python 3.10, but this one had
me scratching my head for a few minutes.

Consider this useless and faulty script:

r = {
   "x": (1 + 2 + 3)
   "y": (4 + 5 + 6)
   "z": (7 + 8 + 9)
}


[...]

Python 3.10 and 3.11 report:


 File "/home/hjp/tmp/foo", line 2
   "x": (1 + 2 + 3)
 ^^
SyntaxError: invalid syntax. Perhaps you forgot a comma?
----

The error message is now a lot better, of course, but the fact that it
points at the expression *before* the error completely threw me. The
underlined expression is clearly not missing a comma, nor is there an
error before that.


Well, it's hard to underline a token which isn't present. But maybe the 
message could be more evocative:


SyntaxError: invalid syntax. Perhaps you forgot a comma after the 
underlined code?


Is this "clairvoyant" behaviour a side-effect of the new parser or was
that a deliberate decision?


I have the vague impression the new parser enabled the improved 
reporting.


Used to use a Pascal compiler once which was uncannily good at 
suggesting where you'd missing a semicolon.


Cheers,
Cameron Simpson 
--
https://mail.python.org/mailman/listinfo/python-list


Re: Where is the error?

2023-08-06 Thread dn via Python-list

On 07/08/2023 08.41, Peter J. Holzer via Python-list wrote:

Mostly, error messages got a lot better in Python 3.10, but this one had
me scratching my head for a few minutes.

...



The error message is now a lot better, of course, but the fact that it
points at the expression *before* the error completely threw me. The
underlined expression is clearly not missing a comma, nor is there an
error before that. My real program was a bit longer of course, so I
checked the lines before that to see if I forgot to close any
parentheses. Took me some time to notice the missing comma *after* the
underlined expression.

Is this "clairvoyant" behaviour a side-effect of the new parser or was
that a deliberate decision?


Found myself chuckling at this - not to be unkind, but because can 
easily imagine such confusion on my own part.


The issue of unhelpful error messages or information aimed at a similar 
but different context, has been the story of our lives. Advice to 
trainees has always been to cast-about looking for the error - rather 
than taking the line-number as a precise location. Have made a note to 
avoid advising folk to work 'backwards'!


Meantime (back at the ranch?), haven't experienced this. Using an IDE 
means all such stuff is reported, as one types, through highlights and 
squiggly lines (which should(?) be considered and cleared - before 
pressing the GO-button).


In this case, the PyCharm* editor adds red-squiggles where the commas 
should have been. Hovering the cursor over a squiggle, the IDE reports 
"',' expected"! Its PythonConsole behaves similarly (without offering a 
'hover'). Plus, even after the closing brace, it continues to assume a 
multi-line compound-statement (and thus won't execute, per expected REPL 
behavior).



Way-back (grey-beard time!) when we submitted card-decks of code to be 
compiled over-night, one idea to avoid expensive, trivial errors/eras; 
was that spelling-checkers should be built-in to compilers, eg to 
auto-magically correct typos, eg


AFF 1 TO TOTAL

instead of:

ADD 1 TO TOTAL

These days, we can look at code from two or more years ago, 'produced' 
by ChatGPT (et al), aka "The Stochastic Parrot". There is some thought 
that artificial 'intelligence' will one-day be able to do the coding for 
us/predict what is required/act as a crystal ball...


Speaking of which, and just because I could, here's what Chat-GPT had to 
say when I asked "what's wrong with ...":


«The issue in the given Python code is that you're missing commas 
between the key-value pairs in the dictionary. Commas are required to 
separate different key-value pairs within a dictionary. Here's the 
corrected version of the code:

...
»

Question: If a Chat-AI is built into the IDE (I stripped such out from 
mine), does it take-over error reporting and diagnosis (and offer the 
option of replacing with its 'corrected version'?) - rather than 
requiring an extra copy-paste step, per above?

(and need for my assumption of where the error is located)


Hope you've exerted copyright over the "clairvoyant" description!


* JetBrains kindly sponsor our PUG with a monthly door-prize.
--
--
Regards,
=dn
--
https://mail.python.org/mailman/listinfo/python-list


Where is the error?

2023-08-06 Thread Peter J. Holzer via Python-list
Mostly, error messages got a lot better in Python 3.10, but this one had
me scratching my head for a few minutes.

Consider this useless and faulty script:


r = {
"x": (1 + 2 + 3)
"y": (4 + 5 + 6)
"z": (7 + 8 + 9)
}


Python 3.9 (and earlier) reports:


  File "/home/hjp/tmp/foo", line 3
"y": (4 + 5 + 6)
^
SyntaxError: invalid syntax


This isn't great, but experience with lots of programming languages
tells me that an error is noticed where or after it actually occurs, so
it's easy to see that there is a comma missing just before the "y".

Python 3.10 and 3.11 report:


  File "/home/hjp/tmp/foo", line 2
"x": (1 + 2 + 3)
  ^^
SyntaxError: invalid syntax. Perhaps you forgot a comma?
----

The error message is now a lot better, of course, but the fact that it
points at the expression *before* the error completely threw me. The
underlined expression is clearly not missing a comma, nor is there an
error before that. My real program was a bit longer of course, so I
checked the lines before that to see if I forgot to close any
parentheses. Took me some time to notice the missing comma *after* the
underlined expression.

Is this "clairvoyant" behaviour a side-effect of the new parser or was
that a deliberate decision?

hp

-- 
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | h...@hjp.at |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"


signature.asc
Description: PGP signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Module error

2023-05-27 Thread Thomas Passin

On 5/26/2023 8:30 PM, giuseppacef...@gmail.com wrote:

I have reinstalled python which reinstalls pip.  I have added the
path:'C:\sers\Giuseppa\AppData\Local\Packages\PythonSoftwareFoundation.Pytho
n.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\Scripts and still
get the error below. Could you help me with this please?

  


Traceback (most recent call last):

   File "C:\Users\Giuseppa\Documents\DataScience\PYTHON\Subsetting.py", line
11, in 

 import pandas as pd

ModuleNotFoundError: No module named 'pandas'
First of all, did you install Python from the Microsoft Store or using 
the Python installer from python.org?  The python.org installer does not 
use paths like that.  In case of problems, I think it would be 
preferable to install using the python.org installer.


Second, after an install of Python, you need to install any packages 
that are not standard Python modules and libraries.  Pandas is not part 
of a standard Python installation, so you would have to re-install it. 
Changing the Windows path has nothing to do with it.  Install pandas with


 -m pip install pandas --user

where  is the actual command that you use to run the version of 
Python you want to work with.


You can find out if your version of Python is running out of that 
LocalCache directory or not by running the following from the command 
line in a console:


 -c "import sys;print('\n'.join(sys.path))"

Again,  represents your actual "python" command.

You will get a display something like mine (I'm not showing the entire 
listing):


C:\Users\tom\AppData\Local\Programs\Python\Python311\python311.zip
C:\Users\tom\AppData\Local\Programs\Python\Python311\DLLs
C:\Users\tom\AppData\Local\Programs\Python\Python311\Lib
C:\Users\tom\AppData\Local\Programs\Python\Python311
C:\Users\tom\AppData\Roaming\Python\Python311\site-packages

You see that in my case, there is no LocalCache directory involved.  I 
installed using the installer from python.org.

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


Re: Module error

2023-05-26 Thread MRAB

On 2023-05-27 01:30, giuseppacef...@gmail.com wrote:

I have reinstalled python which reinstalls pip.  I have added the
path:'C:\sers\Giuseppa\AppData\Local\Packages\PythonSoftwareFoundation.Pytho
n.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\Scripts and still
get the error below. Could you help me with this please?

  


Traceback (most recent call last):

   File "C:\Users\Giuseppa\Documents\DataScience\PYTHON\Subsetting.py", line
11, in 

 import pandas as pd

ModuleNotFoundError: No module named 'pandas'


Have you tried re-installing pandas?
--
https://mail.python.org/mailman/listinfo/python-list


FW: Module error

2023-05-26 Thread giuseppacefalu
Directory of
C:\Users\Giuseppa\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.1
1_qbz5n2kfra8p0\LocalCache\local-packages\Python311\Scripts

 

05/26/2023  07:57 PM  .

05/26/2023  04:03 PM  ..

05/26/2023  04:07 PM   108,469 f2py.exe

05/26/2023  04:03 PM   108,497 normalizer.exe

05/26/2023  07:57 PM   108,474 pip.exe

05/26/2023  07:57 PM   108,474 pip3.11.exe

05/26/2023  07:57 PM   108,474 pip3.exe

   5 File(s)542,388 bytes

   2 Dir(s)  378,485,805,056 bytes free

 

From: giuseppacef...@gmail.com  
Sent: Friday, May 26, 2023 8:31 PM
To: python-list@python.org
Subject: Module error

 

I have reinstalled python which reinstalls pip.  I have added the
path:'C:\sers\Giuseppa\AppData\Local\Packages\PythonSoftwareFoundation.Pytho
n.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\Scripts and still
get the error below. Could you help me with this please?

 

Traceback (most recent call last):

  File "C:\Users\Giuseppa\Documents\DataScience\PYTHON\Subsetting.py", line
11, in 

import pandas as pd

ModuleNotFoundError: No module named 'pandas'

 

Thank you!No

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


FW: Module error

2023-05-26 Thread giuseppacefalu
The directory is empty after issuing the command: Directory of
C:\Users\Giuseppa\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.1
1_qbz5n2kfra8p0\LocalCache\local-packages\Python311\Scripts

 

05/26/2023  07:57 PM  .

05/26/2023  04:03 PM  ..

05/26/2023  04:07 PM   108,469 f2py.exe

05/26/2023  04:03 PM   108,497 normalizer.exe

05/26/2023  07:57 PM   108,474 pip.exe

05/26/2023  07:57 PM   108,474 pip3.11.exe

05/26/2023  07:57 PM   108,474 pip3.exe

   5 File(s)542,388 bytes

   2 Dir(s)  378,485,805,056 bytes free

 

From: giuseppacef...@gmail.com  
Sent: Friday, May 26, 2023 8:31 PM
To: python-list@python.org
Subject: Module error

 

I have reinstalled python which reinstalls pip.  I have added the
path:'C:\sers\Giuseppa\AppData\Local\Packages\PythonSoftwareFoundation.Pytho
n.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\Scripts and still
get the error below. Could you help me with this please?

 

Traceback (most recent call last):

  File "C:\Users\Giuseppa\Documents\DataScience\PYTHON\Subsetting.py", line
11, in 

import pandas as pd

ModuleNotFoundError: No module named 'pandas'

 

Thank you!No

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


Module error

2023-05-26 Thread giuseppacefalu
I have reinstalled python which reinstalls pip.  I have added the
path:'C:\sers\Giuseppa\AppData\Local\Packages\PythonSoftwareFoundation.Pytho
n.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\Scripts and still
get the error below. Could you help me with this please?

 

Traceback (most recent call last):

  File "C:\Users\Giuseppa\Documents\DataScience\PYTHON\Subsetting.py", line
11, in 

import pandas as pd

ModuleNotFoundError: No module named 'pandas'

 

Thank you!No

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


Re: Error installing packages or upgrading pip

2023-05-20 Thread Mats Wichmann

On 5/18/23 04:30, Test Only wrote:

Hi there, I hope you are in a great health

I am having a problem with python even though I uninstall and reinstall it
again multiple times


Ummm... there's usually not a great reason to do that. I know it's the 
traditional "Windows Way" of the past, but usually looking for actual 
solutions first is better than "reinstall because it might be 
corrupted". To put it in snarky terms: reach for the sledgehammer only 
once you know the use of a sledge is warranted.


Have you tried searching for this through a search engine?  A really 
quick try shows several hits, including some StackOverflow articles. 
There's no way for us to judge if any of those scenarios actually would 
apply to your case, so suggesting you take a look first.




the error I get when I try to upgrade or install a package for example

pip install requests

I get this error which I could not find a solution for



pip install requests
Requirement already satisfied: requests in
c:\users\uly\appdata\local\programs\python\python310\lib\site-packages\requests-2.30.0-py3.10.egg
(2.30.0)
WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None,
status=None)) after connection broken by 'ProtocolError('Connection
aborted.', FileNotFoundError(2, 'No such file or directory'))':
/simple/charset-normalizer/
WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None,
status=None)) after connection broken by 'ProtocolError('Connection
aborted.', FileNotFoundError(2, 'No such file or directory'))':
/simple/charset-normalizer/
WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None,
status=None)) after connection broken by 'ProtocolError('Connection
aborted.', FileNotFoundError(2, 'No such file or directory'))':
/simple/charset-normalizer/
WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None,
status=None)) after connection broken by 'ProtocolError('Connection
aborted.', FileNotFoundError(2, 'No such file or directory'))':
/simple/charset-normalizer/
WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None,
status=None)) after connection broken by 'ProtocolError('Connection
aborted.', FileNotFoundError(2, 'No such file or directory'))':
/simple/charset-normalizer/
WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None,
status=None)) after connection broken by 'ProtocolError('Connection
aborted.', FileNotFoundError(2, 'No such file or directory'))':
/simple/requests/
WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None,
status=None)) after connection broken by 'ProtocolError('Connection
aborted.', FileNotFoundError(2, 'No such file or directory'))':
/simple/requests/
WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None,
status=None)) after connection broken by 'ProtocolError('Connection
aborted.', FileNotFoundError(2, 'No such file or directory'))':
/simple/requests/
WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None,
status=None)) after connection broken by 'ProtocolError('Connection
aborted.', FileNotFoundError(2, 'No such file or directory'))':
/simple/requests/
WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None,
status=None)) after connection broken by 'ProtocolError('Connection
aborted.', FileNotFoundError(2, 'No such file or directory'))':
/simple/requests/
ERROR: Could not find a version that satisfies the requirement
charset_normalizer<4,>=2 (from requests) (from versions: none)
ERROR: No matching distribution found for charset_normalizer<4,>=2
WARNING: There was an error checking the latest version of pip.


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


Error installing packages or upgrading pip

2023-05-18 Thread Test Only
Hi there, I hope you are in a great health

I am having a problem with python even though I uninstall and reinstall it
again multiple times

the error I get when I try to upgrade or install a package for example

pip install requests

I get this error which I could not find a solution for



pip install requests
Requirement already satisfied: requests in
c:\users\uly\appdata\local\programs\python\python310\lib\site-packages\requests-2.30.0-py3.10.egg
(2.30.0)
WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None,
status=None)) after connection broken by 'ProtocolError('Connection
aborted.', FileNotFoundError(2, 'No such file or directory'))':
/simple/charset-normalizer/
WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None,
status=None)) after connection broken by 'ProtocolError('Connection
aborted.', FileNotFoundError(2, 'No such file or directory'))':
/simple/charset-normalizer/
WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None,
status=None)) after connection broken by 'ProtocolError('Connection
aborted.', FileNotFoundError(2, 'No such file or directory'))':
/simple/charset-normalizer/
WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None,
status=None)) after connection broken by 'ProtocolError('Connection
aborted.', FileNotFoundError(2, 'No such file or directory'))':
/simple/charset-normalizer/
WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None,
status=None)) after connection broken by 'ProtocolError('Connection
aborted.', FileNotFoundError(2, 'No such file or directory'))':
/simple/charset-normalizer/
WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None,
status=None)) after connection broken by 'ProtocolError('Connection
aborted.', FileNotFoundError(2, 'No such file or directory'))':
/simple/requests/
WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None,
status=None)) after connection broken by 'ProtocolError('Connection
aborted.', FileNotFoundError(2, 'No such file or directory'))':
/simple/requests/
WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None,
status=None)) after connection broken by 'ProtocolError('Connection
aborted.', FileNotFoundError(2, 'No such file or directory'))':
/simple/requests/
WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None,
status=None)) after connection broken by 'ProtocolError('Connection
aborted.', FileNotFoundError(2, 'No such file or directory'))':
/simple/requests/
WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None,
status=None)) after connection broken by 'ProtocolError('Connection
aborted.', FileNotFoundError(2, 'No such file or directory'))':
/simple/requests/
ERROR: Could not find a version that satisfies the requirement
charset_normalizer<4,>=2 (from requests) (from versions: none)
ERROR: No matching distribution found for charset_normalizer<4,>=2
WARNING: There was an error checking the latest version of pip.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Help on ImportError('Error: Reinit is forbidden')

2023-05-18 Thread Barry
 On 18 May 2023, at 13:56, Jason Qian  wrote:

 
 Hi Barry,
 void handleError(const char* msg)
 {
 ...
 PyErr_Fetch(, , );
 PyErr_NormalizeException(, , );

 PyObject* str_value = PyObject_Repr(pyExcValue);
 PyObject* pyExcValueStr = PyUnicode_AsEncodedString(str_value, "utf-8",
 "Error ~");
 const char *strErrValue = PyBytes_AS_STRING(pyExcValueStr);
 //where   strErrValue   = "ImportError('Error: Reinit is forbidden')"
 ...
 }
 What we imported is a Python file which import some pyd libraries.

   Please do not top post replies.
   Ok so assume the error is correct and hunt for the code that does the
   reimport.
   You may need to set break points in you C code to find tnw caller.
   Barry

 Thanks 
 Jason 
 On Thu, May 18, 2023 at 3:53 AM Barry <[1]ba...@barrys-emacs.org> wrote:

   > On 17 May 2023, at 20:35, Jason Qian via Python-list
   <[2]python-list@python.org> wrote:
   >
   >  Hi,
   >
   >   I Need some of your help.
   >
   > I have the following C code to import *Import python.*   It works
   99% of
   > the time, but sometimes  receives  "*ImportError('Error: Reinit is
   > forbidden')*". error.
   > **We run multiple instances of the app parallelly.
   >
   > *** Python version(3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51)
   [MSC
   > v.1914 64 bit (AMD64)]
   >
   > PyObject * importPythonModule(const char* pmodName)
   > {
   >    const char* errors = NULL;
   >     int nlen = strlen(pmodName);
   >     PyObject *pName = PyUnicode_DecodeUTF8(pmodName, nlen, errors);
   >     PyObject *pModule = *PyImport_Import*(pName);
   >     Py_DECREF(pName);
   >     if (pModule == NULL) {
   >     if (*PyErr_Occurred*()) {
   >            handleError("PyImport_Import()");
   >      }
   >   }
   > }
   > void handleError(const char* msg)
   > {
   >  ...
   >  "PyImport_Import() - ImportError('Error: Reinit is forbidden')"
   > }

   You do not seem to printing out msg, you have assumed it means reinit
   it seems.
   What does msg contain when it fails?

   Barry
   >
   >
   > Thanks
   > Jason
   > --
   > [3]https://mail.python.org/mailman/listinfo/python-list
   >

References

   Visible links
   1. mailto:ba...@barrys-emacs.org
   2. mailto:python-list@python.org
   3. https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Help on ImportError('Error: Reinit is forbidden')

2023-05-18 Thread Jason Qian via Python-list
Hi Barry,

void handleError(const char* msg)
{
...
PyErr_Fetch(, , );
PyErr_NormalizeException(, , );

PyObject* str_value = PyObject_Repr(pyExcValue);
PyObject* pyExcValueStr = PyUnicode_AsEncodedString(str_value, "utf-8",
"Error ~");
const char **strErrValue* = PyBytes_AS_STRING(pyExcValueStr);

//where   *strErrValue*   = "ImportError('Error: Reinit is forbidden')"
...
}

What we imported is a Python file which import some pyd libraries.


Thanks
Jason


On Thu, May 18, 2023 at 3:53 AM Barry  wrote:

>
>
> > On 17 May 2023, at 20:35, Jason Qian via Python-list <
> python-list@python.org> wrote:
> >
> >  Hi,
> >
> >   I Need some of your help.
> >
> > I have the following C code to import *Import python.*   It works 99% of
> > the time, but sometimes  receives  "*ImportError('Error: Reinit is
> > forbidden')*". error.
> > **We run multiple instances of the app parallelly.
> >
> > *** Python version(3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC
> > v.1914 64 bit (AMD64)]
> >
> > PyObject * importPythonModule(const char* pmodName)
> > {
> >const char* errors = NULL;
> > int nlen = strlen(pmodName);
> > PyObject *pName = PyUnicode_DecodeUTF8(pmodName, nlen, errors);
> > PyObject *pModule = *PyImport_Import*(pName);
> > Py_DECREF(pName);
> > if (pModule == NULL) {
> > if (*PyErr_Occurred*()) {
> >handleError("PyImport_Import()");
> >  }
> >   }
> > }
> > void handleError(const char* msg)
> > {
> >  ...
> >  "PyImport_Import() - ImportError('Error: Reinit is forbidden')"
> > }
>
> You do not seem to printing out msg, you have assumed it means reinit it
> seems.
> What does msg contain when it fails?
>
> Barry
> >
> >
> > Thanks
> > Jason
> > --
> > https://mail.python.org/mailman/listinfo/python-list
> >
>
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Help on ImportError('Error: Reinit is forbidden')

2023-05-18 Thread Barry


> On 17 May 2023, at 20:35, Jason Qian via Python-list  
> wrote:
> 
>  Hi,
> 
>   I Need some of your help.
> 
> I have the following C code to import *Import python.*   It works 99% of
> the time, but sometimes  receives  "*ImportError('Error: Reinit is
> forbidden')*". error.
> **We run multiple instances of the app parallelly.
> 
> *** Python version(3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC
> v.1914 64 bit (AMD64)]
> 
> PyObject * importPythonModule(const char* pmodName)
> {
>const char* errors = NULL;
> int nlen = strlen(pmodName);
> PyObject *pName = PyUnicode_DecodeUTF8(pmodName, nlen, errors);
> PyObject *pModule = *PyImport_Import*(pName);
> Py_DECREF(pName);
> if (pModule == NULL) {
> if (*PyErr_Occurred*()) {
>handleError("PyImport_Import()");
>  }
>   }
> }
> void handleError(const char* msg)
> {
>  ...
>  "PyImport_Import() - ImportError('Error: Reinit is forbidden')"
> }

You do not seem to printing out msg, you have assumed it means reinit it seems.
What does msg contain when it fails?

Barry
> 
> 
> Thanks
> Jason
> -- 
> https://mail.python.org/mailman/listinfo/python-list
> 

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


Help on ImportError('Error: Reinit is forbidden')

2023-05-17 Thread Jason Qian via Python-list
 Hi,

   I Need some of your help.

 I have the following C code to import *Import python.*   It works 99% of
the time, but sometimes  receives  "*ImportError('Error: Reinit is
forbidden')*". error.
 **We run multiple instances of the app parallelly.

*** Python version(3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC
v.1914 64 bit (AMD64)]

PyObject * importPythonModule(const char* pmodName)
{
const char* errors = NULL;
 int nlen = strlen(pmodName);
 PyObject *pName = PyUnicode_DecodeUTF8(pmodName, nlen, errors);
 PyObject *pModule = *PyImport_Import*(pName);
 Py_DECREF(pName);
 if (pModule == NULL) {
 if (*PyErr_Occurred*()) {
handleError("PyImport_Import()");
  }
   }
}
void handleError(const char* msg)
{
  ...
  "PyImport_Import() - ImportError('Error: Reinit is forbidden')"
}


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


Re: Pip Error

2023-05-17 Thread Thomas Passin

On 5/17/2023 10:54 AM, Aysu Mammadli wrote:

I encountered an error while attempting to install pip using the terminal.
The exact error message I received is:

"An error occurred during configuration: option use-feature: invalid
choice: '2020-resolver' (choose from 'fast-deps', 'truststore',
'no-binary-enable-wheel-cache')"

Here are the steps I followed and the context of my system:

Operating System: Windows 11 Python Version: 3.11.3 I executed the command
in the terminal to install pip, but it resulted in the aforementioned error
message. This error specifically references the '2020-resolver' choice
within the 'use-feature' option. An error occurred during configuration:
option use-feature: invalid choice: '2020-resolver' (choose from
'fast-deps', 'truststore', 'no-binary-enable-wheel-cache')

I have already attempted the following troubleshooting steps without
success:

Checked my internet connectivity to ensure it was stable and not causing
any issues. Verified that I have the latest version of pip installed, as
well as the latest version of Python. Tried using alternative commands,
such as using the --upgrade flag or specifying a specific pip version, but
the error persists. Looked for any recent system updates or changes that
could have caused this issue, but found none. I'm uncertain about the cause
of this error and how to resolve it. Any insights or suggestions would be
greatly appreciated.

Thank you in advance for your assistance!


I don't remember needing to install pip with Windows installations. I've 
got 3.11.3 on Windows 10. The installer and source distro for Windows 
both come with the ensurepip module:


 -m ensurepip

will install pip, where  is the name of the version of Python 
you want to run. I assume (but don't know for sure) that the standard 
installer runs ensurepip as part of its work.


How (and why) did you try to install it?

The error is coming from Lib\site-packages\pip\_internal\cli\parser.py. 
It's possible that some inconsistency has crept in between the allowed 
options and the ones that are given to the parser.


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


Re: Pip Error

2023-05-17 Thread Barry


> On 17 May 2023, at 17:26, Aysu Mammadli  wrote:
> 
> I encountered an error while attempting to install pip using the terminal.
> The exact error message I received is:
> 
> "An error occurred during configuration: option use-feature: invalid
> choice: '2020-resolver' (choose from 'fast-deps', 'truststore',
> 'no-binary-enable-wheel-cache')"
> 
> Here are the steps I followed and the context of my system:
> 
> Operating System: Windows 11 Python Version: 3.11.3 I executed the command
> in the terminal to install pip, but it resulted in the aforementioned error
> message. This error specifically references the '2020-resolver' choice
> within the 'use-feature' option. An error occurred during configuration:
> option use-feature: invalid choice: '2020-resolver' (choose from
> 'fast-deps', 'truststore', 'no-binary-enable-wheel-cache')
> 
> I have already attempted the following troubleshooting steps without
> success:
> 
> Checked my internet connectivity to ensure it was stable and not causing
> any issues. Verified that I have the latest version of pip installed, as
> well as the latest version of Python. Tried using alternative commands,
> such as using the --upgrade flag or specifying a specific pip version, but
> the error persists. Looked for any recent system updates or changes that
> could have caused this issue, but found none. I'm uncertain about the cause
> of this error and how to resolve it. Any insights or suggestions would be
> greatly appreciated.
> 
> Thank you in advance for your assistance!

Pip is installed by default with the python.org kits.
I am not sure what the situation is for the app store python.

Can you run python it self?

Does one of these work for you?

py -m pip
python -m pip

If so you have pip installed.

Barry


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

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


Pip Error

2023-05-17 Thread Aysu Mammadli
I encountered an error while attempting to install pip using the terminal.
The exact error message I received is:

"An error occurred during configuration: option use-feature: invalid
choice: '2020-resolver' (choose from 'fast-deps', 'truststore',
'no-binary-enable-wheel-cache')"

Here are the steps I followed and the context of my system:

Operating System: Windows 11 Python Version: 3.11.3 I executed the command
in the terminal to install pip, but it resulted in the aforementioned error
message. This error specifically references the '2020-resolver' choice
within the 'use-feature' option. An error occurred during configuration:
option use-feature: invalid choice: '2020-resolver' (choose from
'fast-deps', 'truststore', 'no-binary-enable-wheel-cache')

I have already attempted the following troubleshooting steps without
success:

Checked my internet connectivity to ensure it was stable and not causing
any issues. Verified that I have the latest version of pip installed, as
well as the latest version of Python. Tried using alternative commands,
such as using the --upgrade flag or specifying a specific pip version, but
the error persists. Looked for any recent system updates or changes that
could have caused this issue, but found none. I'm uncertain about the cause
of this error and how to resolve it. Any insights or suggestions would be
greatly appreciated.

Thank you in advance for your assistance!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python-pickle error

2023-05-09 Thread Tony Flury via Python-list

Charles,

by your own admission, you deleted your pkl file,

And your code doesn't write that pkl file (pickle.dumps(...) doesn't 
write a file it creates a new string and at no point will it write to 
the file :


What you need is this :

import pickle
number=2
my_pickled_object=pickle.dumps(number)
with open('file.pkl', 'w') as file:
file.write(my_pickled_object)
print("this is my pickled object",{my_pickled_object},)

del number # you can do this if you really want to test pickle.

with open('file.pkl', 'r') as file:
number=pickle.load(file)

my_unpickled_object=pickle.loads(my_pickled_object)
print("this is my unpickled object",{my_unpickled_object},)

Note :  that the whole point of the pickle format is that you don't need 
to open and write/read files in binary format.



On 19/04/2023 17:14, charles wiewiora wrote:

Hello,
I am experincing problems with the pickle moducle
the folowing code was working before,

import pickle
number=2
my_pickeld_object=pickle.dumps(number)
print("this is my pickled object",{my_pickeld_object},)
with open('file.pkl', 'rb') as file:
 number=pickle.load(file)
my_unpickeled_object=pickle.loads(my_pickeld_object)
print("this is my unpickeled object",{my_unpickeled_object},)

but now i get error

Traceback (most recent call last):
   File "C:\Users\lukwi\Desktop\python\tester2.py", line 5, in 
 with open('file.pkl', 'rb') as file:
FileNotFoundError: [Errno 2] No such file or directory: 'file.pkl'

im get this problem after this,
a .pkl came into my Python script files
i though this could be a spare file made from python becauce i was doing this 
first,

import pickle
number=2
my_pickeld_object=pickle.dumps(number)
print("this is my pickled object",{my_pickeld_object},)
with open('file.pkl', 'rb') as file:
 number=pickle.load(file)

so i stupidly deleted the file

do you know how to fix this?
i reinstalled it but it didn't work
this is on widnows and on version 3.11.3 on python

thank you


--
Anthony Flury
email : anthony.fl...@btinternet.com

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


Re: How to 'ignore' an error in Python?

2023-04-29 Thread Phu Sam
Unsubscribe

On Sat, Apr 29, 2023 at 7:05 PM Chris Angelico  wrote:

> On Sun, 30 Apr 2023 at 11:58, Chris Green  wrote:
> >
> > Chris Angelico  wrote:
> > > On Sat, 29 Apr 2023 at 14:27, Kushal Kumaran 
> wrote:
> > > >
> > > > On Fri, Apr 28 2023 at 04:55:41 PM, Chris Green  wrote:
> > > > > I'm sure I'm missing something obvious here but I can't see an
> elegant
> > > > > way to do this.  I want to create a directory, but if it exists
> it's
> > > > > not an error and the code should just continue.
> > > > >
> > > > > So, I have:-
> > > > >
> > > > > for dirname in listofdirs:
> > > > > try:
> > > > > os.mkdir(dirname)
> > > > >     except FileExistsError:
> > > > > # so what can I do here that says 'carry on regardless'
> > > > > except:
> > > > > # handle any other error, which is really an error
> > > > >
> > > > > # I want code here to execute whether or not dirname exists
> > > > >
> > > > >
> > > > > Do I really have to use a finally: block?  It feels rather clumsy.
> > > > >
> > > > > I suppose I could test if the directory exists before the
> os.mkdir()
> > > > > but again that feels a bit clumsy somehow.
> > > > >
> > > > > I suppose also I could use os.mkdirs() with exist_ok=True but again
> > > > > that feels vaguely wrong somehow.
> > > > >
> > > >
> > > > Why does exist_ok=True feel wrong to you?  This is exactly what it is
> > > > there for.
> > > >
> > >
> > > Using mkdirs when you only want to make one is inviting problems of
> > > being subtly wrong, where it creates too many levels of directory.
> > > Personally, I would just do:
> > >
> > > try: os.mkdir(dirname)
> > > except FileExistsError: pass
> > >
> > > and not try to handle anything else at all.
> > >
> > Yes, OP here, that seems to me to be the 'right' way to do it.
> > Basically I hadn't realised the effect of pass in a try block and
> > that's why I asked the question originally.
> >
>
> There's two points to note here. "pass" doesn't do anything
> whatsoever; it's only there to prevent the syntactic problem of having
> nothing in that block. This will also suppress the error:
>
> try:
> os.mkdir(dirname)
> except FileExistsError:
> dummy = "ignore"
>
> The second thing is that, as soon as you have an "except" clause that
> matches the error, that's it - it stops there. The error is considered
> handled at that point. If that's NOT what you want, you have a few
> options. Firstly, you can simply not have a matching except clause.
> That's why we like to be as precise as possible with our catching;
> every other type of problem will be left uncaught. Secondly, you can
> use "try/finally" to add code that happens as the exception flies by,
> but doesn't catch it (it also happens at the end of the block for
> other reasons). And thirdly, you can reraise the exception:
>
> try:
> os.mkdir(dirname)
> except FileExistsError:
> print("Hey, that one already exists!")
> raise
>
> That's going to keep the exception going just as if it hadn't been
> caught, but with the additional handling.
>
> But if you don't do any of those things, the exception is deemed to be
> handled, and it goes no further.
>
> ChrisA
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to 'ignore' an error in Python?

2023-04-29 Thread Chris Angelico
On Sun, 30 Apr 2023 at 12:02, jak  wrote:
>
> Chris Angelico ha scritto:
> > Using mkdirs when you only want to make one is inviting problems of
> > being subtly wrong, where it creates too many levels of directory.
> > Personally, I would just do:
>
>
> Maybe I only say this because it has happened to me too many times but
> before ignoring the error in the 'except' branch, I would make sure that
> if the name exists it is a folder and not a file.
>

That's a fair consideration, although the other way to handle that is
to allow other operations to fail later (if someone creates a file
called "logs" and then you try to create "logs/2023-04-30.txt", you
get an error at that point). I have also known situations where this
is a deliberate way to suppress something (like a cache or log
directory).

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


Re: How to 'ignore' an error in Python?

2023-04-29 Thread jak

Stefan Ram ha scritto:

jak  writes:

Maybe I only say this because it has happened to me too many times but
before ignoring the error in the 'except' branch, I would make sure that
if the name exists it is a folder and not a file.


   If the name exists and it is a file's name, this will be detected
   by "mkdir( exist_ok=True )", and an object will be raised. Such
   an object, indeed, usually should /not/ be ignored by the caller.
   But there is no reason to deviate from the EAFP path.





Maybe I expressed myself badly but I didn't mean to propose alternatives
to the EAFP way but just to evaluate the possibility that it is not a
folder.
--
https://mail.python.org/mailman/listinfo/python-list


Re: How to 'ignore' an error in Python?

2023-04-29 Thread Chris Angelico
On Sun, 30 Apr 2023 at 11:58, Chris Green  wrote:
>
> Chris Angelico  wrote:
> > On Sat, 29 Apr 2023 at 14:27, Kushal Kumaran  wrote:
> > >
> > > On Fri, Apr 28 2023 at 04:55:41 PM, Chris Green  wrote:
> > > > I'm sure I'm missing something obvious here but I can't see an elegant
> > > > way to do this.  I want to create a directory, but if it exists it's
> > > > not an error and the code should just continue.
> > > >
> > > > So, I have:-
> > > >
> > > > for dirname in listofdirs:
> > > > try:
> > > > os.mkdir(dirname)
> > > > except FileExistsError:
> > > > # so what can I do here that says 'carry on regardless'
> > > > except:
> > > > # handle any other error, which is really an error
> > > >
> > > > # I want code here to execute whether or not dirname exists
> > > >
> > > >
> > > > Do I really have to use a finally: block?  It feels rather clumsy.
> > > >
> > > > I suppose I could test if the directory exists before the os.mkdir()
> > > > but again that feels a bit clumsy somehow.
> > > >
> > > > I suppose also I could use os.mkdirs() with exist_ok=True but again
> > > > that feels vaguely wrong somehow.
> > > >
> > >
> > > Why does exist_ok=True feel wrong to you?  This is exactly what it is
> > > there for.
> > >
> >
> > Using mkdirs when you only want to make one is inviting problems of
> > being subtly wrong, where it creates too many levels of directory.
> > Personally, I would just do:
> >
> > try: os.mkdir(dirname)
> > except FileExistsError: pass
> >
> > and not try to handle anything else at all.
> >
> Yes, OP here, that seems to me to be the 'right' way to do it.
> Basically I hadn't realised the effect of pass in a try block and
> that's why I asked the question originally.
>

There's two points to note here. "pass" doesn't do anything
whatsoever; it's only there to prevent the syntactic problem of having
nothing in that block. This will also suppress the error:

try:
os.mkdir(dirname)
except FileExistsError:
dummy = "ignore"

The second thing is that, as soon as you have an "except" clause that
matches the error, that's it - it stops there. The error is considered
handled at that point. If that's NOT what you want, you have a few
options. Firstly, you can simply not have a matching except clause.
That's why we like to be as precise as possible with our catching;
every other type of problem will be left uncaught. Secondly, you can
use "try/finally" to add code that happens as the exception flies by,
but doesn't catch it (it also happens at the end of the block for
other reasons). And thirdly, you can reraise the exception:

try:
os.mkdir(dirname)
except FileExistsError:
print("Hey, that one already exists!")
raise

That's going to keep the exception going just as if it hadn't been
caught, but with the additional handling.

But if you don't do any of those things, the exception is deemed to be
handled, and it goes no further.

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


Re: How to 'ignore' an error in Python?

2023-04-29 Thread jak

Chris Angelico ha scritto:

Using mkdirs when you only want to make one is inviting problems of
being subtly wrong, where it creates too many levels of directory.
Personally, I would just do:



Maybe I only say this because it has happened to me too many times but
before ignoring the error in the 'except' branch, I would make sure that
if the name exists it is a folder and not a file.

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


Re: How to 'ignore' an error in Python?

2023-04-29 Thread Chris Green
Kushal Kumaran  wrote:
> On Fri, Apr 28 2023 at 04:55:41 PM, Chris Green  wrote:
> > I'm sure I'm missing something obvious here but I can't see an elegant
> > way to do this.  I want to create a directory, but if it exists it's
> > not an error and the code should just continue.
> >
> > So, I have:-
> >
> > for dirname in listofdirs:
> > try:
> > os.mkdir(dirname)
> > except FileExistsError:
> > # so what can I do here that says 'carry on regardless'
> >     except:
> > # handle any other error, which is really an error
> >
> > # I want code here to execute whether or not dirname exists
> >
> >
> > Do I really have to use a finally: block?  It feels rather clumsy.
> >
> > I suppose I could test if the directory exists before the os.mkdir()
> > but again that feels a bit clumsy somehow.
> >
> > I suppose also I could use os.mkdirs() with exist_ok=True but again
> > that feels vaguely wrong somehow.
> >
> 
> Why does exist_ok=True feel wrong to you?  This is exactly what it is
> there for.
> 
It was rather using os.mekedirs() to create a single directory that
seemed wrong.  If os.mkdir() had exist_ok=True than that would have
been the obvious way to do it.

-- 
Chris Green
·
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to 'ignore' an error in Python?

2023-04-29 Thread Chris Green
Chris Angelico  wrote:
> On Sat, 29 Apr 2023 at 14:27, Kushal Kumaran  wrote:
> >
> > On Fri, Apr 28 2023 at 04:55:41 PM, Chris Green  wrote:
> > > I'm sure I'm missing something obvious here but I can't see an elegant
> > > way to do this.  I want to create a directory, but if it exists it's
> > > not an error and the code should just continue.
> > >
> > > So, I have:-
> > >
> > > for dirname in listofdirs:
> > > try:
> > > os.mkdir(dirname)
> > > except FileExistsError:
> > > # so what can I do here that says 'carry on regardless'
> > > except:
> > > # handle any other error, which is really an error
> > >
> > > # I want code here to execute whether or not dirname exists
> > >
> > >
> > > Do I really have to use a finally: block?  It feels rather clumsy.
> > >
> > > I suppose I could test if the directory exists before the os.mkdir()
> > > but again that feels a bit clumsy somehow.
> > >
> > > I suppose also I could use os.mkdirs() with exist_ok=True but again
> > > that feels vaguely wrong somehow.
> > >
> >
> > Why does exist_ok=True feel wrong to you?  This is exactly what it is
> > there for.
> >
> 
> Using mkdirs when you only want to make one is inviting problems of
> being subtly wrong, where it creates too many levels of directory.
> Personally, I would just do:
> 
> try: os.mkdir(dirname)
> except FileExistsError: pass
> 
> and not try to handle anything else at all.
> 
Yes, OP here, that seems to me to be the 'right' way to do it.
Basically I hadn't realised the effect of pass in a try block and
that's why I asked the question originally.

-- 
Chris Green
·
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to 'ignore' an error in Python?

2023-04-29 Thread Greg Ewing via Python-list

On 30/04/23 2:43 am, jak wrote:

Maybe I expressed myself badly but I didn't mean to propose alternatives
to the EAFP way but just to evaluate the possibility that it is not a
folder.


If it's not a folder, you'll find out when the next thing you
try to do to it fails.

You could check for it earlier, but there's still the possibility
of a race condition -- someone could delete the folder and replace
it with a file in the meantime. Or just delete it and not replace
it with anything. So you need to be prepared to deal with failures
at any point.

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


RE: How to 'ignore' an error in Python?

2023-04-29 Thread avi.e.gross
I get a tad suspicious when someone keeps telling us every offered solution
does not feel right. Perhaps they are not using the right programming
language as clearly they are not willing to work with it as it is not as it
should be.

 After all the back and forth, there are several choices including accepting
whatever method is least annoying to them, or rolling their own.

Create a function with a name like do_it_my_way_or_the_highway() that uses
any acceptable method but completely hides the implementation details from
your code. One way might be to get the source code and copy it under your
own name and modify it so the default is to do what you want. It can even be
as simple as a small wrapper that forwards to the original function with a
keyword set by default.

After all, this does seem to be a bit like what you are asking for. A way to
call your functionality that does it the way you insist it should have been
designed, never mind that many others are happy with it as it is and use the
techniques mentioned at other times.

But I do have sympathy. I have seen lots of simple-minded code that seems to
cleanly and elegantly solve a problem as long as all the ducks are just-so.
Then someone points out that the code may break if it is called with some
other type than expected or if it tries to divide by zero or if something
else changes a variable between the time you looked at it and the time you
update it and so on. Next thing you know, your code grows (even
exponentially) to try to handle all these conditions and includes lots of
nested IF statements and all kinds of TRY statements and slows down and is
hard to read or even think about. And to make it worse, people ask for your
formerly simple function to become a Swiss army knife that accepts oodles of
keyword arguments that alter various aspects of the behavior!

So, yes, it can feel wrong. But so what? Sometimes you can find ways to
reduce the complexity and sometimes you simply create a few accessory
functions you can use that tame the complexity a bit. But almost any complex
program in any language can require a loss of simplicity.


-Original Message-
From: Python-list  On
Behalf Of Kushal Kumaran
Sent: Saturday, April 29, 2023 12:19 AM
To: python-list@python.org
Subject: Re: How to 'ignore' an error in Python?

On Fri, Apr 28 2023 at 04:55:41 PM, Chris Green  wrote:
> I'm sure I'm missing something obvious here but I can't see an elegant
> way to do this.  I want to create a directory, but if it exists it's
> not an error and the code should just continue.
>
> So, I have:-
>
> for dirname in listofdirs:
> try:
> os.mkdir(dirname)
> except FileExistsError:
> # so what can I do here that says 'carry on regardless'
> except:
> # handle any other error, which is really an error
>
> # I want code here to execute whether or not dirname exists
>
>
> Do I really have to use a finally: block?  It feels rather clumsy.
>
> I suppose I could test if the directory exists before the os.mkdir()
> but again that feels a bit clumsy somehow.
>
> I suppose also I could use os.mkdirs() with exist_ok=True but again
> that feels vaguely wrong somehow.
>

Why does exist_ok=True feel wrong to you?  This is exactly what it is
there for.

-- 
regards,
kushal
-- 
https://mail.python.org/mailman/listinfo/python-list

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


Re: How to 'ignore' an error in Python?

2023-04-28 Thread Chris Angelico
On Sat, 29 Apr 2023 at 14:27, Kushal Kumaran  wrote:
>
> On Fri, Apr 28 2023 at 04:55:41 PM, Chris Green  wrote:
> > I'm sure I'm missing something obvious here but I can't see an elegant
> > way to do this.  I want to create a directory, but if it exists it's
> > not an error and the code should just continue.
> >
> > So, I have:-
> >
> > for dirname in listofdirs:
> > try:
> > os.mkdir(dirname)
> > except FileExistsError:
> > # so what can I do here that says 'carry on regardless'
> > except:
> > # handle any other error, which is really an error
> >
> > # I want code here to execute whether or not dirname exists
> >
> >
> > Do I really have to use a finally: block?  It feels rather clumsy.
> >
> > I suppose I could test if the directory exists before the os.mkdir()
> > but again that feels a bit clumsy somehow.
> >
> > I suppose also I could use os.mkdirs() with exist_ok=True but again
> > that feels vaguely wrong somehow.
> >
>
> Why does exist_ok=True feel wrong to you?  This is exactly what it is
> there for.
>

Using mkdirs when you only want to make one is inviting problems of
being subtly wrong, where it creates too many levels of directory.
Personally, I would just do:

try: os.mkdir(dirname)
except FileExistsError: pass

and not try to handle anything else at all.

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


Re: How to 'ignore' an error in Python?

2023-04-28 Thread Kushal Kumaran
On Fri, Apr 28 2023 at 04:55:41 PM, Chris Green  wrote:
> I'm sure I'm missing something obvious here but I can't see an elegant
> way to do this.  I want to create a directory, but if it exists it's
> not an error and the code should just continue.
>
> So, I have:-
>
> for dirname in listofdirs:
> try:
> os.mkdir(dirname)
> except FileExistsError:
> # so what can I do here that says 'carry on regardless'
> except:
> # handle any other error, which is really an error
>
> # I want code here to execute whether or not dirname exists
>
>
> Do I really have to use a finally: block?  It feels rather clumsy.
>
> I suppose I could test if the directory exists before the os.mkdir()
> but again that feels a bit clumsy somehow.
>
> I suppose also I could use os.mkdirs() with exist_ok=True but again
> that feels vaguely wrong somehow.
>

Why does exist_ok=True feel wrong to you?  This is exactly what it is
there for.

-- 
regards,
kushal
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to 'ignore' an error in Python?

2023-04-28 Thread Cameron Simpson

On 28Apr2023 10:39, Mats Wichmann  wrote:

For this specific case, you can use os.makedirs:
os.makedirs(dirname, exist_ok=True)


I'm not a great fan of makedirs because it will make all the missing 
components, not just the final one. So as an example, if you've got a 
NAS mounted backup area at eg:


/mnt/nas/backups/the-thing/backups-subdir

and your config file has this mistyped as:

/mn/nas/backups/the-thing/backups-subdir

and makedirs is used, then it will make the backup area on eg the root 
drive where there's no room. (I'm looking at you, Docker, grr). There 
are plenty of similar situations.


Because of this I usually am prepared to make a missing final component 
with mkdir(), but not a potentially deep path with makedirs().


Cheers,
Cameron Simpson 
--
https://mail.python.org/mailman/listinfo/python-list


Re: How to 'ignore' an error in Python?

2023-04-28 Thread Cameron Simpson

On 28Apr2023 16:55, Chris Green  wrote:

   for dirname in listofdirs:
   try:
   os.mkdir(dirname)
   except FileExistsError:
   # so what can I do here that says 'carry on regardless'
   except:
   # handle any other error, which is really an error

   # I want code here to execute whether or not dirname exists

Do I really have to use a finally: block?  It feels rather clumsy.


You don't. Provided the "handle any other error" part reraises or does a 
break/continue, so as to skip the bottom of the loop body.


ok = true
for dirname in listofdirs:
try:
os.mkdir(dirname)
except FileExistsError:
pass
except Exception as e:
warning("mkdir(%r): %s", dirname, e)
ok = False
continue
rest of the loop body ...
if not ok:
... not all directories made ...

2 notes on the above:
- catching Exception, not a bare except (which catches a rather broader 
  suit of things)

- reporting the other exception

Cheers,
Cameron Simpson 
--
https://mail.python.org/mailman/listinfo/python-list


Re: How to 'ignore' an error in Python?

2023-04-28 Thread Mats Wichmann

On 4/28/23 11:05, MRAB wrote:

On 2023-04-28 16:55, Chris Green wrote:

I'm sure I'm missing something obvious here but I can't see an elegant
way to do this.  I want to create a directory, but if it exists it's
not an error and the code should just continue.

So, I have:-

 for dirname in listofdirs:
 try:
 os.mkdir(dirname)
 except FileExistsError:
 # so what can I do here that says 'carry on regardless'
 except:
 # handle any other error, which is really an error



I'd do this:

     from contextlib import suppress

     for dirname in listofdirs:
     with suppress(FileExistsError):
     os.mkdir(dirname)


I'm fond of that approach too, though you can't use if it you really 
wanted to do the


  except:
  # handle any other error, which is really an error

If you're okay letting Python just raise whatever other error it found, 
then great!



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


Re: How to 'ignore' an error in Python?

2023-04-28 Thread MRAB

On 2023-04-28 16:55, Chris Green wrote:

I'm sure I'm missing something obvious here but I can't see an elegant
way to do this.  I want to create a directory, but if it exists it's
not an error and the code should just continue.

So, I have:-

 for dirname in listofdirs:
 try:
 os.mkdir(dirname)
 except FileExistsError:
 # so what can I do here that says 'carry on regardless'
 except:
 # handle any other error, which is really an error

 # I want code here to execute whether or not dirname exists


Do I really have to use a finally: block?  It feels rather clumsy.

I suppose I could test if the directory exists before the os.mkdir()
but again that feels a bit clumsy somehow.

I suppose also I could use os.mkdirs() with exist_ok=True but again
that feels vaguely wrong somehow.


I'd do this:

from contextlib import suppress

for dirname in listofdirs:
with suppress(FileExistsError):
os.mkdir(dirname)

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


Re: How to 'ignore' an error in Python?

2023-04-28 Thread Mats Wichmann

On 4/28/23 09:55, Chris Green wrote:

I'm sure I'm missing something obvious here but I can't see an elegant
way to do this.  I want to create a directory, but if it exists it's
not an error and the code should just continue.

So, I have:-

 for dirname in listofdirs:
 try:
 os.mkdir(dirname)
 except FileExistsError:
 # so what can I do here that says 'carry on regardless'
 except:
 # handle any other error, which is really an error

 # I want code here to execute whether or not dirname exists


Do I really have to use a finally: block?  It feels rather clumsy.


For this specific case, you can use os.makedirs:

os.makedirs(dirname, exist_ok=True)

The mkdir in pathlib also takes the exist_ok flag


As to the way you asked the question, you can use "pass" or the ellipses 
for the "# so what can I do here"



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


How to 'ignore' an error in Python?

2023-04-28 Thread Chris Green
I'm sure I'm missing something obvious here but I can't see an elegant
way to do this.  I want to create a directory, but if it exists it's
not an error and the code should just continue.

So, I have:-

for dirname in listofdirs:
try:
os.mkdir(dirname)
except FileExistsError:
# so what can I do here that says 'carry on regardless'
except:
# handle any other error, which is really an error

# I want code here to execute whether or not dirname exists


Do I really have to use a finally: block?  It feels rather clumsy.

I suppose I could test if the directory exists before the os.mkdir()
but again that feels a bit clumsy somehow.

I suppose also I could use os.mkdirs() with exist_ok=True but again
that feels vaguely wrong somehow.


-- 
Chris Green
·
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python-pickle error

2023-04-19 Thread Thomas Passin

On 4/19/2023 12:14 PM, charles wiewiora wrote:

Hello,
I am experincing problems with the pickle moducle
the folowing code was working before,

import pickle
number=2
my_pickeld_object=pickle.dumps(number)
print("this is my pickled object",{my_pickeld_object},)
with open('file.pkl', 'rb') as file:
 number=pickle.load(file)
my_unpickeled_object=pickle.loads(my_pickeld_object)
print("this is my unpickeled object",{my_unpickeled_object},)

but now i get error

Traceback (most recent call last):
   File "C:\Users\lukwi\Desktop\python\tester2.py", line 5, in 
 with open('file.pkl', 'rb') as file:
FileNotFoundError: [Errno 2] No such file or directory: 'file.pkl'


That's because you haven't saved anything to a file named "file.pkl". If 
this code seemed to work in the past, it may have been because there was 
a file named "file.pkl" left over from some previous experiment.  But 
it's not there now, and even if it were it would not contain your 
current pickled object.


Take a look at .load() and .dump() (instead of .loads() and .dumps(). 
Maybe they will do what you want a little easier.



im get this problem after this,
a .pkl came into my Python script files
i though this could be a spare file made from python becauce i was doing this 
first,

import pickle
number=2
my_pickeld_object=pickle.dumps(number)
print("this is my pickled object",{my_pickeld_object},)
with open('file.pkl', 'rb') as file:
 number=pickle.load(file)

so i stupidly deleted the file

do you know how to fix this?
i reinstalled it but it didn't work
this is on widnows and on version 3.11.3 on python

thank you


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


Python-pickle error

2023-04-19 Thread charles wiewiora
Hello,
I am experincing problems with the pickle moducle
the folowing code was working before,

import pickle
number=2
my_pickeld_object=pickle.dumps(number)
print("this is my pickled object",{my_pickeld_object},)
with open('file.pkl', 'rb') as file:
number=pickle.load(file)
my_unpickeled_object=pickle.loads(my_pickeld_object)
print("this is my unpickeled object",{my_unpickeled_object},)

but now i get error

Traceback (most recent call last):
  File "C:\Users\lukwi\Desktop\python\tester2.py", line 5, in 
with open('file.pkl', 'rb') as file:
FileNotFoundError: [Errno 2] No such file or directory: 'file.pkl'

im get this problem after this,
a .pkl came into my Python script files
i though this could be a spare file made from python becauce i was doing this 
first,

import pickle
number=2
my_pickeld_object=pickle.dumps(number)
print("this is my pickled object",{my_pickeld_object},)
with open('file.pkl', 'rb') as file:
number=pickle.load(file)

so i stupidly deleted the file

do you know how to fix this?
i reinstalled it but it didn't work
this is on widnows and on version 3.11.3 on python

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


pip upgrade error

2023-04-17 Thread 羅 中勇


When I using pip list, it tells me there is a new release of pip is available, 
but I got these error messages when I upgrading pip. I don’t know what happened 
it is.
PS C:\Users\USER> pip --version pip
pip 23.0.1 from 
C:\Users\USER\AppData\Roaming\Python\Python310\site-packages\pip (python 3.10)
PS C:\Users\USER> python.exe -m pip install --upgrade pip
Requirement already satisfied: pip in 
c:\users\user\appdata\roaming\python\python310\site-packages (23.0.1)
Collecting pip
  Using cached pip-23.1-py3-none-any.whl (2.1 MB)
Installing collected packages: pip
  Attempting uninstall: pip
Found existing installation: pip 23.0.1
Uninstalling pip-23.0.1:
  Successfully uninstalled pip-23.0.1
  Rolling back uninstall of pip
  Moving to c:\users\user\appdata\roaming\python\python310\scripts\pip.exe
   from C:\Users\USER\AppData\Local\Temp\pip-uninstall-byh29tpt\pip.exe
  Moving to c:\users\user\appdata\roaming\python\python310\scripts\pip3.10.exe
   from C:\Users\USER\AppData\Local\Temp\pip-uninstall-byh29tpt\pip3.10.exe
  Moving to c:\users\user\appdata\roaming\python\python310\scripts\pip3.exe
   from C:\Users\USER\AppData\Local\Temp\pip-uninstall-byh29tpt\pip3.exe
  Moving to 
c:\users\user\appdata\roaming\python\python310\site-packages\pip-23.0.1.dist-info\
   from 
C:\Users\USER\AppData\Roaming\Python\Python310\site-packages\~ip-23.0.1.dist-info
  Moving to c:\users\user\appdata\roaming\python\python310\site-packages\pip\
   from C:\Users\USER\AppData\Roaming\Python\Python310\site-packages\~ip
ERROR: Exception:
Traceback (most recent call last):
  File 
"C:\Users\USER\AppData\Roaming\Python\Python310\site-packages\pip\_internal\cli\base_command.py",
 line 160, in exc_logging_wrapper
status = run_func(*args)
  File 
"C:\Users\USER\AppData\Roaming\Python\Python310\site-packages\pip\_internal\cli\req_command.py",
 line 247, in wrapper
return func(self, options, args)
  File 
"C:\Users\USER\AppData\Roaming\Python\Python310\site-packages\pip\_internal\commands\install.py",
 line 507, in run
installed = install_given_reqs(
  File 
"C:\Users\USER\AppData\Roaming\Python\Python310\site-packages\pip\_internal\req\__init__.py",
 line 73, in install_given_reqs
requirement.install(
  File 
"C:\Users\USER\AppData\Roaming\Python\Python310\site-packages\pip\_internal\req\req_install.py",
 line 796, in install
install_wheel(
  File 
"C:\Users\USER\AppData\Roaming\Python\Python310\site-packages\pip\_internal\operations\install\wheel.py",
 line 729, in install_wheel
_install_wheel(
  File 
"C:\Users\USER\AppData\Roaming\Python\Python310\site-packages\pip\_internal\operations\install\wheel.py",
 line 646, in _install_wheel
generated_console_scripts = maker.make_multiple(scripts_to_generate)
  File 
"C:\Users\USER\AppData\Roaming\Python\Python310\site-packages\pip\_vendor\distlib\scripts.py",
 line 436, in make_multiple
filenames.extend(self.make(specification, options))
  File 
"C:\Users\USER\AppData\Roaming\Python\Python310\site-packages\pip\_internal\operations\install\wheel.py",
 line 427, in make
return super().make(specification, options)
  File 
"C:\Users\USER\AppData\Roaming\Python\Python310\site-packages\pip\_vendor\distlib\scripts.py",
 line 425, in make
self._make_script(entry, filenames, options=options)
  File 
"C:\Users\USER\AppData\Roaming\Python\Python310\site-packages\pip\_vendor\distlib\scripts.py",
 line 325, in _make_script
self._write_script(scriptnames, shebang, script, filenames, ext)
  File 
"C:\Users\USER\AppData\Roaming\Python\Python310\site-packages\pip\_vendor\distlib\scripts.py",
 line 249, in _write_script
launcher = self._get_launcher('t')
  File 
"C:\Users\USER\AppData\Roaming\Python\Python310\site-packages\pip\_vendor\distlib\scripts.py",
 line 404, in _get_launcher
raise ValueError(msg)
ValueError: Unable to find resource t64.exe in package pip._vendor.distlib

[notice] A new release of pip is available: 23.0.1 -> 23.1
[notice] To update, run: python.exe -m pip install --upgrade pip
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python 2.7 range Function provokes a Memory Error

2023-03-06 Thread Chris Angelico
On Tue, 7 Mar 2023 at 16:53, Stephen Tucker  wrote:
>
> Hi again,
>
> I tried xrange, but I got an error telling me that my integer was too big
> for a C long.
>
> Clearly, xrange in Py2 is not capable of dealing with Python (that is,
> possibly very long) integers.

That's because Py2 has two different integer types, int and long.

> I am raising this because,
>
> (a) IF xrange in Py3 is a simple "port" from Py2, then it won't handle
> Python integers either.
>
> AND
>
> (b) IF xrange in Py3 is intended to be equivalent to range (which, even in
> Py2, does handle Python integers)
>
> THEN
>
> It could be argued that xrange in Py3 needs some attention from the
> developer(s).


Why don't you actually try Python 3 instead of making assumptions
based on the state of Python from more than a decade ago?

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


Re: Python 2.7 range Function provokes a Memory Error

2023-03-06 Thread Stephen Tucker
Hi again,

I tried xrange, but I got an error telling me that my integer was too big
for a C long.

Clearly, xrange in Py2 is not capable of dealing with Python (that is,
possibly very long) integers.

I am raising this because,

(a) IF xrange in Py3 is a simple "port" from Py2, then it won't handle
Python integers either.

AND

(b) IF xrange in Py3 is intended to be equivalent to range (which, even in
Py2, does handle Python integers)

THEN

It could be argued that xrange in Py3 needs some attention from the
developer(s).

Stephen Tucker.


On Thu, Mar 2, 2023 at 6:24 PM Jon Ribbens via Python-list <
python-list@python.org> wrote:

> On 2023-03-02, Stephen Tucker  wrote:
> > The range function in Python 2.7 (and yes, I know that it is now
> > superseded), provokes a Memory Error when asked to deiliver a very long
> > list of values.
> >
> > I assume that this is because the function produces a list which it then
> > iterates through.
> >
> > 1. Does the  range  function in Python 3.x behave the same way?
>
> No, in Python 3 it is an iterator which produces the next number in the
> sequence each time.
>
> > 2. Is there any equivalent way that behaves more like a  for loop (that
> is,
> > without producing a list)?
>
> Yes, 'xrange' in Python 2 behaves like 'range' in Python 3.
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python 2.7 range Function provokes a Memory Error

2023-03-02 Thread Jon Ribbens via Python-list
On 2023-03-02, Stephen Tucker  wrote:
> The range function in Python 2.7 (and yes, I know that it is now
> superseded), provokes a Memory Error when asked to deiliver a very long
> list of values.
>
> I assume that this is because the function produces a list which it then
> iterates through.
>
> 1. Does the  range  function in Python 3.x behave the same way?

No, in Python 3 it is an iterator which produces the next number in the
sequence each time.

> 2. Is there any equivalent way that behaves more like a  for loop (that is,
> without producing a list)?

Yes, 'xrange' in Python 2 behaves like 'range' in Python 3.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python 2.7 range Function provokes a Memory Error

2023-03-02 Thread Chris Angelico
On Thu, 2 Mar 2023 at 22:27, Stephen Tucker  wrote:
>
> Hi,
>
> The range function in Python 2.7 (and yes, I know that it is now
> superseded), provokes a Memory Error when asked to deiliver a very long
> list of values.
>
> I assume that this is because the function produces a list which it then
> iterates through.
>
> 1. Does the  range  function in Python 3.x behave the same way?

No, but list(range(x)) might, for the same reason. In Py2, range
returns a list, which means it needs a gigantic collection of integer
objects. In Py3, a range object just defines its start/stop/step, but
if you call list() on it, you get the same sort of

> 2. Is there any equivalent way that behaves more like a  for loop (that is,
> without producing a list)?
>
> To get round the problem I have written my own software that is used in a
> for  loop.

xrange is an iterator in Py2, so that's the easiest way to handle it.
Obviously migrating to Py3 would be the best way, but in the meantime,
xrange will probably do what you need.

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


Re: Python 2.7 range Function provokes a Memory Error

2023-03-02 Thread 2QdxY4RzWzUUiLuE
On 2023-03-02 at 11:25:49 +,
Stephen Tucker  wrote:

> The range function in Python 2.7 (and yes, I know that it is now
> superseded), provokes a Memory Error when asked to deiliver a very long
> list of values.
> 
> I assume that this is because the function produces a list which it then
> iterates through.
> 
> 1. Does the  range  function in Python 3.x behave the same way?

No.

> 2. Is there any equivalent way that behaves more like a  for loop (that is,
> without producing a list)?

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


Python 2.7 range Function provokes a Memory Error

2023-03-02 Thread Stephen Tucker
Hi,

The range function in Python 2.7 (and yes, I know that it is now
superseded), provokes a Memory Error when asked to deiliver a very long
list of values.

I assume that this is because the function produces a list which it then
iterates through.

1. Does the  range  function in Python 3.x behave the same way?

2. Is there any equivalent way that behaves more like a  for loop (that is,
without producing a list)?

To get round the problem I have written my own software that is used in a
for  loop.

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


Re: Why doesn't Python (error msg) tell me WHAT the actual (arg) values are ?

2023-02-25 Thread Weatherby,Gerard
“So the case where the assumption fails may not be easily
reproducable and the more information you can get post-mortem the
better”

That’s true for rare corner cases or esoteric race conditions. Usually, when I 
see asserts it's just because I was just plain stupid.

From: Python-list  on 
behalf of Peter J. Holzer 
Date: Saturday, February 25, 2023 at 5:21 PM
To: python-list@python.org 
Subject: Re: Why doesn't Python (error msg) tell me WHAT the actual (arg) 
values are ?
On 2023-02-25 21:58:18 +, Weatherby,Gerard wrote:
> I only use asserts for things I know to be true.

Yeah, that's what assers are for. Or rather for things that you *think*
are true.

> In other words, a failing assert means I have a hole in my program
> logic.

Yes, if you include your assumptions in your definition of "logic".


> For that use, the default behavior –telling me which line the assert
> is on, is more than sufficient. Depending on the circumstance, I’ll
> re-run the code with a breakpoint or replace the assert with an
> informative f-string Exception.

That may not always be practical. Things that we know (or think) are
true often have *are* true in most cases (otherwise we wouldn't think
so). So the case where the assumption fails may not be easily
reproducable and the more information you can get post-mortem the
better. For example, in C on Linux a failed assertion causes a core
dump. So you can inspect the complete state of the program.

hp

--
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | h...@hjp.at |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Why doesn't Python (error msg) tell me WHAT the actual (arg) values are ?

2023-02-25 Thread Peter J. Holzer
On 2023-02-25 21:58:18 +, Weatherby,Gerard wrote:
> I only use asserts for things I know to be true.

Yeah, that's what assers are for. Or rather for things that you *think*
are true.

> In other words, a failing assert means I have a hole in my program
> logic.

Yes, if you include your assumptions in your definition of "logic".


> For that use, the default behavior –telling me which line the assert
> is on, is more than sufficient. Depending on the circumstance, I’ll
> re-run the code with a breakpoint or replace the assert with an
> informative f-string Exception.

That may not always be practical. Things that we know (or think) are
true often have *are* true in most cases (otherwise we wouldn't think
so). So the case where the assumption fails may not be easily
reproducable and the more information you can get post-mortem the
better. For example, in C on Linux a failed assertion causes a core
dump. So you can inspect the complete state of the program.

hp

-- 
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | h...@hjp.at |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"


signature.asc
Description: PGP signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Why doesn't Python (error msg) tell me WHAT the actual (arg) values are ?

2023-02-25 Thread Weatherby,Gerard
I only use asserts for things I know to be true. Nothing is harder to debug 
than when something you know to be true turns out to be… not True. Because I’ll 
check everything else instead of the cause of the bug.

In other words, a failing assert means I have a hole in my program logic.

For that use, the default behavior –telling me which line the assert is on, is 
more than sufficient. Depending on the circumstance, I’ll re-run the code with 
a breakpoint or replace the assert with an informative f-string Exception.



From: Python-list  on 
behalf of Peter J. Holzer 
Date: Saturday, February 25, 2023 at 9:22 AM
To: python-list@python.org 
Subject: Re: Why doesn't Python (error msg) tell me WHAT the actual (arg) 
values are ?
On 2023-02-25 09:10:06 -0500, Thomas Passin wrote:
> On 2/25/2023 1:13 AM, Peter J. Holzer wrote:
> > On 2023-02-24 18:19:52 -0500, Thomas Passin wrote:
> > > Sometimes you can use a second parameter to assert if you know what kind 
> > > of
> > > error to expect:
[...]
> > > With type errors, assert may actually give you the information needed:
> > >
> > > > > > c = {"a": a, "b": 2}
> > > > > > assert a > c
> > > Traceback (most recent call last):
> > >File "", line 1, in 
> > > TypeError: '>' not supported between instances of 'list' and 'dict'
> >
> > Actually in this case it isn't assert which gives you the information,
> > it's evaluating the expression itself. You get the same error with just
> >  a > c
> > on a line by its own.
>
> In some cases.  For my example with an explanatory string, you wouldn't want
> to write code like that after an ordinary line of code, at least not very
> often.  The assert statement allows it syntactically.

Yes, but if an error in the expression triggers an exception (as in this
case) the explanatory string will never be displayed.

hp

--
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | h...@hjp.at |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Why doesn't Python (error msg) tell me WHAT the actual (arg) values are ?

2023-02-25 Thread Peter J. Holzer
On 2023-02-25 09:10:06 -0500, Thomas Passin wrote:
> On 2/25/2023 1:13 AM, Peter J. Holzer wrote:
> > On 2023-02-24 18:19:52 -0500, Thomas Passin wrote:
> > > Sometimes you can use a second parameter to assert if you know what kind 
> > > of
> > > error to expect:
[...]
> > > With type errors, assert may actually give you the information needed:
> > > 
> > > > > > c = {"a": a, "b": 2}
> > > > > > assert a > c
> > > Traceback (most recent call last):
> > >File "", line 1, in 
> > > TypeError: '>' not supported between instances of 'list' and 'dict'
> > 
> > Actually in this case it isn't assert which gives you the information,
> > it's evaluating the expression itself. You get the same error with just
> >  a > c
> > on a line by its own.
> 
> In some cases.  For my example with an explanatory string, you wouldn't want
> to write code like that after an ordinary line of code, at least not very
> often.  The assert statement allows it syntactically.

Yes, but if an error in the expression triggers an exception (as in this
case) the explanatory string will never be displayed.

hp

-- 
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | h...@hjp.at |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"


signature.asc
Description: PGP signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Why doesn't Python (error msg) tell me WHAT the actual (arg) values are ?

2023-02-25 Thread Thomas Passin

On 2/25/2023 1:13 AM, Peter J. Holzer wrote:

On 2023-02-24 18:19:52 -0500, Thomas Passin wrote:

On 2/24/2023 2:47 PM, dn via Python-list wrote:

On 25/02/2023 08.12, Peter J. Holzer wrote:

On 2023-02-24 16:12:10 +1300, dn via Python-list wrote:

In some ways, providing this information seems appropriate.
Curiously, this does not even occur during an assert exception -
despite the value/relationship being the whole point of using
the command!

  x = 1
  assert x == 2

AssertionError (and that's it)


Sometimes you can use a second parameter to assert if you know what kind of
error to expect:


a = [1,2,3]
b = [4,5]
assert len(a) == len(b), f'len(a): {len(a)} != len(b): {len(b)}'

Traceback (most recent call last):
   File "", line 1, in 
AssertionError: len(a): 3 != len(b): 2


Yup. That's very useful (but I tend to forget that).



With type errors, assert may actually give you the information needed:


c = {"a": a, "b": 2}
assert a > c

Traceback (most recent call last):
   File "", line 1, in 
TypeError: '>' not supported between instances of 'list' and 'dict'


Actually in this case it isn't assert which gives you the information,
it's evaluating the expression itself. You get the same error with just
 a > c
on a line by its own.


In some cases.  For my example with an explanatory string, you wouldn't 
want to write code like that after an ordinary line of code, at least 
not very often.  The assert statement allows it syntactically.


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


Re: Why doesn't Python (error msg) tell me WHAT the actual (arg) values are ?

2023-02-24 Thread Peter J. Holzer
On 2023-02-24 18:19:52 -0500, Thomas Passin wrote:
> On 2/24/2023 2:47 PM, dn via Python-list wrote:
> > On 25/02/2023 08.12, Peter J. Holzer wrote:
> > > On 2023-02-24 16:12:10 +1300, dn via Python-list wrote:
> > > > In some ways, providing this information seems appropriate.
> > > > Curiously, this does not even occur during an assert exception -
> > > > despite the value/relationship being the whole point of using
> > > > the command!
> > > > 
> > > >  x = 1
> > > >  assert x == 2
> > > > 
> > > > AssertionError (and that's it)
> 
> Sometimes you can use a second parameter to assert if you know what kind of
> error to expect:
> 
> >>> a = [1,2,3]
> >>> b = [4,5]
> >>> assert len(a) == len(b), f'len(a): {len(a)} != len(b): {len(b)}'
> Traceback (most recent call last):
>   File "", line 1, in 
> AssertionError: len(a): 3 != len(b): 2

Yup. That's very useful (but I tend to forget that).


> With type errors, assert may actually give you the information needed:
> 
> >>> c = {"a": a, "b": 2}
> >>> assert a > c
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: '>' not supported between instances of 'list' and 'dict'

Actually in this case it isn't assert which gives you the information,
it's evaluating the expression itself. You get the same error with just
a > c
on a line by its own.

hp

-- 
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | h...@hjp.at |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"


signature.asc
Description: PGP signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Why doesn't Python (error msg) tell me WHAT the actual (arg) values are ?

2023-02-24 Thread Thomas Passin

On 2/24/2023 2:47 PM, dn via Python-list wrote:

On 25/02/2023 08.12, Peter J. Holzer wrote:

On 2023-02-24 16:12:10 +1300, dn via Python-list wrote:
In some ways, providing this information seems appropriate. 
Curiously, this

does not even occur during an assert exception - despite the
value/relationship being the whole point of using the command!

 x = 1
 assert x == 2

AssertionError (and that's it)


Sometimes you can use a second parameter to assert if you know what kind 
of error to expect:


>>> a = [1,2,3]
>>> b = [4,5]
>>> assert len(a) == len(b), f'len(a): {len(a)} != len(b): {len(b)}'
Traceback (most recent call last):
  File "", line 1, in 
AssertionError: len(a): 3 != len(b): 2

With type errors, assert may actually give you the information needed:

>>> c = {"a": a, "b": 2}
>>> assert a > c
Traceback (most recent call last):
  File "", line 1, in 
TypeError: '>' not supported between instances of 'list' and 'dict'

So now we know that a is a list and c is a dictionary.


Pytest is great there. If an assertion in a test case fails it analyzes
the expression to give you various levels of details:

 test session starts 


platform linux -- Python 3.10.6, pytest-6.2.5, py-1.10.0, pluggy-0.13.0
rootdir: /home/hjp/tmp/t
plugins: cov-3.0.0, anyio-3.6.1
collected 1 item

test_a.py 
F   [100%]


= FAILURES 
==
__ test_a 
___


 def test_a():
 a = [1, 2, 3]
 b = {"a": a, "b": 2}


   assert len(a) == len(b)

E   AssertionError: assert 3 == 2
E    +  where 3 = len([1, 2, 3])
E    +  and   2 = len({'a': [1, 2, 3], 'b': 2})

test_a.py:7: AssertionError
== short test summary info 
==

FAILED test_a.py::test_a - AssertionError: assert 3 == 2
= 1 failed in 0.09s 
=


+1
and hence the tone of slight surprise in the observation - because only 
ever use assert within pytests, and as observed, pytest amplifies the 
report-back to provide actionable-intelligence. See also: earlier 
contribution about using a debugger.



That said, have observed coders 'graduating' from other languages, 
making wider use of assert - assumed to be more data (value) 
sanity-checks than typing, but ...


Do you use assert frequently?


The OP seems wedded to his?her ways, complaining that Python does not 
work the way it 'should'. In turn, gives rise to the impression that 
expounding the advantages of TDD, and thus anticipating such unit and 
integration error-possibilities, might be considered an insult or 
unhelpful.

(sigh!)

Personally, I struggled a bit to adapt from the more-strictured (if not 
more-structured) languages of my past, to Python - particularly the 
different philosophies or emphases of what happens at 'compile-time' cf 
'execution-time'; and how such required marked changes in attitudes to 
design, time-allocation, work-flow, and tool-set. Two related-activities 
which made the language-change more workable and unleashed greater than 
step-change advantage, were: increased use of TDD, and actively learning 
the facilities within Python-oriented IDEs.




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


Re: Why doesn't Python (error msg) tell me WHAT the actual (arg) values are ?

2023-02-24 Thread Peter J. Holzer
On 2023-02-25 08:47:00 +1300, dn via Python-list wrote:
> That said, have observed coders 'graduating' from other languages, making
> wider use of assert - assumed to be more data (value) sanity-checks than
> typing, but ...
> 
> Do you use assert frequently?

Not very often, but I do use it. Sometimes for its intended purpose
(i.e. to guard against bugs or wrong assumptions), sometimes just to
guard incomplete or sloppy code (e.g. browsing through some projects I
find
assert len(data["structure"]["dimensions"]["observation"]) == 1
(incomplete code - I didn't bother to implement multiple observations)
and
assert(header[0] == "Monat (MM)")
(the code below is sloppy. Instead of fixing it I just made the original
programmer's assumptions explicit)
and of course
assert False
(this point should never be reached)).

hp

-- 
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | h...@hjp.at |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"


signature.asc
Description: PGP signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Why doesn't Python (error msg) tell me WHAT the actual (arg) values are ?

2023-02-24 Thread dn via Python-list

On 25/02/2023 08.12, Peter J. Holzer wrote:

On 2023-02-24 16:12:10 +1300, dn via Python-list wrote:

In some ways, providing this information seems appropriate. Curiously, this
does not even occur during an assert exception - despite the
value/relationship being the whole point of using the command!

 x = 1
 assert x == 2

AssertionError (and that's it)


Pytest is great there. If an assertion in a test case fails it analyzes
the expression to give you various levels of details:

 test session starts 

platform linux -- Python 3.10.6, pytest-6.2.5, py-1.10.0, pluggy-0.13.0
rootdir: /home/hjp/tmp/t
plugins: cov-3.0.0, anyio-3.6.1
collected 1 item

test_a.py F 
  [100%]

= FAILURES 
==
__ test_a 
___

 def test_a():
 a = [1, 2, 3]
 b = {"a": a, "b": 2}


   assert len(a) == len(b)

E   AssertionError: assert 3 == 2
E+  where 3 = len([1, 2, 3])
E+  and   2 = len({'a': [1, 2, 3], 'b': 2})

test_a.py:7: AssertionError
== short test summary info 
==
FAILED test_a.py::test_a - AssertionError: assert 3 == 2
= 1 failed in 0.09s 
=


+1
and hence the tone of slight surprise in the observation - because only 
ever use assert within pytests, and as observed, pytest amplifies the 
report-back to provide actionable-intelligence. See also: earlier 
contribution about using a debugger.



That said, have observed coders 'graduating' from other languages, 
making wider use of assert - assumed to be more data (value) 
sanity-checks than typing, but ...


Do you use assert frequently?


The OP seems wedded to his?her ways, complaining that Python does not 
work the way it 'should'. In turn, gives rise to the impression that 
expounding the advantages of TDD, and thus anticipating such unit and 
integration error-possibilities, might be considered an insult or unhelpful.

(sigh!)

Personally, I struggled a bit to adapt from the more-strictured (if not 
more-structured) languages of my past, to Python - particularly the 
different philosophies or emphases of what happens at 'compile-time' cf 
'execution-time'; and how such required marked changes in attitudes to 
design, time-allocation, work-flow, and tool-set. Two related-activities 
which made the language-change more workable and unleashed greater than 
step-change advantage, were: increased use of TDD, and actively learning 
the facilities within Python-oriented IDEs.


--
Regards,
=dn
--
https://mail.python.org/mailman/listinfo/python-list


Re: Why doesn't Python (error msg) tell me WHAT the actual (arg) values are ?

2023-02-24 Thread Peter J. Holzer
On 2023-02-24 16:12:10 +1300, dn via Python-list wrote:
> In some ways, providing this information seems appropriate. Curiously, this
> does not even occur during an assert exception - despite the
> value/relationship being the whole point of using the command!
> 
> x = 1
> assert x == 2
> 
> AssertionError (and that's it)

Pytest is great there. If an assertion in a test case fails it analyzes
the expression to give you various levels of details:

 test session starts 

platform linux -- Python 3.10.6, pytest-6.2.5, py-1.10.0, pluggy-0.13.0
rootdir: /home/hjp/tmp/t
plugins: cov-3.0.0, anyio-3.6.1
collected 1 item

test_a.py F 
  [100%]

= FAILURES 
==
__ test_a 
___

def test_a():
a = [1, 2, 3]
b = {"a": a, "b": 2}

>   assert len(a) == len(b)
E   AssertionError: assert 3 == 2
E+  where 3 = len([1, 2, 3])
E+  and   2 = len({'a': [1, 2, 3], 'b': 2})

test_a.py:7: AssertionError
== short test summary info 
==
FAILED test_a.py::test_a - AssertionError: assert 3 == 2
= 1 failed in 0.09s 
=

hp

-- 
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | h...@hjp.at |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"


signature.asc
Description: PGP signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Why doesn't Python (error msg) tell me WHAT the actual (arg) values are ?

2023-02-24 Thread Peter J. Holzer
On 2023-02-23 20:32:26 -0700, Michael Torrie wrote:
> On 2/23/23 01:08, Hen Hanna wrote:
> >  Python VM  is seeing an "int" object (123)   (and telling me that)
> >  ...   so it should be easy to print that "int" object What does
> >  Python VMknow ?   and when does it know it ?
> It knows there is an object and its name and type.  It knows this from
> the first moment you create the object and bind a name to it.
> > it seems like  it is being playful, teasing (or mean),and
> > hiding  the ball from me
> 
> Sorry you aren't understanding.  Whenever you print() out an object,
> python calls the object's __repr__() method to generate the string to
> display.  For built-in objects this is obviously trivial. But if you
> were dealing an object of some arbitrary class, there may not be a
> __repr__() method

Is this even possible? object has a __repr__ method, so all other
classes would inherit that if they don't define one themselves. I guess
it's possible to explicitely remove it ...

> which would cause an exception, or if the __repr__()
> method itself raised an exception,

Yup. That is possible and has happened to me several times - of course
always in a situation where I really needed that output ...

hp

-- 
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | h...@hjp.at |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"


signature.asc
Description: PGP signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Why doesn't Python (error msg) tell me WHAT the actual (arg) values are ?

2023-02-24 Thread Peter J. Holzer
On 2023-02-22 15:46:09 -0800, Hen Hanna wrote:
> On Wednesday, February 22, 2023 at 12:05:34 PM UTC-8, Hen Hanna wrote:
> > > py bug.py 
> > Traceback (most recent call last): 
> > File "C:\Usenet\bug.py", line 5, in  
> > print( a + 12 ) 
> > TypeError: can only concatenate str (not "int") to str 
> > 
> > 
> > Why doesn't Python (error msg) do the obvious thing and tell me 
> > WHAT the actual (offending, arg) values are ? 
> > 
> > In many cases, it'd help to know what string the var A had , when the error 
> > occurred. 
> >  i wouldn't have to put print(a) just above, to see. 
> > 
> > ( pypy doesn't do that either, but Python makes programming
> > (debugging) so easy that i hardly feel any inconvenience.)

That seems like a non-sequitur to me. If you hardly feel any
inconvenience, why argue so forcefully?
And why is pypy relevant here?


> i  see that my example   would be clearER  with this one-line  change:
> 
> 
>   >  py   bug.py
> 
>Traceback (most recent call last):
> 
>   File "C:\Usenet\bug.py", line 5, in 
>  map( Func,fooBar(  X,  Y,  X +  
> Y  ))
>  
>TypeError: can only concatenate str (not "int") to str
> 
> 
> i hope that   NOW   a few of you  can  see this as a genuine,  (reasonable)  
> question.

That doesn't seem a better example to me. There is still only one
subexpression (X + Y) where that error can come from, so I know that X
is a str and Y is an int.

A better example would be something like 

x = (a + b) * (c + d)

In this case it could be either (a + b) or (c + d) which caused the
error. But what I really want to know here is the names of the involved
variables, NOT the values. If the error message told me that the values
were 'foo' and 12.3, I still wouldn't be any wiser. The problem here of
course is that the operands aren't necessarily simple variables as in
this example - they may be arbitrarily complex expressions. However, it
might be sufficient to mark the operator which caused the exception:

|   ...
|   File "/home/hjp/tmp/./foo", line 4, in f
| return (a + b) * (c + d)
| ^
| TypeError: can only concatenate str (not "int") to str

would tell me that (c + d) caused the problem and therefore that c must
be a str which it obviously shouldn't be.

hp

-- 
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | h...@hjp.at |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"


signature.asc
Description: PGP signature
-- 
https://mail.python.org/mailman/listinfo/python-list


  1   2   3   4   5   6   7   8   9   10   >