How do I close a form without closing the entire program?

2020-08-23 Thread Steve
This program is fully operational with the exception of not being able to
close the form when I have completed the data entry. If I have code for a
second form, both remain visible.
Thoughts appreciated


from tkinter import *

def ShowForm1():
  
  fields1 = ('Sensor_Reading', 'Test_Strip_Reading', 'Dose', 'o2')

  def Data_Entry1(entries1):
   SR = (entries['Sensor_Reading'].get())
   TSR = (entries['Test_Strip_Reading'].get())
   Dose = (entries['Dose'].get())
   o2 = (entries['o2'].get())

  def SubmitForm(entries1):
   SR = entries1['Sensor_Reading'].get()
   TSR = entries1['Test_Strip_Reading'].get()
   Dose = (entries1['Dose'].get())
   o2 = (entries1['o2'].get())
   
   FormDataInfo=open("Form1Data.txt", "w") # Start a new file
   FormDataInfo.write("\n" + "   SR = " + SR + "\n")
   FormDataInfo.write("  TSR = " + TSR + "\n")
   FormDataInfo.write(" Dose = " + Dose + "\n")
   FormDataInfo.write("   o2 = " + o2 + "\n")
   FormDataInfo.close()
   print("Line written to file1")
   
  def makeform1(root, fields1):
   entries1 = {}
   for field1 in fields1:
  row = Frame(root)
  lab = Label(row, width=22, text=field1+": ", anchor='w')
  ent = Entry(row)
  ent.insert(0,"0")
  row.pack(side = TOP, fill = X, padx = 5 , pady = 5)
  lab.pack(side = LEFT)
  ent.pack(side = RIGHT, expand = YES, fill = X)
  entries1[field1] = ent
   return entries1

  if __name__ == '__main__':
   root1 = Tk()
   ents = makeform1(root1, fields1)
   
   b1 = Button(root1, text = 'Submit',
  command=(lambda e = ents: SubmitForm(e)))
   b1.pack(side = LEFT, padx = 5, pady = 5)
 
   b2 = Button(root1, text = 'Quit', command = root1.quit)
   b2.pack(side = LEFT, padx = 5, pady = 5)
   root1.mainloop()
# ===
ShowForm1()
print(" End ")
# ===


Steve


Footnote:
The human brain is one of the most complex things known to man.
according to the human brain.

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


"dictionary changed size during iteration" error in Python 3 but not in Python 2

2020-08-23 Thread Chris Green
I have a (fairly) simple little program that removes old mail messages
from my junk folder.  I have just tried to upgrade it from Python 2 to
Python 3 and now, when it finds any message[s] to delete it produces
the error:-

RuntimeError: dictionary changed size during iteration

I can sort of see why I'm getting the error but have two questions: 

1 - Why doesn't it error in Python 2?

2 - How do I fix it?


Here is the program:-

#!/usr/bin/python3
#
#
# Remove old mail from mbox files
#
import email
import mailbox
import os
import sys
import time
#
#
# Constants/configuration
#
junkdir = "/home/chris/Mail/Ju" # directory to clear old mail from
days = 7# remove mail older than this
#
#
#
#
for f in os.listdir(junkdir):
mbxPath = os.path.join(junkdir, f)
mbx = mailbox.mbox(mbxPath, factory=None)
try:
mbx.lock()
for k, msg in mbx.iteritems():
subject = msg['subject']
if msg['date'] is None:
continue
parsedDate = email.utils.parsedate(msg['date'])
if parsedDate is None:
print (subject + '\n - Bad date format:- "' + msg['date'] + '"')
continue
msgDate = time.mktime(parsedDate)
if (time.time() - msgDate) / (24 * 60 * 60) > days:
mbx.remove(k)
mbx.flush()
mbx.unlock()
except mailbox.ExternalClashError:
print ("Failed to lock: " + mbxPath)


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


Re: "dictionary changed size during iteration" error in Python 3 but not in Python 2

2020-08-23 Thread Cameron Simpson
On 23Aug2020 10:00, Chris Green  wrote:
>I have a (fairly) simple little program that removes old mail messages
>from my junk folder.  I have just tried to upgrade it from Python 2 to
>Python 3 and now, when it finds any message[s] to delete it produces
>the error:-
>
>RuntimeError: dictionary changed size during iteration
>
>I can sort of see why I'm getting the error but have two questions:
>
>1 - Why doesn't it error in Python 2?

The dict internal implementation has changed. I don't know the 
specifics, but it is now faster and maybe smaller and also now preserves 
insert order.

>2 - How do I fix it?

That standard way is to take a copy of what you're iterating over, 
usually just the keys (consumes less memory).

BTW, this approach is standard for _any_ data structure you're iterating 
over and modifying.

So:

for k, v in d.iteritems():
   ... d.remove(k) ...

might become:

for k, v in list(d.iteritems()):
   ... d.remove(k) ...

or:

for k in list(d):
   v = d[k]
   ... d.remove(k) ...

The iterators from iteritems or iterkeys (and plain old items and keys 
in Python 3) walk over the internal structure, which is a hash table. A 
typical dynamic hash table will resize every so often if items are 
inserted or removed, which doesn't just rearrange things, it can reorder 
the keys because the distribution of the keys into buckets can change as 
the number of buckets changes.

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


Re: "dictionary changed size during iteration" error in Python 3 but not in Python 2

2020-08-23 Thread Chris Green
Cameron Simpson  wrote:
> On 23Aug2020 10:00, Chris Green  wrote:
> >I have a (fairly) simple little program that removes old mail messages
> >from my junk folder.  I have just tried to upgrade it from Python 2 to
> >Python 3 and now, when it finds any message[s] to delete it produces
> >the error:-
> >
> >RuntimeError: dictionary changed size during iteration
> >
> >I can sort of see why I'm getting the error but have two questions:
> >
> >1 - Why doesn't it error in Python 2?
> 
> The dict internal implementation has changed. I don't know the 
> specifics, but it is now faster and maybe smaller and also now preserves 
> insert order.
> 
Ah, that probably explains it then.


> >2 - How do I fix it?
> 
> That standard way is to take a copy of what you're iterating over, 
> usually just the keys (consumes less memory).
> 
> BTW, this approach is standard for _any_ data structure you're iterating 
> over and modifying.
> 
> So:
> 
> for k, v in d.iteritems():
>... d.remove(k) ...
> 
> might become:
> 
> for k, v in list(d.iteritems()):
>... d.remove(k) ...
> 
I've been [not]understanding it the wrong way round!  I was somehow
trying to copy the iterator and then doing things to the copy, I now
see that you make a copy to iterate over (that isn't modified) and you
do what's necessary to the original.  Obvious really! :-)

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


Re: "dictionary changed size during iteration" error in Python 3 but not in Python 2

2020-08-23 Thread Peter Otten
Chris Green wrote:

>> >1 - Why doesn't it error in Python 2?
>> 
>> The dict internal implementation has changed. I don't know the
>> specifics, but it is now faster and maybe smaller and also now preserves
>> insert order.
>> 
> Ah, that probably explains it then.

But if you try to modify a dict while you iterate over it in py2 you trigger 
the same error:

$ python
Python 2.7.6 (default, Nov 13 2018, 12:45:42) 
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> d = dict(a=1)
>>> for k in d: del d["a"]
... 
Traceback (most recent call last):
  File "", line 1, in 
RuntimeError: dictionary changed size during iteration

If you look at the 2.7 mailbox code you'll find that the iteritems() method 
delegates to iterkeys() which in turn uses keys(), not iterkeys() as one 
might expect,

for key in self._toc.keys():
yield key

of the underlying _toc dict, and in py2 keys() creates a list of keys.

In py3 the above loop becomes

yield from self._toc.keys()

but in py3 the keys() method returns a view on the underlying dict.

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


Program chaining on Windows

2020-08-23 Thread Rob Cliffe via Python-list
On WIndows 10, running Python programs in a DOS box, I would like one 
Python program to chain to another.  I.e. the first program to be 
replaced by the second (*not* waiting for the second to finish, as with 
e.g. os.system).  This doesn't seem a lot to ask, but so far I have been 
unable to so this.  I am using Python 3.8.3.  Some attempts so far (may 
be nonsensical):


ATTEMPT #1

# File X1.py
import os
print("This is X1")
os.execl('C:\\Python38\\python.exe', 'X2.py')

# File X2.py
print("This is X2")

When I type "X1.py", it prints "This is X1", then starts the Python 
interactive interpreter.  Furthermore:

    TLDR: Weird behaviour
    Long version:  If I attempt to exit the interpreter with ctl-Z, 
this apparently succeeds (displaying the Windows command prompt), but in 
reality it is still in the interpreter, e.g. if I type "dir" it responds 
"" followed by the ">>>" interpreter prompt.  And 
this cycle (ctl-Z etc.) can be repeated ad nauseam.  If instead I try to 
exit from the interpreter with "exit()", the cursor moves to the next 
line and the interpreter waits for more input (but without displaying 
the prompt). If I try "exit()" again, the whole DOS box disappears.


ATTEMPT #2
-
# File X1.py
import os
print("This is X1")
os.execl("C:\\Python38\\python.exe X2.py", '')

This raises ValueError: execv() arg 2 first element cannot be empty

ATTEMPT #3


import os, sys
print("This is X1")
os.execl("%s X2.py" % sys.executable, "X2.py")

This raises FileNotFoundError: [Errno 2] No such file or directory

ATTEMPT #4

# File X1.py
import os, sys
print("This is X1")
os.execv(sys.executable, ['X2.py'])

This behaves the same as, or similarly to, Attempt #1.

ATTEMPT #5

# File X1.py
import os
print("This is X1")
os.popen('python X2.py')

# File X2.py as previously

    TLDR: Really weird behaviour!
    Long version: If I type "X1.py", it displays "This is X1" followed 
by the DOS prompt.  If I type in a DOS command, it is executed, and the 
DOS prompt displayed.  However, if I type in another DOS command, 
nothing happens except that the cursor moves to the next line and waits 
for input (no prompt).  If I type in a further DOS command, it is 
executed.  If I type still another DOS command, I see


Exception ignored in: encoding='cp1252'>

OSError: [Errno 22] Invalid argument

and the cursor moves to the next line (no prompt).  If I type in one 
more DOS command, it is executed, and we appear to be back to normal DOS 
operation.


ATTEMPT #6
-
# File X1.py
import subprocess, sys
print("This is X1")
subprocess.Popen('X2.py', executable=sys.executable)

This behaves the same as, or similarly to, Attempt #1.

ATTEMPT #7
-
# File X1.py
import subprocess, sys
print("This is X1")
subprocess.Popen('-c X2.py', executable=sys.executable)    # added -c

# File X2.py
print("This is X2")

Some progress (maybe).  This prints "This is X1", then the DOS prompt 
followed by "This is X2", then the cursor moves to the next line and 
sits waiting for input (no prompt).  If I then type something in, this 
is interpreted as a DOS command, and finally the DOS prompt is 
displayed.  To find out more about what is happening:


ATTEMPT #8

# File X1.py as above

# File X2.py
print("This is X2")
input("Press Enter to continue X2")
input("Press Enter to quit X2")

If I type "X1.py", it displays:

This is X1
C:\Python38>This is X2
Press Enter to continue X2

Now:
    TLDR: More weird behaviour, as if Windows and X2.py were taking 
turns to collect lines from the console.
    Long version: Now if I type something in and press Enter, it is 
interpreted as a *DOS command".  Then the DOS prompt is displayed. Now 
if I (type something and) hit Enter, I see


Press Enter to quit X2

Now if I type something and hit Enter, it is interpreted as a DOS 
command, and the DOS prompt is displayed again.  Now if I type in a DOS 
command and press Enter, it is ignored but the cursor moves to the next 
line and waits for input (no prompt).  Now if I type another DOS 
command, it is executed.  Finally we appear to be done (the DOS prompt 
is displayed and we are back to normal DOS operation).



Am I missing something?  Is there a way in Windows for one Python 
program to "chain" to another (or indeed to any executable) without 
waiting for the latter to finish?

Thanks in advance
Rob Cliffe

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


Issue in installing Python (Windows 10)

2020-08-23 Thread Debasis Chatterjee
-- Forwarded message -
From: Debasis Chatterjee 
Date: Sun, Aug 23, 2020 at 11:06 AM
Subject: Issue in installing Python (Windows 10)
To: 


Hi

I started off by using "python-3.8.5.exe".

I use "Run as Administrator" option to click this (provide my local-admin
username/pwd).

After this, I see python shell available. But no IDLE. Not sure why?
>From CMD, I can check "pip list". Surprisingly, it shows me packages that I
installed earlier, before deinstalling and reinstalling.

I am doing all these steps because earlier my program could not see
installed packages although I could see using "pip list".

Something is not right. Hence I am trying to make a fresh restart.

One thing odd is that even after removing installed program (Python) from
control panel, I still find that from "Start".

Please help.

Thank you

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


Re: Embedded python: How to debug code in an isolated way

2020-08-23 Thread Grant Edwards
On 2020-08-22, Chris Angelico  wrote:
> On Sun, Aug 23, 2020 at 5:51 AM Eko palypse  wrote:
>> So the question is, what do I need to read/learn/understand in order to 
>> solve this issue?
>> Or in other words, how can I debug my script in an isolated environment.
>
> I'd go for the old standby - IIDPIO: If In Doubt, Print It Out!
> Instead of trying to use a debug harness, just run your code normally,
> and print out whatever you think might be of interest. If you don't
> have a console, well, that would be the first thing to do - you
> *always* need a console.

Yep.  Even if you have to bit-bang a tx-only UART on a GPIO pin.

I've had to do that many times, and the last time was only a couple
years ago.  Though I must admit I never had to do that _in_ Python or
on a platform capable of running Python...

--
Grant



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


Re: Embedded python: How to debug code in an isolated way

2020-08-23 Thread Chris Angelico
On Mon, Aug 24, 2020 at 6:00 AM Grant Edwards  wrote:
>
> On 2020-08-22, Chris Angelico  wrote:
> > On Sun, Aug 23, 2020 at 5:51 AM Eko palypse  wrote:
> >> So the question is, what do I need to read/learn/understand in order to 
> >> solve this issue?
> >> Or in other words, how can I debug my script in an isolated environment.
> >
> > I'd go for the old standby - IIDPIO: If In Doubt, Print It Out!
> > Instead of trying to use a debug harness, just run your code normally,
> > and print out whatever you think might be of interest. If you don't
> > have a console, well, that would be the first thing to do - you
> > *always* need a console.
>
> Yep.  Even if you have to bit-bang a tx-only UART on a GPIO pin.
>
> I've had to do that many times, and the last time was only a couple
> years ago.  Though I must admit I never had to do that _in_ Python or
> on a platform capable of running Python...
>

Haha, yep. That's also why the first "hello world" on any embedded
system is also an important tool in itself - if you can make an LED
flicker on and off in response to your code, then you have the most
rudimentary of print functionality that you can use to debug
everything else...

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


Re: Program chaining on Windows

2020-08-23 Thread dn via Python-list

On 23/08/2020 19:31, Rob Cliffe via Python-list wrote:
On WIndows 10, running Python programs in a DOS box, I would like one 
Python program to chain to another.  I.e. the first program to be 
replaced by the second (*not* waiting for the second to finish, as with 
e.g. os.system).  This doesn't seem a lot to ask, but so far I have been 
unable to so this.  I am using Python 3.8.3.  Some attempts so far (may 
be nonsensical):


What is the definition of "finish" in the first program?
Not sure if have understood <<<(*not* waiting for the second to finish, 
as with e.g. os.system)>>>.
In Python, the easiest way to chain two "modules" is to use import. This 
gives full control to the 'import-er'.




ATTEMPT #1

# File X1.py
import os
print("This is X1")
os.execl('C:\\Python38\\python.exe', 'X2.py')

# File X2.py
print("This is X2")



# File X1.py
import os
def fn():
print("This is X1")
os.execl('C:\\Python38\\python.exe', 'X2.py')
#  !

# File X2.py
def fn():
print("This is X2")

# File x3.py
import x1
import x2
x1.fn()
x2.fn()
print( "x3 terminating" )


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


Re: Program chaining on Windows

2020-08-23 Thread Chris Angelico
On Mon, Aug 24, 2020 at 6:39 AM dn via Python-list
 wrote:
>
> On 23/08/2020 19:31, Rob Cliffe via Python-list wrote:
> > On WIndows 10, running Python programs in a DOS box, I would like one
> > Python program to chain to another.  I.e. the first program to be
> > replaced by the second (*not* waiting for the second to finish, as with
> > e.g. os.system).  This doesn't seem a lot to ask, but so far I have been
> > unable to so this.  I am using Python 3.8.3.  Some attempts so far (may
> > be nonsensical):
>
> What is the definition of "finish" in the first program?
> Not sure if have understood <<<(*not* waiting for the second to finish,
> as with e.g. os.system)>>>.
> In Python, the easiest way to chain two "modules" is to use import. This
> gives full control to the 'import-er'.
>

With exec, the intention is to *replace* the current program, not to
invoke it and wait till it's done. The current program will not
continue after a successful exec.

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


Re: Program chaining on Windows

2020-08-23 Thread Barry


> On 23 Aug 2020, at 20:58, Rob Cliffe via Python-list  
> wrote:
> 
> On WIndows 10, running Python programs in a DOS box, I would like one Python 
> program to chain to another.  I.e. the first program to be replaced by the 
> second (*not* waiting for the second to finish, as with e.g. os.system).  
> This doesn't seem a lot to ask, but so far I have been unable to so this.  I 
> am using Python 3.8.3.  Some attempts so far (may be nonsensical):
> 
> ATTEMPT #1
> 
> # File X1.py
> import os
> print("This is X1")
> os.execl('C:\\Python38\\python.exe', 'X2.py')

I think you need to have this (untested):

os.execl('C:\\Python38\\python.exe', 'C:\\Python38\\python.exe', 'X2.py')

You must put the path as the first arg, it is not done for you.

You version ran python without an arg so it thinks you want a interactive 
session.

Barry


> 
> # File X2.py
> print("This is X2")
> 
> When I type "X1.py", it prints "This is X1", then starts the Python 
> interactive interpreter.  Furthermore:
> TLDR: Weird behaviour
> Long version:  If I attempt to exit the interpreter with ctl-Z, this 
> apparently succeeds (displaying the Windows command prompt), but in reality 
> it is still in the interpreter, e.g. if I type "dir" it responds " function dir>" followed by the ">>>" interpreter prompt.  And this cycle 
> (ctl-Z etc.) can be repeated ad nauseam.  If instead I try to exit from the 
> interpreter with "exit()", the cursor moves to the next line and the 
> interpreter waits for more input (but without displaying the prompt). If I 
> try "exit()" again, the whole DOS box disappears.
> 
> ATTEMPT #2
> -
> # File X1.py
> import os
> print("This is X1")
> os.execl("C:\\Python38\\python.exe X2.py", '')

Arg 1 is a path to a program, not a command line.
So”python.exe” or maybe “X2.py”.


> 
> This raises ValueError: execv() arg 2 first element cannot be empty
> 
> ATTEMPT #3
> 
> 
> import os, sys
> print("This is X1")
> os.execl("%s X2.py" % sys.executable, "X2.py")
> 
> This raises FileNotFoundError: [Errno 2] No such file or directory
> 
> ATTEMPT #4
> 
> # File X1.py
> import os, sys
> print("This is X1")
> os.execv(sys.executable, ['X2.py'])
> 
> This behaves the same as, or similarly to, Attempt #1.
> 
> ATTEMPT #5
> 
> # File X1.py
> import os
> print("This is X1")
> os.popen('python X2.py')
> 
> # File X2.py as previously
> 
> TLDR: Really weird behaviour!
> Long version: If I type "X1.py", it displays "This is X1" followed by the 
> DOS prompt.  If I type in a DOS command, it is executed, and the DOS prompt 
> displayed.  However, if I type in another DOS command, nothing happens except 
> that the cursor moves to the next line and waits for input (no prompt).  If I 
> type in a further DOS command, it is executed.  If I type still another DOS 
> command, I see
> 
> Exception ignored in:  encoding='cp1252'>
> OSError: [Errno 22] Invalid argument
> 
> and the cursor moves to the next line (no prompt).  If I type in one more DOS 
> command, it is executed, and we appear to be back to normal DOS operation.
> 
> ATTEMPT #6
> -
> # File X1.py
> import subprocess, sys
> print("This is X1")
> subprocess.Popen('X2.py', executable=sys.executable)
> 
> This behaves the same as, or similarly to, Attempt #1.
> 
> ATTEMPT #7
> -
> # File X1.py
> import subprocess, sys
> print("This is X1")
> subprocess.Popen('-c X2.py', executable=sys.executable)# added -c
> 
> # File X2.py
> print("This is X2")
> 
> Some progress (maybe).  This prints "This is X1", then the DOS prompt 
> followed by "This is X2", then the cursor moves to the next line and sits 
> waiting for input (no prompt).  If I then type something in, this is 
> interpreted as a DOS command, and finally the DOS prompt is displayed.  To 
> find out more about what is happening:
> 
> ATTEMPT #8
> 
> # File X1.py as above
> 
> # File X2.py
> print("This is X2")
> input("Press Enter to continue X2")
> input("Press Enter to quit X2")
> 
> If I type "X1.py", it displays:
> 
> This is X1
> C:\Python38>This is X2
> Press Enter to continue X2
> 
> Now:
> TLDR: More weird behaviour, as if Windows and X2.py were taking turns to 
> collect lines from the console.
> Long version: Now if I type something in and press Enter, it is 
> interpreted as a *DOS command".  Then the DOS prompt is displayed. Now if I 
> (type something and) hit Enter, I see
> 
> Press Enter to quit X2
> 
> Now if I type something and hit Enter, it is interpreted as a DOS command, 
> and the DOS prompt is displayed again.  Now if I type in a DOS command and 
> press Enter, it is ignored but the cursor moves to the next line and waits 
> for input (no prompt).  Now if I type another DOS command, it is executed.  
> Finally we appear to be done (the DOS prompt is displayed and we are back to 
> normal DOS operation).
> 
> 
> Am I missing something?  Is the

Re: Program chaining on Windows

2020-08-23 Thread Eryk Sun
On 8/23/20, Rob Cliffe via Python-list  wrote:
>
> Am I missing something?  Is there a way in Windows for one Python
> program to "chain" to another (or indeed to any executable) without
> waiting for the latter to finish?

Windows does not implement anything equivalent to the POSIX exec
family of system calls. The C runtime library implements exec
functions by spawning a new process and exiting the current process.
So a parent process, such as a shell, that's waiting on the current
process will resume, including its console I/O. If it had been up to
me, I would have ignored the C runtime exec functions in Windows
Python. They only lead to problems with cross-platform code that
assumes they work like the POSIX exec functions. Cross-platform code
needs to spawn, wait, and proxy the child's exit code.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Program chaining on Windows

2020-08-23 Thread dn via Python-list

On 24/08/2020 09:04, Chris Angelico wrote:

On Mon, Aug 24, 2020 at 6:39 AM dn via Python-list
 wrote:


On 23/08/2020 19:31, Rob Cliffe via Python-list wrote:

On WIndows 10, running Python programs in a DOS box, I would like one
Python program to chain to another.  I.e. the first program to be
replaced by the second (*not* waiting for the second to finish, as with
e.g. os.system).  This doesn't seem a lot to ask, but so far I have been
unable to so this.  I am using Python 3.8.3.  Some attempts so far (may
be nonsensical):


What is the definition of "finish" in the first program?
Not sure if have understood <<<(*not* waiting for the second to finish,
as with e.g. os.system)>>>.
In Python, the easiest way to chain two "modules" is to use import. This
gives full control to the 'import-er'.



With exec, the intention is to *replace* the current program, not to
invoke it and wait till it's done. The current program will not
continue after a successful exec.



As a 'general rule', isn't exec() something to be avoided?

With an appropriate conditional control between the three modules, and 
bearing @Eryk's observations in-mind (and the lack of specifics in the 
OP), won't the import option succeed and won't all of file1's attributes 
be garbage-collected? Same effect, or something missing?

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


Re: Embedded python: How to debug code in an isolated way

2020-08-23 Thread Barry


> On 22 Aug 2020, at 20:53, Eko palypse  wrote:
> 
> Hello,
> 
> background info first. On windows, python3.8.5
> 
> A cpp app has an embedded python interpreter which allows to modify/enhance 
> the cpp app
> by providing objects to manipulate the cpp app and callbacks to act on 
> certain events, 
> like fileopen, fileclose, updateui ... which are send by the cpp app.
> The embedded python interpreter acts more or less like the standard python 
> REPL.
> If you run a script with code like
> 
> def test(i):
>print(i*2)
> 
> test(4)
> 
> then the test function is now globally available as long as the cpp app is 
> alive.
> 
> I've written a debugger based on bdb and encountered a situation which I 
> haven't found out how to handle correctly yet.
> 
> Let's assume I've registered a callback when something changes in the UI.
> In that case an object function gets called which highlights certain aspects 
> in the UI.
> 
> Now if I run a script via this debugger it works as long as I don't use the 
> same object function.
> If I do use it, then the stack gets corrupted(?).

When the app calls into python does the event loop of the gui block?
When you print does that trigger the event loop to run in a nested call back 
into the cpp?

Maybe you need to run python in its own thread and Marshall in and out of the 
gui main thread with the event loop?

Barry

> For example it look like this
> 
> stack:
> , 580
> ', line 1, code >, 1
>  >, 8
> 
> now if I enter the function which call this object function this gets add
> 
>  add_match>, 5
> 
> I step through the code and suddenly the stack looks like this
> 
> , 580
> ', line 1, code >, 1
>  >, 8
>  >, 154
>  paint_it>, 102)]
> 
> EnhanceAnyLexer is neither part of the test_pydebugger script nor part of the 
> debugger.
> It is used to register a callback on the updateui event.
> 
> So the question is, what do I need to read/learn/understand in order to solve 
> this issue?
> Or in other words, how can I debug my script in an isolated environment.
> I can't manipulate the __main__.dict as this seems to have general impact on 
> registered callbacks as well.
> Any ideas?
> 
> Thank you
> Eren
> -- 
> https://mail.python.org/mailman/listinfo/python-list
> 

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


Re: Program chaining on Windows

2020-08-23 Thread Chris Angelico
On Mon, Aug 24, 2020 at 7:40 AM dn via Python-list
 wrote:
>
> On 24/08/2020 09:04, Chris Angelico wrote:
> > On Mon, Aug 24, 2020 at 6:39 AM dn via Python-list
> >  wrote:
> >>
> >> On 23/08/2020 19:31, Rob Cliffe via Python-list wrote:
> >>> On WIndows 10, running Python programs in a DOS box, I would like one
> >>> Python program to chain to another.  I.e. the first program to be
> >>> replaced by the second (*not* waiting for the second to finish, as with
> >>> e.g. os.system).  This doesn't seem a lot to ask, but so far I have been
> >>> unable to so this.  I am using Python 3.8.3.  Some attempts so far (may
> >>> be nonsensical):
> >>
> >> What is the definition of "finish" in the first program?
> >> Not sure if have understood <<<(*not* waiting for the second to finish,
> >> as with e.g. os.system)>>>.
> >> In Python, the easiest way to chain two "modules" is to use import. This
> >> gives full control to the 'import-er'.
> >>
> >
> > With exec, the intention is to *replace* the current program, not to
> > invoke it and wait till it's done. The current program will not
> > continue after a successful exec.
>
>
> As a 'general rule', isn't exec() something to be avoided?
>

Nope, it's a very important tool. Not for every situation, of course,
but there are plenty of times when it's the right thing to do.

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


Re: Program chaining on Windows

2020-08-23 Thread Eryk Sun
On 8/23/20, Chris Angelico  wrote:
> On Mon, Aug 24, 2020 at 7:40 AM dn via Python-list
>
>> As a 'general rule', isn't exec() something to be avoided?
>
> Nope, it's a very important tool. Not for every situation, of course,
> but there are plenty of times when it's the right thing to do.

In POSIX, yes, but the faked implementation in Windows is almost
always the wrong choice. Since the exec functions in Windows simply
spawn a new process and exit the current process instead of replacing
the executable image of the current process, they result in broken
semantics for a waiting parent process, both in terms of getting the
correct exit status and waiting for the process to exit. The result of
the latter is an unworkable mess with console applications, since both
the parent and child will compete for console I/O.

For Windows, we need to spawn, wait, and proxy the exit status. If
possible, the spawned child process should also be added to a
kill-on-close job object, like the py.exe launcher does. That way if
the waiting parent crashes or gets terminated, the spawned child will
be terminated as well.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Program chaining on Windows

2020-08-23 Thread Rob Cliffe via Python-list
Thanks for everyone who replied so far, it is appreciated.  (I don't 
particularly like asking for help and taking up other peoples' time, but 
I really ran out of ideas.)


Chris, thanks for your explanation:

With exec, the intention is to*replace*  the current program, not to
invoke it and wait till it's done. The current program will not
continue after a successful exec.

That describes exactly what I want to do, but haven't succeeded in doing 
so far.  It's a bit frustrating that I can't do what I have been doing 
routinely for decades in another language.


dn asked

    What is the definition of "finish" in the first program?
    Not sure if have understood <<<(*not* waiting for the second to 
finish, as with e.g. os.system)>>>.


My definition of "finish" is that the program exits (sys.exit()  and 
friends), without waiting for the second program to finish.
So if I were "chaining" say to a .exe file, the Python interpreter would 
shut down immediately.

In Chris' words, I want the second program to *replace* the first one.

Barry, thanks for your suggestion:

os.execl('C:\\Python38\\python.exe', 'C:\\Python38\\python.exe', 
'X2.py')

but I'm afraid it didn't help.  I tried it and got the same behaviour 
(Python and Windows alternately grabbing console input lines) as my 
"ATTEMPT #8" which used


    subprocess.Popen('-c X2.py', executable=sys.executable)

Anything dubious about exec (or whatever) doesn't worry me as this is 
development, not live installation.


Let me describe my actual use case.  I am developing a large Python 
program (in Windows, working in DOS boxes) and I constantly want to 
modify it and re-run it.  What I have been doing is to make it respond 
to a hotkey by calling itself via os.system.  The problem is that if I 
do this 50 times I am left with 51 instances still running, each one 
waiting for the next to finish.  That's actually OK, except that when I 
finally shut it down, it takes a long time (about 2.5 sec per instance).


I have found a workaround: a small shell program which calls the main 
program (wth os.system), then when the latter exits, calls it again (if 
required).  Starting the main program is slightly slower, but acceptably 
so; shutting it down becomes constant time.


But I would still like to be able to do it as I originally planned, if 
possible.  Not least because I may have other uses for program 
"chaining" in future.


Best wishes
Rob Cliffe

On 23/08/2020 21:37, dn via Python-list wrote:

On 23/08/2020 19:31, Rob Cliffe via Python-list wrote:
On WIndows 10, running Python programs in a DOS box, I would like one 
Python program to chain to another. I.e. the first program to be 
replaced by the second (*not* waiting for the second to finish, as 
with e.g. os.system).  This doesn't seem a lot to ask, but so far I 
have been unable to so this.  I am using Python 3.8.3.  Some attempts 
so far (may be nonsensical):


What is the definition of "finish" in the first program?
Not sure if have understood <<<(*not* waiting for the second to 
finish, as with e.g. os.system)>>>.
In Python, the easiest way to chain two "modules" is to use import. 
This gives full control to the 'import-er'.




ATTEMPT #1

# File X1.py
import os
print("This is X1")
os.execl('C:\\Python38\\python.exe', 'X2.py')

# File X2.py
print("This is X2")



# File X1.py
import os
def fn():
    print("This is X1")
    os.execl('C:\\Python38\\python.exe', 'X2.py')
    #  !

# File X2.py
def fn():
    print("This is X2")

# File x3.py
import x1
import x2
x1.fn()
x2.fn()
print( "x3 terminating" )




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


Re: Program chaining on Windows

2020-08-23 Thread Chris Angelico
On Mon, Aug 24, 2020 at 9:51 AM Rob Cliffe via Python-list
 wrote:
> Let me describe my actual use case.  I am developing a large Python
> program (in Windows, working in DOS boxes) and I constantly want to
> modify it and re-run it.  What I have been doing is to make it respond
> to a hotkey by calling itself via os.system.  The problem is that if I
> do this 50 times I am left with 51 instances still running, each one
> waiting for the next to finish.  That's actually OK, except that when I
> finally shut it down, it takes a long time (about 2.5 sec per instance).
>
> I have found a workaround: a small shell program which calls the main
> program (wth os.system), then when the latter exits, calls it again (if
> required).  Starting the main program is slightly slower, but acceptably
> so; shutting it down becomes constant time.
>
> But I would still like to be able to do it as I originally planned, if
> possible.  Not least because I may have other uses for program
> "chaining" in future.
>

Hmm. Python isn't really set up to make this sort of thing easy. My
recommendations, in order of priority, would be:

1) What you're doing, but with a dedicated exit code that means
"changed, please restart me"

2) The same thing but entirely within Python. Instead of importing
modules, manually load them and exec the source code. (No relation to
the process-level exec - I'm talking about the exec function.)
Updating is way WAY faster, but it isn't the same thing as restarting.
Your code has to be built with this in mind.

3) Similar to #2 but using a language that's designed with that kind
of thing in mind. Off topic for this list but it's something I've done
on a number of occasions, so I'd be happy to discuss that with you.

4) Any other option available

5) Messing with exec on Windows

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


There is LTS?

2020-08-23 Thread 황병희
Hi, just i am curious. There is LTS for *Python*? If so, i am very thank
you for Python Project.

Yesterday, by chance, i heard that there is LTS for Linux Kernel. The
idea seems so beautiful!!! 

Sincerely, Byung-Hee

-- 
^고맙습니다 _白衣從軍_ 감사합니다_^))//
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Embedded python: How to debug code in an isolated way

2020-08-23 Thread Grant Edwards
On 2020-08-23, Chris Angelico  wrote:
> On Mon, Aug 24, 2020 at 6:00 AM Grant Edwards  
> wrote:
>>
>> On 2020-08-22, Chris Angelico  wrote:
>> > On Sun, Aug 23, 2020 at 5:51 AM Eko palypse  wrote:
>> >> So the question is, what do I need to read/learn/understand in order to 
>> >> solve this issue?
>> >> Or in other words, how can I debug my script in an isolated environment.
>> >
>> > I'd go for the old standby - IIDPIO: If In Doubt, Print It Out!
>> > Instead of trying to use a debug harness, just run your code normally,
>> > and print out whatever you think might be of interest. If you don't
>> > have a console, well, that would be the first thing to do - you
>> > *always* need a console.
>>
>> Yep.  Even if you have to bit-bang a tx-only UART on a GPIO pin.
>>
>> I've had to do that many times, and the last time was only a couple
>> years ago.  Though I must admit I never had to do that _in_ Python or
>> on a platform capable of running Python...
>
> Haha, yep. That's also why the first "hello world" on any embedded
> system is also an important tool in itself - if you can make an LED
> flicker on and off in response to your code, then you have the most
> rudimentary of print functionality that you can use to debug
> everything else...

Yep, you can send morse code, or a simple "one flash when I get here",
"two flashes when I get here", etc.  Turn it on here off there, and
now you can profile performance.

--
Grant



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