Poll

Do you like Python?

Yes, I love it.
22 (24.2%)
Yes, I like it.
24 (26.4%)
No, I don't like it
17 (18.7%)
No, I hate it.
14 (15.4%)
No opinion, indiferent
11 (12.1%)
I refuse to answer
3 (3.3%)

Total Members Voted: 90

Author Topic: Python becomes the most popular language  (Read 99297 times)

0 Members and 2 Guests are viewing this topic.

Offline brucehoult

  • Super Contributor
  • ***
  • Posts: 4050
  • Country: nz
Re: Python becomes the most popular language
« Reply #225 on: November 03, 2021, 05:42:46 am »
I just changed the array initialisation to...

nums = Math.trunc(Math.random() * ARRAYSIZE);

... to use integers like the other programs instead of floating point.

No other changes.

This reduced the runtime from 1.415 to 1.301, so that's 8.8% faster.

 

Offline mansaxel

  • Super Contributor
  • ***
  • Posts: 3554
  • Country: se
  • SA0XLR
    • My very static home page
Re: Python becomes the most popular language
« Reply #226 on: November 03, 2021, 06:21:16 am »
I am waiting for 3.11 when the apparently 2x speed up is supposed to be occuring

https://m.slashdot.org/story/385526

Yeah, 3.11 was finally half-usable!

(there should be a win3.11 logo here)



(Sorry, had to. Remembering hurts me too. Some digit strings with punctuation won't rinse from my mind, not even with bleach.. )
« Last Edit: November 03, 2021, 02:19:28 pm by mansaxel »
 
The following users thanked this post: Ed.Kloonk, newbrain

Offline brucehoult

  • Super Contributor
  • ***
  • Posts: 4050
  • Country: nz
Re: Python becomes the most popular language
« Reply #227 on: November 03, 2021, 07:26:53 am »
Yeah, 3.11 was finally half-usable!

(Sorry, had to. Remembering hurts me too. Some digit strings with punctuation won't rinse from my mind, not even with bleach.. )

NT 3.51 (Build 1057) was the first version of Windows I was prepared to use. It was quite decent, and actually had some advantages over MacOS of the time, unlike Windows 3.0, 3.11, 95, and (barf) 98. It performed quite well on a Pentium Pro 200. I worked on some MVC apps on it using VC++.

Unfortunately, I also had to use Visual SourceSafe, which was just awful.
 

Offline Just_another_Dave

  • Regular Contributor
  • *
  • Posts: 192
  • Country: es
Re: Python becomes the most popular language
« Reply #228 on: November 03, 2021, 07:34:48 am »
Just for fun, I converted that sort program to Javascript. Mostly this was just taking the C version, removing all the types, and sprinkling in the odd "function" or "var" keyword and changing rand() to Math.random() and so forth.

On my x86 Linux machine I get:

 0.816 gcc -O qsort.c -o qsort
 1.415 Javascript
 1.760 gcc qsort.c -o qsort
43.380 Python

So that's pretty fast -- faster than people who use C without turning on the optimiser get -- but it is every bit as dynamicy and scripty as Python.

And it's programmed in the C explicit step-by-step way that you're apparently not supposed to do in Python, not using built in higher level things that Javascript does actually have too.

Note that the Javascript time INCLUDES the time to parse the program and compile it to machine code. That's about another 0.040 seconds for the C version.

Here's qsort.js:

Code: [Select]
const ARRAYSIZE = 10000000;

function partition(values, left, right, pivotidx) {
    let pivot = values[pivotidx];
    var temp = values[right];
    values[right] = values[pivotidx];
    values[pivotidx] = temp;
    var storeidx = left;
    for(var idx = left; idx<right; idx++) {
if (values[idx] < pivot) {
            temp = values[idx];
            values[idx] = values[storeidx];
            values[storeidx] = temp;
            storeidx++;
}
    }
   
    temp = values[storeidx];
    values[storeidx] = values[right];
    values[right] = temp;
    return storeidx;
}

function _doquicksort(values, left, right) {
    if (right > left) {
var pivotidx = Math.trunc((left + right) / 2);
pivotidx = partition(values, left, right, pivotidx);
_doquicksort(values, left, pivotidx);
_doquicksort(values, pivotidx + 1, right);
    }
    return values;
}

function quicksort(nums) {
   return _doquicksort(nums, 0, ARRAYSIZE-1);
}
       
var nums = [];
for(var i=0; i<ARRAYSIZE; i++) {
    nums[i] = Math.random();
}

var timeit = Date.now();
nums = quicksort(nums);
timeit = Date.now() - timeit;
console.log("time = %f\n", timeit/1000);

And running it...

Code: [Select]
bruce@rip:~/programs/qsort$ node qsort.js
time = 1.415

As far as I know cpython does not have jit compilation, which is one of the causes why the explicit way is so slow (the other one is probably implemented directly in c). However, using numba or Pypy might improve your results
 

Offline tszaboo

  • Super Contributor
  • ***
  • Posts: 7418
  • Country: nl
  • Current job: ATEX product design
Re: Python becomes the most popular language
« Reply #229 on: November 03, 2021, 11:57:01 am »
Just for fun, I converted that sort program to Javascript. Mostly this was just taking the C version, removing all the types, and sprinkling in the odd "function" or "var" keyword and changing rand() to Math.random() and so forth.

On my x86 Linux machine I get:

 0.816 gcc -O qsort.c -o qsort
 1.415 Javascript
 1.760 gcc qsort.c -o qsort
43.380 Python

So that's pretty fast -- faster than people who use C without turning on the optimiser get -- but it is every bit as dynamicy and scripty as Python.

And it's programmed in the C explicit step-by-step way that you're apparently not supposed to do in Python, not using built in higher level things that Javascript does actually have too.

Note that the Javascript time INCLUDES the time to parse the program and compile it to machine code. That's about another 0.040 seconds for the C version.

Here's qsort.js:

Code: [Select]
const ARRAYSIZE = 10000000;

function partition(values, left, right, pivotidx) {
    let pivot = values[pivotidx];
    var temp = values[right];
    values[right] = values[pivotidx];
    values[pivotidx] = temp;
    var storeidx = left;
    for(var idx = left; idx<right; idx++) {
if (values[idx] < pivot) {
            temp = values[idx];
            values[idx] = values[storeidx];
            values[storeidx] = temp;
            storeidx++;
}
    }
   
    temp = values[storeidx];
    values[storeidx] = values[right];
    values[right] = temp;
    return storeidx;
}

function _doquicksort(values, left, right) {
    if (right > left) {
var pivotidx = Math.trunc((left + right) / 2);
pivotidx = partition(values, left, right, pivotidx);
_doquicksort(values, left, pivotidx);
_doquicksort(values, pivotidx + 1, right);
    }
    return values;
}

function quicksort(nums) {
   return _doquicksort(nums, 0, ARRAYSIZE-1);
}
       
var nums = [];
for(var i=0; i<ARRAYSIZE; i++) {
    nums[i] = Math.random();
}

var timeit = Date.now();
nums = quicksort(nums);
timeit = Date.now() - timeit;
console.log("time = %f\n", timeit/1000);

And running it...

Code: [Select]
bruce@rip:~/programs/qsort$ node qsort.js
time = 1.415

Code: [Select]
import numpy as np
import time
numpy.random.seed(0)
nums = np.random.randint(np.iinfo(np.int64).min, np.iinfo(np.int64).max,size = 1000000,dtype = 'int64')
timeit = time.time()
nums = nums.sort()
timeit = time.time() - timeit
print('time =', timeit)

time = 0.11429095268249512

Conclusion: Python is faster than C if you know what you are doing.
 

Offline brucehoult

  • Super Contributor
  • ***
  • Posts: 4050
  • Country: nz
Re: Python becomes the most popular language
« Reply #230 on: November 03, 2021, 12:55:58 pm »
time = 0.11429095268249512

Conclusion: Python is faster than C if you know what you are doing.

Number 1: you didn't program in Python, you used someone's C library. You might with as much logic say that bash is faster than C because you typed "python sort_using_numpy.py" to run it.

Number 2: the ridiculous result that numpy was 7 times faster than C [1] should have clued you in to the fact that the other programs are sorting ten times more data than you are.

[1] admittedly we don't know how fast your computer is because you didn't present a C result but it can't be much faster than my AMD Zen x86 and M1 ARM Mac, which are pretty close in performance.
« Last Edit: November 03, 2021, 12:58:21 pm by brucehoult »
 
The following users thanked this post: cfbsoftware, george.b, SiliconWizard

Offline tszaboo

  • Super Contributor
  • ***
  • Posts: 7418
  • Country: nl
  • Current job: ATEX product design
Re: Python becomes the most popular language
« Reply #231 on: November 03, 2021, 01:13:59 pm »
time = 0.11429095268249512

Conclusion: Python is faster than C if you know what you are doing.

Number 1: you didn't program in Python, you used someone's C library. You might with as much logic say that bash is faster than C because you typed "python sort_using_numpy.py" to run it.

Number 2: the ridiculous result that numpy was 7 times faster than C [1] should have clued you in to the fact that the other programs are sorting ten times more data than you are.

[1] admittedly we don't know how fast your computer is because you didn't present a C result but it can't be much faster than my AMD Zen x86 and M1 ARM Mac, which are pretty close in performance.
1) Ok, run it with 10 times data, 1.1 sec. maybe you should just point out that I missed a 0 compared to your intentionally badly written
2) I'm done talking to you, because you sir are a rude ... and I don't see a reason to continue any discussion, because you turned this into an echo chamber.
 

Online SiliconWizard

  • Super Contributor
  • ***
  • Posts: 14553
  • Country: fr
Re: Python becomes the most popular language
« Reply #232 on: November 03, 2021, 07:45:31 pm »
I am waiting for 3.11 when the apparently 2x speed up is supposed to be occuring

https://m.slashdot.org/story/385526

If there was one thing that could express what is wrong with Python on a higher level, that would be this announcement.
"Microsoft Funds a Team with Guido van Rossum to Double the Speed of Python ."
 :popcorn:
 

Offline PlainName

  • Super Contributor
  • ***
  • Posts: 6871
  • Country: va
Re: Python becomes the most popular language
« Reply #233 on: November 03, 2021, 08:11:58 pm »
Yep! I was gradually warming up to putting my prejudice aside and taking a running jump at Python, but the Microsoft link has undone one of my shoelaces.
 

Offline brucehoult

  • Super Contributor
  • ***
  • Posts: 4050
  • Country: nz
Re: Python becomes the most popular language
« Reply #234 on: November 03, 2021, 09:57:40 pm »
1) Ok, run it with 10 times data, 1.1 sec. maybe you should just point out that I missed a 0 compared to your intentionally badly written

1) it's not my code, it's Picuino's. I have merely run it, and made a trivial conversion from C to Javascript without fixing or commenting on the goodness or otherwise of the code, because that was not germane to the discussion. It gets the job done.

2) putting important constants at the start of the program is generally considered best practice, and Picuino did that.

3) it seems numpy takes about 85% of the time of fairly non-optimal code written in one of the worst programming languages ever imposed on the world (sorry Brendan, you know it's true). That doesn't seem something to be proud of. I could probably make a couple of trivial modifications to Picuino's code to speed it up by most of the 15% difference.

4) numpy and other libraries offer a notational advantage -- you don't have to write so much code yourself. This is valuable IF they contain what you need. If not then .. boom .. glass jaw, and you're back to slow Python.

Quote
2) I'm done talking to you, because you sir are a rude ... and I don't see a reason to continue any discussion, because you turned this into an echo chamber.

The feeling, sir, is mutual. You were the one who started talking in an insulting way. Do you enjoy getting it back? Apparently not. I am polite with people who are polite to me.
 

Offline DiTBho

  • Super Contributor
  • ***
  • Posts: 3918
  • Country: gb
Re: Python becomes the most popular language
« Reply #235 on: November 03, 2021, 10:10:05 pm »
pySerial ... people prefer to use it instead of making good C code to handle the serial-line.
As result, you find pySerial even for embedded things. That's no good.
The opposite of courage is not cowardice, it is conformity. Even a dead fish can go with the flow
 

Offline PlainName

  • Super Contributor
  • ***
  • Posts: 6871
  • Country: va
Re: Python becomes the most popular language
« Reply #236 on: November 04, 2021, 12:33:08 am »
Funny you should mention that. I purchased a hardware product which has a front end written in python running on the PC. Seemed to be OK and I put down the odd glitch of strange data to the product I was using this to test. But then I used exactly the same product, in exactly the same way, with exactly the same python install on a much slower PC, and blow me if the thing was throwing glitches all over the place. Seems like serial over USB needed a quad core CPU just to not have dropped data.
 

Online SiliconWizard

  • Super Contributor
  • ***
  • Posts: 14553
  • Country: fr
Re: Python becomes the most popular language
« Reply #237 on: November 04, 2021, 12:35:44 am »
Yeah, but look how easy it is to do it with Python! :popcorn:
 

Offline Ed.Kloonk

  • Super Contributor
  • ***
  • Posts: 4000
  • Country: au
  • Cat video aficionado
Re: Python becomes the most popular language
« Reply #238 on: November 04, 2021, 07:37:07 am »
Just posting this for anyone who may be interested. Runtime: 1hr.

Quote
The Worst Programming Language Ever (Mark Rendle, 2014)

There's something good you can say about every programming language. But that's no fun. Instead, let's take the worst features of all the languages we know, and put them together to create an abomination with the worst syntax, the worst semantics, the worst foot-guns and the worst runtime behaviour in recorded history. Let's make a language so bad it would make people run screaming to Visual Basic for Applications.


iratus parum formica
 

Offline DiTBho

  • Super Contributor
  • ***
  • Posts: 3918
  • Country: gb
Re: Python becomes the most popular language
« Reply #239 on: November 04, 2021, 09:57:06 am »
Code: [Select]
import serial
import sys

ourSerial = serial.Serial()
ourSerial.port = '/dev/ttyS0'
ourSerial.baudrate = 9600
ourSerial.bytesize = serial.EIGHTBITS
ourSerial.parity = serial.PARITY_NONE
ourSerial.stopbits = serial.STOPBITS_ONE
ourSerial.xonxoff = False
ourSerial.rtscts = False
ourSerial.dsrdtr = False

ourSerial.open()
ourSerial.flushInput()
ourSerial.flushOutput()

with open (sys.argv[1]) as fil:
    for li in fil:
        ourSerial.write(li)
        ourSerial.flush()

fil.close()
9600-8-1-none

like this  :D
The opposite of courage is not cowardice, it is conformity. Even a dead fish can go with the flow
 

Offline PlainName

  • Super Contributor
  • ***
  • Posts: 6871
  • Country: va
Re: Python becomes the most popular language
« Reply #240 on: November 04, 2021, 10:20:42 am »
Relevant part seems to be:

Code: [Select]
while counter1 < sleep_timer.get():
         sleep_reading.set(ser.readline(2).hex())
         if round((int(sleep_reading.get(),16)*LSB)/float(sense_resistor.get()),6) < 500 \
                  and round((int(sleep_reading.get(),16)*LSB)/float(sense_resistor.get()),6) != 0.0:
           si.append(round((int(sleep_reading.get(),16)*LSB)/float(sense_resistor.get()),6))
           sleep_file.write(str(round((int(sleep_reading.get(),16)*LSB)/float(sense_resistor.get()),6)))
           sleep_file.write('\n')

Seems to be rather a lot of floating point stuff inbetween serial port reads. But since I currently don't do python it could be something else.
 

Offline brucehoult

  • Super Contributor
  • ***
  • Posts: 4050
  • Country: nz
Re: Python becomes the most popular language
« Reply #241 on: November 04, 2021, 11:18:47 am »
Just for fun, I converted that sort program to Javascript. Mostly this was just taking the C version, removing all the types, and sprinkling in the odd "function" or "var" keyword and changing rand() to Math.random() and so forth.

On my x86 Linux machine I get:

 0.816 gcc -O qsort.c -o qsort
 1.415 Javascript
 1.760 gcc qsort.c -o qsort
43.380 Python

So that's pretty fast -- faster than people who use C without turning on the optimiser get -- but it is every bit as dynamicy and scripty as Python.

I reworked the Javascript a little to use a better (my opinion) partition function, and also to only use the recursive partitioning if the partition size was greater than 40, and then do an insertion sort cleanup at the end.

 0.82: improved Javascript
 1.02: improved Javascript, without insertion sort cleanup
6:41:59.48: improved Javascript, insertion sort without recursive partitioning first

Note that the Javascript time is now almost identical to the optimised C time (with a slightly worse partitioning algorithm). And 34% faster than the 1.1 seconds reported for numpy's built in sort function -- assuming comparable machines, which we don't know. My x86 Linux machine is a three year old (August 2018) Zen 1+ with only 4.2 GHz maximum clock so it's quite likely the machine numpy was run on was as fast or faster.

I'm actually shocked the Javascript is as fast as it is. It's not just a convenient high level scripting language for gluing together libraries other people have written, these days it's good enough to *write* the libraries in too.

The improved Javascript:

Code: [Select]
const ARRAYSIZE = 10000000;

function partition(nums, left, right) {
    let pivot = nums[Math.trunc((left + right) / 2)];
    var i = left-1, j = right+1;
    while (1) {
var iv, jv;
do { iv = nums[++i] } while (iv < pivot);
do { jv = nums[--j] } while (jv > pivot);
if (i >= j) break;
nums[i] = jv;
nums[j] = iv;
    }
    return j;
}

function _doquicksort(nums, left, right) {
    if ((right - left) > 40) {
let pivotidx = partition(nums, left, right);
_doquicksort(nums, left, pivotidx);
_doquicksort(nums, pivotidx + 1, right);
    }
}

function _doinsertionsort(nums, size) {
    for (var i=1; i<size; ++i) {
var vi = nums[i], j = i-1;
for (; j>=0; --j) {
    let vj = nums[j];
    if (vj <= vi) break;
    nums[j+1] = vj;
}
nums[j+1] = vi;
    }
}

function quicksort(nums, size) {
    _doquicksort(nums, 0, size-1);
    _doinsertionsort(nums, size);
}

function checkSorted(nums, size) {
    for (var i=1; i<size; ++i) {
if (nums[i] > nums[i+1])
    console.log("Items %d and %d not sorted: %d %d\n", i, i+1, nums[i], nums[i+1]);
    }
}

var nums = [];
for(var i=0; i<ARRAYSIZE; i++) {
    nums[i] = Math.trunc(Math.random() * ARRAYSIZE);
}

var timeit = Date.now();
quicksort(nums, ARRAYSIZE);
timeit = Date.now() - timeit;
console.log("time = %f\n", timeit/1000);
checkSorted(nums, ARRAYSIZE);

« Last Edit: November 04, 2021, 10:17:59 pm by brucehoult »
 

Online Nominal Animal

  • Super Contributor
  • ***
  • Posts: 6321
  • Country: fi
    • My home page and email address
Re: Python becomes the most popular language
« Reply #242 on: November 05, 2021, 05:16:14 am »
I've so many times had annoying troubles with python-serial (pyserial) and similar, that I nowadays recommend using nonblocking I/O (O_NONBLOCK when opening the device, preferably with O_CLOEXEC so as to not leak the descriptor to child processes), using termios to set the character device to pure 8-bit raw mode.

Python3 does have termios support built-in (see pydoc3 termios), and you'll need to use the built-in fcntl and select modules too (see pydoc3 fcntl and pydoc3 select) to implement non-blocking I/O, so it's not impossible; but, I do prefer doing it in C anyway.

For USB Serial in a Python application, it can make sense to use two Python threads instead, one for writing, and another for reading, both blocking (not non-blocking), optionally using a third thread for the coordination between the two; and communicating with the UI using Queues (one per direction).  This is thread-safe, and since the threads are almost always in a blocking I/O call, the fact that the current Python interpreter only executes one thread of Python code at a time, is perfectly acceptable.

For simple Graphical User Interfaces controlling an USB Serial microcontroller widget with a native USB interface developed in the Arduino, like a Teensy, this works perfectly.  The serial interface can be implemented separately for each OS (in Python), and for Linux and POSIX-type OSes, the basic threaded 2/3 worker model works very well and allows completely asynchronous interface to the device, while being so simple that even a completely new programmer can get it right.
(Again, note that in Linux, this involves only packages available in package management, so when distributed as a standard package (with sensible library version requirements!), there are no dependency issues; it Just Works.)

The completely asynchronous interface means that instead of the traditional query-response ping-pong approach, the host and the device has essentially two separate data streams that do not need to interact at all: one from the host to the device, and the other from the device to the host.  Given a native USB interface, the MCU can almost always support multiple endpoints, so that you can have for example a dedicated data streams and a dedicated control stream.  (I'd like to switch to bulk USB transfers, but thus far haven't found a way for really new programmers to grasp all of that as easily as USB Serial.)  A common one is a gamepad or joystick, keyboard, and USB Serial.
Because Human Interface Devices (HID) do not require OS drivers or privileges, for low-bandwidth applications (much less than 64000 bytes per second, 1ms latency per message) HID is a superior choice, as it completely avoids the OS driver support mess, and Just Works.

Even the communications protocol between the application and the microcontroller then uses the event-based approach.  If you have queries and responses, you'll associate each with an identifier, so that more than one thing can be under work at the same time, and there is no specific order to things, as they are identified by the identifier and can occur in whatever order. This can help a lot with latencies and delays, and can boost the achievable throughput –– say, for a data acquisition device where there is lots of data flowing in to the host, and only occasionally some control commands to the device –– avoiding the annoying "glitches" (drops in data) during command parsing.  You know, useful stuff, and not at all difficult to grasp when you have your mind open and are willing to learn new stuff.

Whether the interface to such a device is implemented in Python or in C, even when the user interface was in Python, is a bigger picture question.  If the device is not tightly coupled to the software, and the vendor doesn't mind the clients developing new applications for the device, then a pure Python implementation makes sense.
If the device and the software are tightly coupled together and both the device and the processing of the data to/from the device involve Top Sekrit Sauce, then C or C++ makes a lot more sense.

When interfacing with Python, I do prefer to use C and not C++, because the runtime dependencies are so much simpler for C.  In Linux, for example, basically all dynamically linked executables, no matter what programming language they use, have a runtime dependency on the standard C library.  So, if one limits oneself to C only, the dependencies are minimized.  Others prefer the power of expression and approaches in C++, and consider the added dependencies worth the packaging effort.

As this shows once again, I don't personally use Python for its language features or its libraries, but because it has a gentle learning curve for new programmers and allows them to do modifications without a development environment, and because it is so easy to interface to native libraries, having only to write Python code for the interface; and because its nature as a scripting language provides a perfect licensing separation for more complex licensing schemes.  AIUI, all other widely used scripting languages like Ruby and Lua do require additional native code for efficient bindings.
« Last Edit: November 05, 2021, 05:23:08 am by Nominal Animal »
 

Offline Mattjd

  • Regular Contributor
  • *
  • Posts: 230
  • Country: us
Re: Python becomes the most popular language
« Reply #243 on: November 10, 2021, 02:20:26 am »
I am waiting for 3.11 when the apparently 2x speed up is supposed to be occuring

https://m.slashdot.org/story/385526

Yeah, 3.11 was finally half-usable!

(there should be a win3.11 logo here)



(Sorry, had to. Remembering hurts me too. Some digit strings with punctuation won't rinse from my mind, not even with bleach.. )

Oh don't worry about it, I'm not old enough to have experienced that let alone remember it 😂
 

Offline RoGeorge

  • Super Contributor
  • ***
  • Posts: 6269
  • Country: ro
Re: Python becomes the most popular language
« Reply #244 on: November 10, 2021, 09:36:33 am »
"October Headline: Python programming language number 1!

Can confirm Python as the most full of nice surprises (thought it's more about its modules this time), but here's the full tale, true story:
- was upset about the user interface changes after Firefox ESR upgraded, and that they let no way to revert the UI
- tried about a week for alternative browsers, there are not many options left, by the way
- then one dude on another forum wrote this:

Quote from: antae post_id=11516 time=1636135872 user_id=71
Quote from: RoGeorge post_id=11507 time=1636111581 user_id=67
Any other browsers I should consider for a KDE/Qt5 desktop with a big monitor and a mouse?

(idea) You can create own browser.
These are two random tutorials from the internet, just to show the idea, I didn't check if they are correct, but I experimented in the past.
qt https://techvidvan.com/tutorials/create-web-browser-python-pyqt/
webkit https://pythonprogramminglanguage.com/webkit-browser/

Well, I wouldn't believe but it's that easy indeed!   ???

A DIY web browser in Python v1:
Code: [Select]
# [url]https://pythonprogramminglanguage.com/webkit-browser/[/url]
#!/usr/bin/python

from PyQt5.QtCore import *
from PyQt5.QtWidgets import *

# from PyQt5.QtWebKitWidgets import *   # was deprecated, now it is called QtWebEngineWidgets, pip install PyQtWebEngine
# from PyQt5.QtWebEngineWidgets import *
from PyQt5.QtWebEngineWidgets import QWebEngineView as QWebView

from PyQt5.QtGui import *
import sip
import sys

class tabdemo(QMainWindow):
   def __init__(self):
        super(tabdemo, self).__init__()
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.tabs = QTabWidget()
        self.tabs.setTabsClosable(True)
        self.tabs.tabCloseRequested.connect(self.closeTab)
        self.tab1 = QWidget()
        self.tabWebView = []
        self.lNameLine = []
        self.tabs.addTab(self.tab1,"New Tab")
        self.tab1UI(self.tab1)     
        self.setWindowTitle("PyQt [url]https://pythonprogramminglanguage.com[/url]")
        self.setCentralWidget(self.tabs)
        self.showMaximized()
        QShortcut(QKeySequence("Ctrl+T"), self, self.addTab)       

   def addTab(self):
      tab = QWidget()
      self.tabs.addTab(tab,"New Tab")
      self.tab1UI(tab)

      index = self.tabs.currentIndex()
      self.tabs.setCurrentIndex( index + 1 )
      #self.tabWebView[self.tabs.currentIndex()].load( QUrl('about:blank'))

   def goBack(self):
      index = self.tabs.currentIndex()
      self.tabWebView[index].back()

   def goNext(self):
      index = self.tabs.currentIndex()
      self.tabWebView[index].forward()

   def goRefresh(self):
      index = self.tabs.currentIndex()
      self.tabWebView[index].reload()

   def changePage(self):
        index = self.tabs.currentIndex()
        pageTitle = self.sender().title()[:15]
        self.tabs.setTabText(index, pageTitle);       
        self.lNameLine[self.tabs.currentIndex()].setText(self.sender().url().url())

   def load_started(self):
       return

   def tab1UI(self,tabName):
        webView = QWebView()

        backButton = QPushButton("")
        backIcon = QIcon()
        backIcon.addPixmap(QPixmap("back.svg"))
        backButton.setIcon(backIcon)
        backButton.setFlat(True)

        nextButton = QPushButton("")
        nextIcon = QIcon()
        nextIcon.addPixmap(QPixmap("next.svg"))
        nextButton.setIcon(nextIcon)
        nextButton.setFlat(True)

        refreshButton = QPushButton("")
        refreshIcon = QIcon()
        refreshIcon.addPixmap(QPixmap("refresh.svg"))
        refreshButton.setIcon(refreshIcon)
        refreshButton.setFlat(True)

        backButton.clicked.connect(self.goBack)
        nextButton.clicked.connect(self.goNext)
        refreshButton.clicked.connect(self.goRefresh)

        self.newTabButton = QPushButton("+")
        self.destroyTabButton = QPushButton("-")
        self.tabWidget = QTabWidget()

        nameLine = QLineEdit()
        nameLine.returnPressed.connect(self.requestUri)

        tabGrid = QGridLayout()

        tabGrid.setContentsMargins(0,0,0,0)

        navigationFrame = QWidget()
        navigationFrame.setMaximumHeight(32)

        navigationGrid = QGridLayout(navigationFrame)
        navigationGrid.setSpacing(0)
        navigationGrid.setContentsMargins(0,0,0,0)
        navigationGrid.addWidget(backButton,0,1)
        navigationGrid.addWidget(nextButton,0,2)
        navigationGrid.addWidget(refreshButton,0,3)
        navigationGrid.addWidget(nameLine,0,4)     

        tabGrid.addWidget(navigationFrame)

        webView = QWebView()
        htmlhead = "<head><style>body{ background-color: #fff; }</style></head><body></body>";
        webView.setHtml(htmlhead)

        #webView.loadProgress.connect(self.loading)
        webView.loadFinished.connect(self.changePage)

        frame = QFrame()
        frame.setFrameStyle(QFrame.Panel)

        gridLayout = QGridLayout(frame);
        #gridLayout.setObjectName(QStringLiteral("gridLayout"));
        gridLayout.setContentsMargins(0, 0, 0, 0);
        gridLayout.addWidget(webView, 0, 0, 1, 1);
        frame.setLayout(gridLayout)

        self.tabWebView.append(webView)
        self.tabWidget.setCurrentWidget(webView)       
        self.lNameLine.append(nameLine)
        tabGrid.addWidget(frame)
        tabName.setLayout(tabGrid)

   def tab2UI(self):
        vbox = QVBoxLayout()
        tbl1 = QTableWidget()
        tbl1.setRowCount(5)
        tbl1.setColumnCount(5)
        vbox.addWidget(tbl1)
        tbl1.setItem(0, 0, QTableWidgetItem("1")) # row, col
        self.tab2.setLayout(vbox)

   def requestUri(self):
       if self.tabs.currentIndex() != -1:

           urlText = self.lNameLine[self.tabs.currentIndex()].text()

           ##########################
           # no protocol?
           if 'http' not in urlText:
               self.lNameLine[self.tabs.currentIndex()].setText( 'https://' + urlText)

           url = QUrl(self.lNameLine[self.tabs.currentIndex()].text())

           print(self.tabs.currentIndex())
           if url.isValid():
               self.tabWebView[self.tabs.currentIndex()].load(url)
           else:
               print("Url not valid")
       else:
           print("No tabs open, open one first.")

   def closeTab(self,tabId):
       print(tabId)
       del self.lNameLine[tabId]
       del self.tabWebView[tabId]
       self.tabs.removeTab(tabId) 

def main():
   app = QApplication(sys.argv)
   ex = tabdemo()
   ex.show()
   sys.exit(app.exec_())

if __name__ == '__main__':
   main()


A DIY web browser in Python v2:
Code: [Select]
import sys

#importing Widgtes
from PyQt5.QtWidgets import *

#importing Engine Widgets
from PyQt5.QtWebEngineWidgets import *

#importing QtCore to use Qurl
from PyQt5.QtCore import *

#main window class (to create a window)-sub class of QMainWindow class
class Window(QMainWindow):

    #defining constructor function
    def __init__(self):
        #creating connnection with parent class constructor
        super(Window,self).__init__()

        #---------------------adding browser-------------------
        self.browser = QWebEngineView()

        #setting url for browser, you can use any other url also
        self.browser.setUrl(QUrl('[url]https://duckduckgo.com/'[/url]))

        #to display the search engine on our browser
        self.setCentralWidget(self.browser)

        #-------------------full screen mode------------------
        #to display browser in full screen mode, you may comment below line if you don't want to open your browser in full screen mode
        self.showMaximized()

        #----------------------navbar-------------------------
        #creating a navigation bar for the browser
        navbar = QToolBar()
        #adding created navbar
        self.addToolBar(navbar)

        #-----------------prev Button-----------------
        #creating prev button
        prevBtn = QAction('Prev',self)
        #when triggered set connection
        prevBtn.triggered.connect(self.browser.back)
        # adding prev button to the navbar
        navbar.addAction(prevBtn)

        #-----------------next Button---------------
        nextBtn = QAction('Next',self)
        nextBtn.triggered.connect(self.browser.forward)
        navbar.addAction(nextBtn)

        #-----------refresh Button--------------------
        refreshBtn = QAction('Refresh',self)
        refreshBtn.triggered.connect(self.browser.reload)
        navbar.addAction(refreshBtn)

        #-----------home button----------------------
        homeBtn = QAction('Home',self)
        #when triggered call home method
        homeBtn.triggered.connect(self.home)
        navbar.addAction(homeBtn)

        #---------------------search bar---------------------------------
        #to maintain a single line
        self.searchBar = QLineEdit()
        #when someone presses return(enter) call loadUrl method
        self.searchBar.returnPressed.connect(self.loadUrl)
        #adding created seach bar to navbar
        navbar.addWidget(self.searchBar)

        #if url in the searchBar is changed then call updateUrl method
        self.browser.urlChanged.connect(self.updateUrl)

    #method to navigate back to home page
    def home(self):
        self.browser.setUrl(QUrl('[url]https://duckduckgo.com/'[/url]))

    #method to load the required url
    def loadUrl(self):
        #fetching entered url from searchBar
        url = self.searchBar.text()
        #loading url
        self.browser.setUrl(QUrl(url))

    #method to update the url
    def updateUrl(self, url):
        #changing the content(text) of searchBar
        self.searchBar.setText(url.toString())


MyApp = QApplication(sys.argv)

#setting application name
QApplication.setApplicationName('A 100 lines DIY Web Browser   :o)')

#creating window
window = Window()

#executing created app
MyApp.exec_()




Both working!   :D
The second one fits in 100 lines, comments and empty ones included.



For the second link, PyQtWebEngine must be used instead (pip install PyQtWebEngine), QtWebKitWidgets is now deprecated in PyQt5:  https://stackoverflow.com/questions/37876987/cannot-import-qtwebkitwidgets-in-pyqt5

It's strange to creepy that it somehow deals with cookies, and was able to remember a forum login after closing the python browser and running the .py file again.   :o
« Last Edit: November 10, 2021, 09:42:52 am by RoGeorge »
 

Offline PlainName

  • Super Contributor
  • ***
  • Posts: 6871
  • Country: va
Re: Python becomes the most popular language
« Reply #245 on: November 10, 2021, 01:51:12 pm »
Quote
It's strange to creepy that it somehow deals with cookies, and was able to remember a forum login

Perhaps because it's a skin on Webkit, which is Apple's browser engine?
 

Offline RoGeorge

  • Super Contributor
  • ***
  • Posts: 6269
  • Country: ro
Re: Python becomes the most popular language
« Reply #246 on: November 10, 2021, 02:07:23 pm »
Might be, will have to look into that if I'll use the module for real.

I've noticed later today that the login remembering is not permanent, after a while it forgot the login, maybe it's somehow related with how EEVblog deals with logins (and so far I didn't test the login for other web places).

Offline PicuinoTopic starter

  • Frequent Contributor
  • **
  • Posts: 833
  • Country: 00
    • Picuino web
Re: Python becomes the most popular language
« Reply #247 on: November 10, 2021, 02:09:06 pm »
Tiobe Index for November 2021:

« Last Edit: November 10, 2021, 02:12:01 pm by Picuino »
 

Offline RoGeorge

  • Super Contributor
  • ***
  • Posts: 6269
  • Country: ro
Re: Python becomes the most popular language
« Reply #248 on: November 10, 2021, 02:19:34 pm »
I don't believe the 8th place is realistic for assembly as a nowadays programming language, not even if we add microcontrollers and ARM together with PC as a single "assembly language".  IMO it is rather on the 80th place or so, certainly not in the top 10.

Online xrunner

  • Super Contributor
  • ***
  • Posts: 7533
  • Country: us
  • hp>Agilent>Keysight>???
Re: Python becomes the most popular language
« Reply #249 on: November 10, 2021, 02:52:11 pm »
Tiobe Index for November 2021:

My bolding -

Quote
The TIOBE Programming Community index is an indicator of the popularity of programming languages. The index is updated once a month. The ratings are based on the number of skilled engineers world-wide, courses and third party vendors. Popular search engines such as Google, Bing, Yahoo!, Wikipedia, Amazon, YouTube and Baidu are used to calculate the ratings. It is important to note that the TIOBE index is not about the best programming language or the language in which most lines of code have been written.
I told my friends I could teach them to be funny, but they all just laughed at me.
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf