Τρίτη 19 Οκτωβρίου 2021

Run a Python script from M2000

This is a test module to start a python script exported to temp directory. The program wait until the script ends. Also we get feedback (reading lines from the hidden console).

Yου,can change python3 with python.

In cmd you can enter python  --version

If you didn't see version number then in Windows 10 just write python without arguments and then the Store open and you can download immediately the python from there.




Module CheckPython{
      // here without use WithEvents
      Def hidetext as long
      Declare SP SHELLPIPE
      with SP, "Active" as IsActive, "Hasline" as Sp.HasLine
      text code.py {#!/usr/bin/env python3
      import ctypes
      MessageBox = ctypes.windll.user32.MessageBoxW
      MessageBox(None, 'Hello', 'Window title', 0)
      print("Done from python")
      }
      Method SP, "Run","python3 "+quote$(temporary$+"code.py") as ok
      profiler
      if ok==0 else 500
      while isActive
      Method Sp, "ProcessLoop"
      if sp.Hasline then
            method Sp, "GetLine" as aLine$
            print
            print #-2, aLine$
            hidetext=true
            refresh
      end if
      wait 0
      if hidetext else Print Over "wait..."; timecount
      end while
      print
      print "done"
      print exist( temporary$+"code.py")=true
500      text code.py ' delete temporary$+"code.py"
      print exist( temporary$+"code.py")=false
}
CheckPython


Here we have a While   End While which get all lines before exit.
Text statement save test encoded as ANSI (one byte). We can use Text UTF-16 filename.py { } or Text UTF-8 filename.py { }.  Python read UTF-8, so if ANSI has characters below 128 then these are the same as in UTF-8.

Here we don't have characters above 127.

module variation2 {
      Declare SP SHELLPIPE
      with SP, "Active" as IsActive, "Hasline" as Sp.HasLine
      text code.py {#!/usr/bin/env python3
                                    import random
                                     
                                    def rand9999():
                                        return random.randint(1000, 9999)
                                     
                                    def tag(attr='', **kwargs):
                                        for tag, txt in kwargs.items():
                                            return '<{tag}{attr}>{txt}</{tag}>'.format(**locals())
                                     
                                    if __name__ == '__main__':
                                        header = tag(tr=''.join(tag(th=txt) for txt in ',X,Y,Z'.split(','))) + '\n'
                                        rows = '\n'.join(tag(tr=tag(' style="font-weight: bold;"', td=i)
                                                                        + ''.join(tag(td=rand9999())
                                                                                  for j in range(3)))
                                                         for i in range(1, 6))
                                        table = tag(table='\n' + header + rows + '\n')
                                        print(table)
                                    }
            Method SP, "Run","python "+quote$(temporary$+"code.py") as ok
            if ok==0 else 500
            while isActive
            Method Sp, "ProcessLoop"
            while sp.Hasline
                  method Sp, "GetLine" as aLine$
                  print #-2, aLine$
                  refresh
            end while
            wait 0
            end while
            print
            print "done"
      500      text code.py ' delete temporary$+"code.py"
}
variation2



Variation3 (Updated)
Now a logging.info()  can send text to stdout so we can get it (print() not working from thread ????)
Text saved as UTF-8 so now we show this Unicode letters  今日は



module variation3 {
      Declare SP SHELLPIPE
      Print $(4), ' switch to proportional length text rendering
      with SP, "Active" as IsActive, "Hasline" as Sp.HasLine
      text UTF-8 code.py {#!/usr/bin/env python3
      import logging
      import threading
      from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
      class HelloHTTPRequestHandler(BaseHTTPRequestHandler):
        message = 'Hello World! 今日は'
        def do_GET(self):
          self.send_response(200)
          self.send_header('Content-type', 'text/html; charset=UTF-8')
          self.end_headers()
          self.wfile.write(self.message.encode('utf-8'))
          self.close_connection = True
          logging.info("New do_GET()")
      def serve(addr, port):
        logging.info("Thread %s: starting", "Hello")
        with ThreadingHTTPServer((addr, port), HelloHTTPRequestHandler) as server:
          server.serve_forever(poll_interval=None)            
      if __name__ == '__main__':
        format = "%(asctime)s: %(message)s"
        logging.basicConfig(format=format, level=logging.INFO, datefmt="%H:%M:%S")
        addr, port = ('localhost', 80)
       
        threading.Thread(target=serve, args=(addr, port), daemon=True).start()
       
        try:
          while True:
            # handle Ctrl+C
            input()
       
        except KeyboardInterrupt:
          pass
      }
        Method SP, "Run","python "+quote$(temporary$+"code.py") as ok
        if ok==0 else 500
        while isActive
        Method SP, "ProcessLoop"
        if keypress(67) and keypress(0x11) then Print "^C": exit
        while sp.Hasline
          method SP, "GetLine" as aLine$
          print aLine$
          refresh
        end while
        wait 0
        end while
        print
        print "done"
        Declare SP nothing
500  text code.py ' delete temporary$+"code.py"
    Print $(0), ' normal text rendering (monospaced)
}
variation3




Δεν υπάρχουν σχόλια:

Δημοσίευση σχολίου

You can feel free to write any suggestion, or idea on the subject.