Jump to content

Hello World from Python


Nisteo
 Share

Recommended Posts

Step 1. Install Python

Step 2. Open CMD, run "pip install pywin32"

Step 3. Go to your_python_directory\Lib\site-packages\win32com\servers

Step 4. Register python COM server by running script "interp.py"

 

Example 1:

$py = ObjCreate("Python.Interpreter")

$py.exec("import sys")
$py_version = $py.eval("sys.version")

MsgBox(64, "Hello World!", "Hello World from Python " & $py_version)

HW_Python.png.f1ac9eb2c54e19d2bce6f42df8290510.png

 

Example 2:

$py = ObjCreate("Python.Interpreter")

$py.exec("import customtkinter")
$py.exec("import sys")

$py.exec("gui = customtkinter.CTk()")

$py.exec("GUI_WIDTH = 640")
$py.exec("GUI_HEIGHT = 115")
$py.exec("GUI_HORIZONTAL = int((gui.winfo_screenwidth() - GUI_WIDTH) / 2)")
$py.exec("GUI_VERTICAL = int((gui.winfo_screenheight() - GUI_HEIGHT) / 2)")

$py.exec("gui.geometry(f'{GUI_WIDTH}x{GUI_HEIGHT}+{GUI_HORIZONTAL}+{GUI_VERTICAL}')")
$py.exec("gui.resizable(False, False)")

$py.exec("gui.title('Hello World!')")

$py.exec("customtkinter.CTkLabel(gui, text=f'Hello World from Python {sys.version}').pack(expand=1)")

$py.exec("gui.mainloop()")

HW_Python-2.png.8e4d59d42b1685435c4226778558d976.png

Link to comment
Share on other sites

Thanks @Nisteo,

but can you please explain why do you want to mix the programming languages? Do you have any proper use case in mind?
I see a lack of reasons 🤔 . Because in case I am well experienced with Python, I can do (all) it directly in Python. The same for AutoIt.

Best regards
Sven

Edited by SOLVE-SMART

Stay innovative!

Spoiler

🌍 Au3Forums

🎲 AutoIt (en) Cheat Sheet

📊 AutoIt limits/defaults

💎 Code Katas: [...] (comming soon)

🎭 Collection of GitHub users with AutoIt projects

🐞 False-Positives

🔮 Me on GitHub

💬 Opinion about new forum sub category

📑 UDF wiki list

✂ VSCode-AutoItSnippets

📑 WebDriver FAQs

👨‍🏫 WebDriver Tutorial (coming soon)

Link to comment
Share on other sites

1 hour ago, SOLVE-SMART said:

Do you have any proper use case in mind?

Python has dictionaries, and you can convert JSON with a billion lines into a dictionary with a flick of your finger. Just "json.loads()" and that's it.

In the case of AutoIt, you have to spend time writing your own parser, and then SUDDENLY discover that AutoIt's execution speed does not allow you to write really good parsers for huge JSON at all.

Even for small JSON, perhaps. 🤣

And this is a disaster, because JSON is everywhere these days.

Link to comment
Share on other sites

2 hours ago, Nisteo said:

In the case of AutoIt, you have to spend time writing your own parser, and then SUDDENLY discover that AutoIt's execution speed does not allow you to write really good parsers for huge JSON at all.

I guess you didn't do a research about what is achievable with AutoIt regarding JSON handling, am I right? There are several UDFs which support working with JSONs¹ very well and make it easy. Please have a look at the this UDF wiki page for more information about it.

Don't get me wrong, I am open minded and I like different ways of doing things, but at least in my opinion it's not a reason to use Python within AutoIt.
Hint: I assume that Python is not installed already on the computer of the AutoIt users. That's why I critically ask for use cases. But all fine @Nisteo 😀 .

I still don't see the point why not just using Python for all actions instead of mixing the languages?

26 minutes ago, Kovacic said:

Python can run on Windows, Mac, Linux, Android, iOS etc... Also its close to Autoit in language. 

AutoIt is only available under Windows that's clear. So what's the point? In case I want to develop cross platform driven, I would not use AutoIt at all.

Anyway, I guess this would lead to a more off topic discussion. That's not the right place as @Nisteo opened the thread in "AutoIt General Help and Support".

Best regards
Sven

¹ @AspirinJunkie, @Jefrey and more JSON enthusiasts.

Edited by SOLVE-SMART

Stay innovative!

Spoiler

🌍 Au3Forums

🎲 AutoIt (en) Cheat Sheet

📊 AutoIt limits/defaults

💎 Code Katas: [...] (comming soon)

🎭 Collection of GitHub users with AutoIt projects

🐞 False-Positives

🔮 Me on GitHub

💬 Opinion about new forum sub category

📑 UDF wiki list

✂ VSCode-AutoItSnippets

📑 WebDriver FAQs

👨‍🏫 WebDriver Tutorial (coming soon)

Link to comment
Share on other sites

As for me this is interesting as an "proof on concept" that we can do things like this in AutoIt.

Thanks @Nisteo

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Link to comment
Share on other sites

Just now, mLipok said:

As for me this is interesting as an "proof on concept" that we can do things like this in AutoIt.

I share your point of view @mLipok regarding the POC 👍 . I try to understand the use cases, nothing more.

Best regards
Sven

Stay innovative!

Spoiler

🌍 Au3Forums

🎲 AutoIt (en) Cheat Sheet

📊 AutoIt limits/defaults

💎 Code Katas: [...] (comming soon)

🎭 Collection of GitHub users with AutoIt projects

🐞 False-Positives

🔮 Me on GitHub

💬 Opinion about new forum sub category

📑 UDF wiki list

✂ VSCode-AutoItSnippets

📑 WebDriver FAQs

👨‍🏫 WebDriver Tutorial (coming soon)

Link to comment
Share on other sites

4 hours ago, Nisteo said:

Python has dictionaries

What do you see as the key criteria that distinguish Python dictionaries from AutoIt maps?
 

4 hours ago, Nisteo said:

In the case of AutoIt, you have to spend time writing your own parser, and then SUDDENLY discover that AutoIt's execution speed does not allow you to write really good parsers for huge JSON at all.

Yup - for huge data you reach the reasonableness limit for AutoIT-based JSON parsers.
In principle, of course, you can also parse a JSON file in AutoIt with a single function call like json.loads() in Python.
However, with correspondingly less performance.

I made a quick comparison: a 250kb JSON file parsed by Python in ~150-200ms, AutoIt needs ~850ms for this.
With a 2MB file it looks already different: Python needs ~300ms and AutoIt already ~4s.
In short: Yes, for large JSON files you should look for other tools.

Whether it brings you much further to call Python within AutoIt instead of directly executing a Python script, would certainly be worth discussing.
Because I assume that although you can run Python from AutoIt, it does not mean that you can process the JSON data parsed by Python in AutoIt - right?
So you have to process the data in Python anyway.
Whether you write this directly in a Python script or take the detour via AutoIt.
I don't know - I don't really see the use case yet. Maybe a few examples will enlighten my mind a bit more.

Otherwise it is nice to see that Python can play the Uno-Reverse card and use the performance argument against others.
Normally Python-users are forced to listen to this argumentation from the respective supporters of compiled languages.
But even there, I think it's a tedious discussion, since it only looks at a single aspect out of 1000.

In the end, it remains as always: Choose the tool based on the task and therefore I agree with the argument that AutoIt is not very suitable for large JSON data.
With the script here, we now have even more options for AutoIt and I think a fundamental discussion about the pros and cons of Python versus AutoIt would be harming the intent of the thread.
By the way, I really enjoy programming in both.

So thanks for the script - it will definitely prove a usefulness to some.

Link to comment
Share on other sites

39 minutes ago, AspirinJunkie said:

What do you see as the key criteria that distinguish Python dictionaries from AutoIt maps?

This? 🤣

autoit_warning.thumb.png.df0eaf581b1da682e25eb8cfd0a8acf6.png

Joking aside, the most important thing for me so far is converting JSON to a dictionary.

 

50 minutes ago, AspirinJunkie said:

I assume that although you can run Python from AutoIt, it does not mean that you can process the JSON data parsed by Python in AutoIt - right?

You can get data from Python (by using "eval" method), but you can't send the result of executing a function or variable from AutoIt to Python for some reason.

 

4 hours ago, Zedna said:

Can you please post some simple/small example for JSON?

Let's get some values from the beginning of this json https://api.invidious.io/instances.json?pretty=1

$py = ObjCreate("Python.Interpreter")

$py.exec("from requests import get")
$py.exec("from json import loads")

$py.exec("INVIDIOUS_API = 'https://api.invidious.io/instances.json'")

$py.exec("json_data = loads(get(INVIDIOUS_API).content)")

;Print "yewtu.be"
ConsoleWrite($py.eval("json_data[0][0]") & @CRLF)

;Attempt to print Netherlands flag icon :D
ConsoleWrite($py.eval('json_data[0][1]["flag"]') & @CRLF)

;Print "NL"
ConsoleWrite($py.eval('json_data[0][1]["region"]') & @CRLF)

;Print "2.0"
ConsoleWrite($py.eval('json_data[0][1]["stats"]["version"]') & @CRLF)

;Print "invidious"
ConsoleWrite($py.eval('json_data[0][1]["stats"]["software"]["name"]') & @CRLF)

;Print "2023.02.14-d24b60c"
ConsoleWrite($py.eval('json_data[0][1]["stats"]["software"]["version"]') & @CRLF)

;Print "master"
ConsoleWrite($py.eval('json_data[0][1]["stats"]["software"]["branch"]') & @CRLF)

 

Link to comment
Share on other sites

4 hours ago, SOLVE-SMART said:

I still don't see the point why not just using Python for all actions instead of mixing the languages?

I still don't see the point why not just using machine code for all actions instead of creating compilers and interpreters and billion programming languages and transpilers from one language to another and interpreted versions of compiled languages and compiled versions of interpreted languages and more and more... 🤣

For example, people using IronPython instead of C#, Cython instead of C, Brython instead of JavaScript, Jython instead of Java, etc, etc, etc... Because python is language mainly for non-qualified programmers like scientists or home linux users or something.  Mixing easier and harder languages allows people to do complex things right now, instead of wasting 100 years for learning C and another 100 for debugging "Hello World" program.

By the same logic, learning few functions from Python and calling them from Autoit is easier task, than learning whole Python. Rapid development, you know 😎

Link to comment
Share on other sites

10 hours ago, Nisteo said:

Let's get some values from the beginning of this json https://api.invidious.io/instances.json?pretty=1

I have placed the pure AutoIt solution (with this UDF) for this next to it for comparison:

#include "JSON.au3"

$sString = FileRead("instances.json")
$aJson_Data = _JSON_Parse($sString)

ConsoleWrite(($aJson_Data[0])[0] & @CRLF)
ConsoleWrite(($aJson_Data[0])[1].flag & @CRLF)
ConsoleWrite(($aJson_Data[0])[1].region & @CRLF)
ConsoleWrite(($aJson_Data[0])[1].stats.version & @CRLF)
ConsoleWrite(($aJson_Data[0])[1].stats.software.name & @CRLF)
ConsoleWrite(($aJson_Data[0])[1].stats.software.version & @CRLF)
ConsoleWrite(($aJson_Data[0])[1].stats.software.branch & @CRLF)

The required time for the script in my case: ~550ms
For comparison: Your modified (so that it reads from the file instead of downloading first) script needs only ~120ms for me.

That means almost a 5x increase in execution speed with your approach!

Link to comment
Share on other sites

34 minutes ago, AspirinJunkie said:

That means almost a 5x increase in execution speed with your approach!

I have a crazy idea. Python has alternative implementations, right? What if we will use something like PyPy instead of standard Python? PyPy supports JIT compilation and runs multiple times faster, but I've never used it before 🤔

Link to comment
Share on other sites

I don't expect extreme improvements there, since only few commands have to be parsed here in the concrete case.
The situation is different if you have a loop, for example, and the commands there have to be chased through the (byte code) interpreter again and again.
These are the cases where Pypy can show its strengths.

Anyway, I ran it through Pypy and got an execution speed of ~90ms.
So no major improvement.

If it is concretely only about json, then you can also fall back on other special tools such as jq and get similar performance but save the whole Python overhead::

ConsoleWrite(_jq_run('instances.json', _
  '.[0][0], ' _
& '.[0][1].flag, ' _
& '.[0][1].region, ' _
& '.[0][1].stats.version, ' _
& '.[0][1].stats.software.name, ' _
& '.[0][1].stats.software.version, ' _
& '.[0][1].stats.software.branch'))


Func _jq_run($sFileName, $sJqCommand)
    Local $iPID = Run('jq.exe -r "' & $sJqCommand & '" "' & $sFileName & '"', @ScriptDir, @SW_Hide, 6)
    ProcessWaitClose($iPID)
    Return DllCall('user32.dll', 'BOOL', 'OemToChar', 'str', StdoutRead($iPID), 'str', '')[2]
EndFunc

 

Edited by AspirinJunkie
Link to comment
Share on other sites

I continued my silly experiments. I compiled a python extension (PYD) using the Nim language (Nim has a Python-like syntax, which is good). Then I called python from autoit and imported this compiled extension.

 

mymodule.nim:

import nimpy

proc hello: string {.exportpy.} =
    return "Hello World from Python compiled extension"

autoit:

$py = ObjCreate("Python.Interpreter")

$py.exec("import sys")
$py.exec("sys.path.insert(0, 'D:\\AutoIt Scripts\\Examples\\Nimpy_Demonstration')")

$py.exec("import mymodule")

$py.exec("hello = mymodule.hello()")

$hello = $py.eval("hello")

MsgBox(64, "", $hello)

hello_from_Nim.png.cd48d356c57b3b8f80f14039b0918626.png

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...