Guild icon
PyScript 💻
💬 | General / ╰╸python-help
General Python support. Do not expect in depth Python help. Rather, you're more likely to get pointers to other resources to help with your Python queries.
Avatar
Snortzy Gaming420 14/06/2022 03:55
Hello
Avatar
Leonard Wolf 04/08/2022 11:50
@a4piration Here
Avatar
a4piration 04/08/2022 11:50
thank you
11:51
I have a question related to 'list' and 'dictionary' to ask.
Avatar
Leonard Wolf 04/08/2022 11:51
Umm yea sure go ahead ask
Avatar
a4piration 04/08/2022 11:53
In this picture, line 12 does not recognise the 'cars' as a dictionary just because it has been previously assigned by square brackets regardless of its content being identical to that of a dictionary, correct?
11:55
I don't know if I have put my doubt properly. May someone see this picture and help me.
Avatar
Avatar
a4piration
In this picture, line 12 does not recognise the 'cars' as a dictionary just because it has been previously assigned by square brackets regardless of its content being identical to that of a dictionary, correct?
Leonard Wolf 04/08/2022 12:02
If you want to printout value of speed just type print(cars['speed'])
Avatar
a4piration 04/08/2022 12:03
Thank you for your suggestion.
12:03
I think I can be more specific.
12:03
umm
Avatar
Jeff Glass 04/08/2022 12:06
The reason cars.values() fails is that cars is a list of 10 things, and each of those things is a dict. But cars itself is still a list
12:07
If you put print(cars) just before that last for loop, you should see a list of 10 things (contained with square brackets, separated by commas), and each of those things will be a small dict
Avatar
Leonard Wolf 04/08/2022 12:07
Oops wait I didnt see it was a list
Avatar
Jeff Glass 04/08/2022 12:09
If you want to print the speed of each car, you’ll first want to loop over all the objects in the list and, for each object, print its speed for car in cars: print(car[‘speed’]) (edited)
Avatar
Avatar
a4piration
In this picture, line 12 does not recognise the 'cars' as a dictionary just because it has been previously assigned by square brackets regardless of its content being identical to that of a dictionary, correct?
Leonard Wolf 04/08/2022 12:09
To print the speed just do for car in cars: print(car['speed'])
😁 2
👍 1
12:10
Lol at the same time
12:10
I noticed it late that it was list
Avatar
Jeff Glass 04/08/2022 12:10
@a4piration that’s good evidence that we’re on the right track 🤣
Avatar
a4piration 04/08/2022 12:11
wow
12:11
bullseye!
12:11
thank you all
✅ 1
12:12
touché!
12:12
haha
Avatar
Jeff Glass 04/08/2022 12:13
Any time! 👍
Avatar
a4piration 05/08/2022 07:04
Hi
07:04
It's a question about lists inside a dictionary.
07:04
07:06
I don't quite know why the title() runs into error in these two places when the title()s above them work without issue.
Avatar
Avatar
a4piration
I don't quite know why the title() runs into error in these two places when the title()s above them work without issue.
Leonard Wolf 05/08/2022 07:13
Thats because .title() is a method for string https://www.w3schools.com/python/ref_string_title.asp
07:13
Brands is a list
07:14
If you want to printout data from list do it like for brand in brands: print(brand.title())
Avatar
a4piration 13/08/2022 05:39
hi, I've just encountered a problem about auto-completion:
05:41
my python in vsc is not showing any input suggestion while typing. Even when I type 'pri', vsc does not show me the option 'print'.
05:41
what factors should I rule out first?
Avatar
Avatar
a4piration
what factors should I rule out first?
Leonard Wolf 13/08/2022 05:42
Extension for Visual Studio Code - IntelliSense (Pylance), Linting, Debugging (multi-threaded, remote), Jupyter Notebooks, code formatting, refactoring, unit tests, and more.
05:42
Install (edited)
Avatar
a4piration 13/08/2022 05:43
yes I have one installed
05:43
Avatar
Avatar
a4piration
yes I have one installed
Leonard Wolf 13/08/2022 05:44
Umm restart vscode once
Avatar
a4piration 13/08/2022 05:45
umm i've tried
05:45
for a few times
05:46
05:46
and the settings are just fine, apparently.
05:49
🥲
05:51
for me, auto-completion is a key factor in choosing vsc.
05:51
but i feel like being stuck this time.
Avatar
Avatar
a4piration
Click to see attachment 🖼️
Leonard Wolf 13/08/2022 06:18
Umm is it showing python in bottom bar as its lang?
Avatar
a4piration 13/08/2022 06:24
yes
Avatar
Avatar
Leonard Wolf
Umm is it showing python in bottom bar as its lang?
a4piration 13/08/2022 06:25
Avatar
Avatar
a4piration
Click to see attachment 🖼️
Leonard Wolf 13/08/2022 06:25
06:25
Out of ideas...
Avatar
a4piration 13/08/2022 06:26
I've seen quite a few related tutorial as to solve the auto-completion and all of them failed.
06:27
The only method that I have not tried is, maybe, reboot the machine.
Avatar
Avatar
a4piration
I've seen quite a few related tutorial as to solve the auto-completion and all of them failed.
Leonard Wolf 13/08/2022 06:27
Umm I have faced it before but it always worked after vs code restart
Avatar
a4piration 13/08/2022 06:27
But I have to wait until my backup is complete.
06:28
I'm backing up my pc to a external drive so the machine is quite occupied in some way.
06:29
(keeping my fingers crossed)
Avatar
Avatar
a4piration
I'm backing up my pc to a external drive so the machine is quite occupied in some way.
Leonard Wolf 13/08/2022 06:32
Ohh well then maybe take some time
06:32
I mean a break and the restart and try to see if it works
Avatar
a4piration 13/08/2022 07:30
ohhh
07:30
yeah
07:30
07:31
I deleted the settings.json and found that was not enough. And I reinstalled the python extension as well.
07:32
then, voilà, it is solved.
07:32
Avatar
Avatar
a4piration
then, voilà, it is solved.
Leonard Wolf 13/08/2022 07:37
Ohh so the extension was the issue!
07:37
Well o well Ill keep that in mind
07:53
Hi, here is a while loop written by a beginner.
07:55
I though, with line 5 highlighted in red, line 11, 15 and 19 could be deleted for better simplicity, but as I click run button, things are not what I expected.
07:56
If I have made myself understood, anyone helps me with this doubt?
Avatar
Jeff Glass 24/08/2022 13:19
Sure, so when you do an assignment like my_variable = some expression, Python evaluates the right hand side (that is, does all the operations you've written out) and assigns the result to the variable named on the left hand side. In your case, the operation is the action of the "f-string" on the template. (The technical name is "literal string interpolation".) (edited)
13:21
So when Python sees ticket = f'The ticket is {fee}', it does all the operations on the right hand side (resulting in, at first, the "The ticket is "), then sets the variable ticket to reference that newly created string. (edited)
13:26
If you want to re-evaluate the string that gets printed each time, you'll need to tell Python to do an operation which evaluates that string each time. One option is to include the lines underlined in blue in your example, as you've found. Another way might be to factor out that common operation into it's own function, perhaps something like: def get_ticket_msg(fee): return f'The ticket is {fee}' #... if int(message) < 3: print(get_ticket_msg('free')) elif int(message) <= 12: print(get_ticket_msg('$10')) elif int(message) <= 999: print(get_ticket_msg('$15'))
Avatar
Avatar
Jeff Glass
If you want to re-evaluate the string that gets printed each time, you'll need to tell Python to do an operation which evaluates that string each time. One option is to include the lines underlined in blue in your example, as you've found. Another way might be to factor out that common operation into it's own function, perhaps something like: def get_ticket_msg(fee): return f'The ticket is {fee}' #... if int(message) < 3: print(get_ticket_msg('free')) elif int(message) <= 12: print(get_ticket_msg('$10')) elif int(message) <= 999: print(get_ticket_msg('$15'))
a4piration 26/08/2022 07:05
Wow, thank you for your knowledge and patience, but things like 'def' and 'return' are yet to be learnt. I'm a beginner but I will try digesting these later.🥲
Avatar
hello
17:02
data = {} def contains(str, chars): for i in chars: if str.find(i) != -1: return i return False print("Please Insert Your Equations") while True: exp = input() op = contains(exp, ['+', '-', '*']) if op: expression = '' ops = exp.split(op) op1 = ops[0].strip() op2 = ops[1].strip() try: expression += data[op1] except KeyError: expression += op1 expression += op try: expression += data[op2] except KeyError: expression += op2 try: print(eval(expression)) except NameError as ne: print(ne) elif exp.find('='): try: tmp = exp.split('=') key = tmp[0].strip() value = tmp[1].strip() data[key] = value except: print("invalid operator")
17:02
17:03
the calculation don't add to the dictionary because i think it should be 22 instead of 20 so pretty much the code is saying the specific variable that the user inserted is equivalent to the number they put and they can add numbers to their character/variable they choose but I realised that the additions or just any other operation doesn't save the actual result to the dictionary pls help 😭 Also it would be good if the variable would always be = to 0 and the user doesn't just have to say A = 0 but if it would be done automatically and they just have to choose their character/name which could be like A and it would be = 0 by default
Avatar
Jeff Glass 10/09/2022 19:05
You switch up the logic a bit and do something like :
  • If exp contains “=“ : find the value of the expression to the right of the equals sign (using the logic you already have for applying an op to variables or numbers), then assign that value the the variable named on the left hand side
  • Otherwise just calculate the value of the expression and print jt
Avatar
umm
19:16
the assigning of the values with = seems to be working fine no? im really new to this
19:16
but
19:17
i realised with I do A + or * or - it doesn't update the dictionary
19:17
of that specific value
Avatar
Jeff Glass 10/09/2022 19:17
Oh you want assignment to work in the first part without using the = sign at all?
Avatar
it would be really nice but this was the closes I got to
Avatar
Jeff Glass 10/09/2022 19:18
Gotcha gotcha
Avatar
I've done a code thats similar let me show you
19:18
but its hardly working
19:19
while True: x = input('enter variable: ') reset = 0 data = {x: reset} #inputnum1 = int(input("What number do you want to add? ")) while True: inputop = input("Please Choose Your Operator: + or - or *: ") inputnum2 = int(input("What number do you want to add? ")) if inputop == "+": reset.append( + inputnum2) elif inputop == "-": reset.append( - inputnum2) elif inputop == "*": reset.append( * inputnum2) else: print("Invalid Operator! Please Try Again with a Valid Operator ") answer1 = input("Do you want to do another calculation? ") if answer1 == "NO" or answer1 == "No" or answer1 == "no" or answer1 == "N" or answer1 == "n": print(*reset) break y = input('enter variable to get: ') print(*data[y]) answer2 = input("Do you want to create another register/variable?") if answer2 == "NO" or answer2 == "No" or answer2 == "no" or answer2 == "N" or answer2 == "n": break print("Loop Ended")
19:20
for this the user only has to type the variable/character/name and it would equal to 0 from the start
Avatar
Jeff Glass 10/09/2022 19:21
You could do something at the end of the first part (of your original example) like: result = eval(expression) If op1 is a variable name: op1 = result
19:22
So an input like “A+2” increases the value of A by 2
Avatar
yeah but I just don't know how to update it
19:23
I tried update method
Avatar
Jeff Glass 10/09/2022 19:23
I’m not sure what you mean by update it… update it’s value in data?
Avatar
like dictionary update()
19:24
but ill assume I used it wrong
Avatar
Jeff Glass 10/09/2022 19:25
You can just reassign the value under that key data[key] = my_new_value
19:26
Update does a different thing - it’s meant for adding in key/value pairs from another dict or iterable https://www.programiz.com/python-programming/methods/dictionary/update
19:26
But that’s not obvious at all from the name, so it’s a very common stumbling block
19:27
ill try that
Avatar
Jeff Glass 10/09/2022 19:27
👍🏻
Avatar
thanks
Avatar
Avatar
Jeff Glass
You can just reassign the value under that key data[key] = my_new_value
but how would I upload it as a dictionary for the new value?
Avatar
the results for the additions or just calculations, I've created a variable for and tried to add it to value but its not working :/
Avatar
Jeff Glass 10/09/2022 21:40
Can you copy paste that section so I can understand better?
Avatar
sorry for late reply
02:32
got it fixed thanks for the help 🙂
Avatar
hey is there anyone?
Avatar
Jeff Glass 14/09/2022 13:26
@Borke10 hello! (edited)
Avatar
hello!
Avatar
have a quick question
01:08
there is the method of printing in 1 line using (end = '')
01:08
but is there a way to make it work with return?
01:08
like return(a, end = '')
Avatar
Jeff Glass 20/09/2022 02:30
Hmmm I’m not sure I understand your question
02:32
So by default, print() adds a newline character to the end of whatever you give it. This makes the output skip down to the start of the next line. By providing an end= argument, you tell print to add something else to the end instead.
02:33
And often, that’s end=‘’ to just continue on the same line, but you could do something like end=‘\t’ to add a tab character at the end, or even something goofy like print(‘Hello’, end= ‘ World.) (edited)
02:34
So… I’m not sure what you mean by using return in this case 😅
Avatar
a4piration 24/09/2022 17:01
Hi, everyone, it is a question about import. I've every once in a while come across import that is clearly not written by me (but by vscode somehow?). I have never written weird import like that (unicodedata). In this case I just wanted to write a simple function with absolutely no intention to import anything, but at some point in time after I finished and saved the file, vscode helped write for line 1, 2 and 3 without my acknowledge until I chanced to review my file. What is the mechanism behind that? Someone gives me a clue?
17:02
Avatar
Jeff Glass 24/09/2022 19:42
With VS code, I usually find that unintended imports are a result of Intellisense auto-importing something when you use auto complete. Given that you have describe_city as a function, it’d be easy for a slip of the finger ti type dec-tab and allow it to autocomplete, VS code might guess you want the decimal class from unicodedata, autocomplete that and add the import at the top. I find this feature is useful about 25% of the time, and a pain the other 75%
Avatar
Avatar
Jeff Glass
With VS code, I usually find that unintended imports are a result of Intellisense auto-importing something when you use auto complete. Given that you have describe_city as a function, it’d be easy for a slip of the finger ti type dec-tab and allow it to autocomplete, VS code might guess you want the decimal class from unicodedata, autocomplete that and add the import at the top. I find this feature is useful about 25% of the time, and a pain the other 75%
a4piration 28/09/2022 17:57
Thank you for your bona fide real-world experience.
Avatar
a4piration 28/09/2022 18:11
I'm being a bit pernickety this time. It's about generating new lines due to reading and printing line by line. I have known previously that after loading a .txt file, print() will generate a new line each time reaches the end of the file. But what do these two 'one' stand for? I noticed that it mentioned the file so I highlighted the content of it to help you better figure out what does the author (Eric Matthes) mean by these two 'one's.
Avatar
Jeff Glass 28/09/2022 18:16
Ah sure! So the ones there are referring to newline characters, the string of bytes which tells an editor/terminal/word processor/etc to skip down to the next line. What the author is pointing out there is that the lines in the file already contain newline characters at the end, and that when you print something, by default print adds a newline character at the end. So when you run the sample code there without rstrip(), you see something like this: (edited)
18:18
The reason there's an "extra" space between lines is that, for each print call:
  • there's one newline character that comes from the line in the file, and
  • another one that print tacks on the end of the line itself
The author has used print(line.rstrip()) to remove the original newline from each line of the file before trying to print, so the lines only have a single newline at the end, added by print()
18:20
What bytes make up a 'newline character'? ... well, for historical reasons, there are multiple ways to represent a newline. But most editors automatically detect what version an opened file is using and display it appropriately, and save it the same way, so the user doesn't often have to worry about it. This stack overflow post has some background: https://stackoverflow.com/a/1552775/19718391 (edited)
Avatar
a4piration 28/09/2022 18:39
Thank you for typing so much only to answer this, how to say, entry level question. I still have a doubt. If I understand it correctly, in this case, there are two factors in generating new lines. One is newline character, and the other is the mechanism of reaching the end of a file. So in the picture 1 I've just attached, there are three newlines in total, right? If so, I guess the author is trying to say both two newline characters are from the file, correct me if I'm wrong?
Avatar
Avatar
Jeff Glass
Ah sure! So the ones there are referring to newline characters, the string of bytes which tells an editor/terminal/word processor/etc to skip down to the next line. What the author is pointing out there is that the lines in the file already contain newline characters at the end, and that when you print something, by default print adds a newline character at the end. So when you run the sample code there without rstrip(), you see something like this: (edited)
a4piration 28/09/2022 18:39
.
Avatar
Jeff Glass 28/09/2022 18:40
Ah, no, the end of a file doesn't necessarily contain a newline character.
18:41
The end of a line of a file has a newline character... because in a way, that's what it means for something to be the end of a line.
Avatar
Avatar
Jeff Glass
The end of a line of a file has a newline character... because in a way, that's what it means for something to be the end of a line.
a4piration 28/09/2022 18:44
I wonder if these two characters are the so-called newline characters.
Avatar
Jeff Glass 28/09/2022 18:46
Could be? They'd be in the right place
18:47
In the Sublime Text editor, there's an extension called RawLineEdit that places indicators for the different line ending characters. In the version of pi_digits.txt I created, it looks like this:
Avatar
a4piration 28/09/2022 18:47
and there are three new lines there, right? Two of them are due to newline characters being interpreted as new lines as the result, and the third of them is due to the mechanism of reaching the end of a text file?
Avatar
Jeff Glass 28/09/2022 18:48
Those symbols are meant to represent a Carraige Return and Line Feed, respectively - the two of them in combination is one way of denoting a 'newline'
18:48
Oh I see
Avatar
Avatar
a4piration
and there are three new lines there, right? Two of them are due to newline characters being interpreted as new lines as the result, and the third of them is due to the mechanism of reaching the end of a text file?
Jeff Glass 28/09/2022 18:48
I believe the third is because you have an empty line 4 in your pi_digits.txt file you showed above
18:48
So line 3 has a newline at the end of it
Avatar
a4piration 28/09/2022 18:49
ah yeah
Avatar
Jeff Glass 28/09/2022 18:49
Which prints, then we print all of line 4 (nothing at all), and then... we end
Avatar
a4piration 28/09/2022 18:49
I stand corrected
Avatar
Jeff Glass 28/09/2022 18:49
👍
18:49
Good on ya for diving deep though, this is down in the nitty gritty stuff. Are you working through a course?
Avatar
a4piration 28/09/2022 18:50
yes i am
Avatar
Jeff Glass 28/09/2022 18:50
Which one, out of curiousity?
Avatar
a4piration 28/09/2022 18:51
Python Crash Course 2nd edition by Eric Matthes
👍 1
18:55
well, shall we go back to the previous step? In this picture, can these characters circled in blue be proved to be newline characters? (edited)
Avatar
Jeff Glass 28/09/2022 18:55
One other option would be that they're spaces. Can you delete them like spaces?
18:56
If not, demonstrating what characters they actually are may be easier or harder depending on your editor
Avatar
a4piration 28/09/2022 18:57
they can, as easily as a normal space can be deleted
Avatar
Jeff Glass 28/09/2022 18:57
Then I suspect they're spaces
18:57
I'm not super familiar with this tool, but you could upload the file to https://hexed.it/
HexEd.it is a free hex editor for Windows, MacOS, Linux and all other modern operating systems, which uses HTML5 and JavaScript (JS) technology to enable hexediting online, directly in your browser.
18:58
It'll show you byte-by-byte what the characters are. 0D OA is Carriage Return + Line Feed 0A is just Line Feed (the other common newline option) 20 is space (typically)
Avatar
a4piration 28/09/2022 19:00
It looks like a useful tool. I will try it.
Avatar
Avatar
Jeff Glass
I'm not super familiar with this tool, but you could upload the file to https://hexed.it/
a4piration 28/09/2022 19:04
You have helped me more than I can appreciate, although my question is not fully ended yet. I shall see to it another time. I guess some questions can be solved by my accumulating knowledge, and I believe this is one of them. Thank you again. Website saved.
Avatar
a4piration 20/10/2022 19:07
hi
19:07
I've just run into a trouble.
19:13
Picture 1: I'm writing a program that greets me with the pre-saved content of a .json file. Picture 2: the content is merely a '4'. Picture 3: And it turns out to be the expected result. Picture 4: But when the file is blank. Picture 5: There is an error. Picture 6: I revised the program adding an exception using the name of the error that occurred in Picture 5, but it did not help. (edited)
19:19
what was that? How can I load an empty .json file in this case? Someone give me a clue and I shall be very grateful...
Avatar
Avatar
a4piration
Picture 1: I'm writing a program that greets me with the pre-saved content of a .json file. Picture 2: the content is merely a '4'. Picture 3: And it turns out to be the expected result. Picture 4: But when the file is blank. Picture 5: There is an error. Picture 6: I revised the program adding an exception using the name of the error that occurred in Picture 5, but it did not help. (edited)
FabioRosado 20/10/2022 20:52
You need to either import the exception from Json or use json.JSONDecoderError You could also read the file before decoding it
Avatar
Avatar
FabioRosado
You need to either import the exception from Json or use json.JSONDecoderError You could also read the file before decoding it
a4piration 21/10/2022 07:20
That's what I'm talking about. Thank you. The error message quite makes me use JSONDecoderError as the name of the exception, though.
Avatar
a4piration 27/10/2022 10:23
hey, anyone tell me whether these two sentences highlighted are contradictory? If so, which is correct?
Avatar
Avatar
a4piration
hey, anyone tell me whether these two sentences highlighted are contradictory? If so, which is correct?
Leonard Wolf 27/10/2022 10:34
The second sentence should have with instead of without
Avatar
a4piration 27/10/2022 10:36
thanks
Avatar
Avatar
a4piration
hey, anyone tell me whether these two sentences highlighted are contradictory? If so, which is correct?
Leonard Wolf 27/10/2022 10:39
Example: class someClass: def __init__(self): self.sharedVariable = 2 def somefunction(self): print(self.sharedVariable) # will be printed as we are using self localVariable = 2 # local variable (not shared) def someFunction2(self): print(localVariable) # will give error as localvariable is not defined # print(self.localVariable) # will work if you share the variable in someFunction by typing self.localVariable = 2
Avatar
Avatar
Leonard Wolf
Example: class someClass: def __init__(self): self.sharedVariable = 2 def somefunction(self): print(self.sharedVariable) # will be printed as we are using self localVariable = 2 # local variable (not shared) def someFunction2(self): print(localVariable) # will give error as localvariable is not defined # print(self.localVariable) # will work if you share the variable in someFunction by typing self.localVariable = 2
a4piration 27/10/2022 10:46
Well, can i see it this way that every method with argument (normally 'self' by convention) in a class kind of submits information back to the Class with each variable being prefixed with self? All the submitted variable information will be shared for further usage in this way. (Excuse my not professional wording.)
Avatar
Avatar
a4piration
Well, can i see it this way that every method with argument (normally 'self' by convention) in a class kind of submits information back to the Class with each variable being prefixed with self? All the submitted variable information will be shared for further usage in this way. (Excuse my not professional wording.)
Leonard Wolf 27/10/2022 10:50
Umm yeah you are true in simple self can be used to share the variables and functions with different functions of class
Avatar
a4piration 27/10/2022 10:52
This takes quite an effort as a beginner, just out of interest in Python. (=^▽^=💧)
10:52
thank you
Avatar
Avatar
a4piration
This takes quite an effort as a beginner, just out of interest in Python. (=^▽^=💧)
Leonard Wolf 27/10/2022 10:54
Dont worry bruh we are here to support!
Avatar
Avatar
a4piration
hey, anyone tell me whether these two sentences highlighted are contradictory? If so, which is correct?
The disclaimer is that I don't know what Python courses to suggest. But the text in this screenshot is badly written, badly explained and also slightly incorrect. I would suggest to find another course 😉
Avatar
Avatar
antocuni
The disclaimer is that I don't know what Python courses to suggest. But the text in this screenshot is badly written, badly explained and also slightly incorrect. I would suggest to find another course 😉
a4piration 28/10/2022 11:06
It's not a course actually but a random website on the top of the result of google search. You know, people encounter various doubts, of which a course book alone cannot cover 100%. By the way, I'm following Python Crash Course by Eric Matthes.
Avatar
a4piration 29/10/2022 10:47
In picture 2, I sort of wonder how does the second parameter (i.e. ai_game) have the ability to refer to the AlienInvasion class (in picure 1)?
Avatar
Avatar
a4piration
In picture 2, I sort of wonder how does the second parameter (i.e. ai_game) have the ability to refer to the AlienInvasion class (in picure 1)?
at line 17: self.ship = Ship(self): at that line self is a reference to AlienInvasion, which is passed to the constructor of Ship.
Avatar
a4piration 29/10/2022 13:39
I haven't anticipated that!
Avatar
Avatar
antocuni
at line 17: self.ship = Ship(self): at that line self is a reference to AlienInvasion, which is passed to the constructor of Ship.
a4piration 29/10/2022 13:40
Thank you
Avatar
a4piration 30/10/2022 04:36
Hi, it's a question about whether to use 'if' or 'elif' for left and right movement in pygame module. Picture 2 is the tutorial that I'm following. The contents circled out in blue and red in Picture 2 are the corresponding part of that of Picture 1. Since the tutorial advises people to avoid using if-elif mode and to use if-if mode (highlighted in green) in ship().update(), then why does the author still use if-elif mode (circled out in Picture 2 in red colour)?
Avatar
with a sequence if if/elif, you enter in ONLY ONE of the cases. As soon as the first checked condition is true, you enter that branch and you don't bother checking the rest. With a sequence of if/if, you check all conditions, and potentially enter all of them. For the update case, the difference is "what happens if the user is pressing both the right and left keys together"? If you use if/elif, you enter only the first case (and thus the ship moves right), if you use if/if you enter both cases (and thus the ship doesn't move, since you do x += 1 and then x -= 1
08:35
the other question is: "why did they use if/elif in the _check_events() method? In this case you already know that only at most one of the various conditions can be true (because a single event cannot be e.g. KEYDOWN and KEYUP at the same time), so an if/elif is preferable (although in this precise case, an if/if would work as well -- but not in general. In particular, if you have an if/elif/elif/.../else chain, then it has a very different meaning than an if/if/if/else chain)
Avatar
Avatar
antocuni
the other question is: "why did they use if/elif in the _check_events() method? In this case you already know that only at most one of the various conditions can be true (because a single event cannot be e.g. KEYDOWN and KEYUP at the same time), so an if/elif is preferable (although in this precise case, an if/if would work as well -- but not in general. In particular, if you have an if/elif/elif/.../else chain, then it has a very different meaning than an if/if/if/else chain)
a4piration 30/10/2022 17:10
Well, thank you for your clear and detailed answer! Admittedly, the relation between the 'if' and 'elifs' (highlighted in blue in Picture 1 and 2) are very reasonable. However, excuse me for not specifying the real parts of if/elif (which are highlighted in red). I wonder why the author uses if and elif (highlighted in red). Would you help me with this point?
Avatar
Avatar
a4piration
Well, thank you for your clear and detailed answer! Admittedly, the relation between the 'if' and 'elifs' (highlighted in blue in Picture 1 and 2) are very reasonable. However, excuse me for not specifying the real parts of if/elif (which are highlighted in red). I wonder why the author uses if and elif (highlighted in red). Would you help me with this point?
I already answered 😅 Look at what I wrote in my answer above: the other question is: "why did they use if/elif in the _check_events() method?
17:17
but basically, the short answer is: in that specific case they could also use if/if and it would work fine
Avatar
Avatar
antocuni
but basically, the short answer is: in that specific case they could also use if/if and it would work fine
a4piration 30/10/2022 17:25
Yes I saw that, and I though you are emphasising the priority of keyup and keydown. What if I want to talk about the priority, for example, in the keydown part? You see, there are if and elif in the keydown part. Does that if and elif chain have more layers of meaning than simply using if if chain? What's the purpose of the author to use if and elif instead of if if, is that a result of random choice?
17:26
thought*
Avatar
no, it's more about style
19:56
if you have a set of uniquely distinct conditions, you usually use if/elif
Avatar
a4piration 07/11/2022 06:18
How can I print the 'self.msg' using neither method constructor nor return method?
Avatar
You can probably override the __str__() method to return self.msg and then use print(Go())
Avatar
Avatar
madhurt
You can probably override the __str__() method to return self.msg and then use print(Go())
a4piration 07/11/2022 06:54
Well, it gets more complicated than expected, I think, but thank you.
Avatar
Avatar
a4piration
How can I print the 'self.msg' using neither method constructor nor return method?
I'm not really sure what is the end goal, but maybe this is what you want: aaa = Go() print(aaa.msg)
Avatar
a4piration 07/11/2022 09:28
I'll try this.
09:32
I'm looking for a way to create, alter, and access a class variable freely.
09:34
But it looks not that easy, so I'm also going to resort to json module to store, alter, and access the data using an external file ending with .json. Thank you all.
Avatar
Avatar
a4piration
I'm looking for a way to create, alter, and access a class variable freely.
I'm 99% sure that you want to mean instance attribute here. Class attributes also exists in Python but it's something slightly different
Avatar
a4piration 07/11/2022 10:37
🤔
10:42
I sort of wonder if the variable prefixed with 'self.' in a method (not a constructor) of a class cannot be accessed freely as that of a constructor method, then what's the point of the existence of that 'self.'? By this time, I was always thinking that any self.xxx variable are created 'equal'. (edited)
Avatar
Avatar
a4piration
🤔
I admit that I have a hard time to answer your precise question because I'm not sure to understand what is your mental model of how Python works, but I'm pretty sure it's incorrect 😅. I suggest to read some book/documentation/tutorial/whatever which explains what are objects, classes, instances, attributes and methods in Python.
Avatar
Andrew Wallo 07/11/2022 10:46
Can I use pyscript along with Laravel PHP backend, with frontend being html and json? and if so does anyone have any examples on how to do that?
Avatar
a4piration 07/11/2022 10:55
I'm following a practical guide book of python, the author of which quite focuses on How instead of Why. But I know that concepts are essential, which I'm referring to from time to time. It's been a time of laying groundwork of python with awkward questions here and there at times.
Avatar
Avatar
Andrew Wallo
Can I use pyscript along with Laravel PHP backend, with frontend being html and json? and if so does anyone have any examples on how to do that?
FabioRosado 07/11/2022 13:38
Are you interacting with your backend through an API? If so, you should be able to use it, check the comment from Mariana and Madhur https://discord.com/channels/972017612454232116/972020206538997822/1038902045312294953
Avatar
Avatar
FabioRosado
Are you interacting with your backend through an API? If so, you should be able to use it, check the comment from Mariana and Madhur https://discord.com/channels/972017612454232116/972020206538997822/1038902045312294953
Andrew Wallo 07/11/2022 19:39
Alright, so I would have to use an API? Also I was wondering If I am alright serving my site through a server/Apache would I still need to use Pyodide and if so why?
Avatar
Avatar
Andrew Wallo
Alright, so I would have to use an API? Also I was wondering If I am alright serving my site through a server/Apache would I still need to use Pyodide and if so why?
FabioRosado 07/11/2022 19:42
Its likely, how are you serving your app currently? Or how do you want to show the information from Laravel? You will still need to use Pyodide yes since that's what will convert your python code to web assembly
Avatar
Andrew Wallo 07/11/2022 20:05
Sorry for the long explanation, but just wanted to be concise… I’m essentially only trying to use pandas dataframes right now to do calculations with mysql database tables to show on the frontend through laravel blade/html,… essentially because it would help a lot considering I am currently building a financial based app in PHP Laravel which would have a lot of accounting based modules and automated calculations, but as you may know… php doesn’t have any plugins at all for data analytics such as that of pandas. I found a route that may work for me though,… which was to just build a folder for python in my project and connect to MySQL database through PyMySQL and SQLAlchemy and do calculations that way… but how would I go about automating the running of python files in my project? Again, doing it this way I wouldn’t have to put python in html templates and could just use pure python files…so is there a way through npm (maybe package.json or vite, etc) that could automatically update MySQL database tables after user input is inserted through the frontend of my app?
Avatar
Avatar
FabioRosado
Its likely, how are you serving your app currently? Or how do you want to show the information from Laravel? You will still need to use Pyodide yes since that's what will convert your python code to web assembly
Andrew Wallo 07/11/2022 20:10
Maybe though a script such as “python app.py, etc”,… but where could I put this in my project that would work?
Avatar
a4piration 08/11/2022 12:20
Hi, the code in line 7 prints ''love you.'', but in line 8 I want it to print 'I love you.' (removing the extra quotation marks by using replace() but without altering self.msg). However, there is always a wave underline suggesting error somehow. Can someone help me point out the sticking point. (=^▽^=💧)
Avatar
a4piration 08/11/2022 13:20
There are 6 print functions but the last 2 are highlighted with wave underline. I wonder how to bypass the wave underline...
Avatar
try to run the code, Python will show an error and this will probably help you in understanding what's wrong
13:26
and in general, don't trust the wave underline: those are shown by your editor, but sometimes the editor is wrong and you have underlines even if the code is correct
13:32
13:34
it shows Syntax
13:34
SyntaxError unmatched f-string
13:35
but I have no clue
Avatar
FabioRosado 08/11/2022 13:35
The synthax error is because you are using single quotes on your fstring and on replace. So when it encounters the second single quote in replace(' it "closes" the fstring
Avatar
a4piration 08/11/2022 13:35
ah!
13:35
yeah
Avatar
FabioRosado 08/11/2022 13:36
In these cases you need to use double quotes for example: f'{msg.replace("i", "i")}' Or the other way around
Avatar
a4piration 08/11/2022 13:36
double quotation marks should be surrounded by single quotation marks
13:36
or vice versa
13:39
thanks
Avatar
Avatar
FabioRosado
The synthax error is because you are using single quotes on your fstring and on replace. So when it encounters the second single quote in replace(' it "closes" the fstring
a4piration 08/11/2022 13:42
I was suddenly alerted to the entry-level faux pas the moment you reminded me that I am using single quotation marks. (=^▽^=💧)
Avatar
a4piration 10/11/2022 07:08
I'm quite interested in the coding style of EAFP and LBYL of coding style. The former is short for (it is easier to) ask (for) forgiveness (than) permission, for example, featured by try-except block. The latter stands for look before you leap , for example, characterised by if-else block. Normally, object A (forgive my choice of words) expressed by try-except (without running except) takes comparatively less time to finish than the object A of if-else. However, if object A of try-except encounters except, then its runtime is significantly longer than that of if else (running else).
07:10
Does if-else run with more continuance while there is somehow a pause before running except (if the except is going to run)?
07:16
And python recognises 'try' with less hesitation than 'if', and run the contents after 'try' more 'immediately'. Python needs to check the contents after 'if' before actually running it, while python runs the contents after 'try' without any ado, just give it a instant 'try'. (=^▽^=💧)
07:16
Does that hold true?
Avatar
Does someone know how i implement the slider var in the python code? Like when i move the slider its value in html is 50 and now i want this also in the python script(NOTE: This is a server py)
Avatar
Avatar
KCLucas
Does someone know how i implement the slider var in the python code? Like when i move the slider its value in html is 50 and now i want this also in the python script(NOTE: This is a server py)
Jeff Glass 23/11/2022 14:37
You'll need to have the oninput method of the slider send a request back to the server with it's value, then have the server handle that request and do something with it. Here's a brief example.
14:37
I moved the HTML into a separate file so my IDE would handle formatting/highlighting, but the same principle applies if it's an inline string like you had
14:39
The new lines in slider.oninput and the server's new do_POST method are the things to look at. I also commented out some Raspberry Pi-specific things for my testing, since I'm not on a Pi at the moment, but uncomment them at your leisure 😅
14:40
Most frontend frameworks have more elegent ways of crafting a POST request, but this is rough and ready and pretty understandable, I think
Avatar
ok i test this right now and this also helps me bc now i can try to build a normal website with the index.html and not as the py programm and have a seperate python script
Avatar
Just a question for me to understand what exactly does the hi button xD?
Avatar
Avatar
KCLucas
Just a question for me to understand what exactly does the hi button xD?
Jeff Glass 23/11/2022 17:49
Oh oops! It's a holdover from my testing the HTML page import, just logs a string to the console's dev terminal. You can delete it. 😅
Avatar
k xD
17:54
must the py program be in the same ordner as the index.html/page.html
Avatar
Jeff Glass 23/11/2022 17:58
That's how it's currently written - if you want to put page.html somewhere else or call it something else, change the path here (line 41) with open('page.html', 'r') as fp: (edited)
Avatar
ok so i just start the py program and it wokrs or should i move it to the apache website folder
18:01
where the page.html automatic starts as server
Avatar
Jeff Glass 23/11/2022 18:10
If apache's serving the webpage, then this Python script isn't... are you looking to move this over to apache? Perhaps I'm missing something (edited)
Avatar
kinda idk what i need to use that i can port foward it so i can acces the website from everywhere and change stuff on there
18:18
couse the cam didnt work with this but my idea is i have a main website(apache) and from there i can get acces to the first py file where the html is inside and i tried it it works so now i wanted to controll the servo from another (websiste, not the cam site) so its easier bc than i can have it sepperated like 2 different projects
18:18
That what i am looking for now is just a normal website where i have a slider to move the servo nothing else couse i do it sepperate now
Avatar
Jeff Glass 23/11/2022 18:24
Whichever program you use as your server, whether apache or the one you've got (RPI_webserver) will need to be responsible for accepting messages from the frontend HTML code (GET for getting content, POST for sending data, etc), and when it receives them, acting on them (returning page content, setting servo levels, etc)
18:24
Apache in this case would replace RPI_webserver.py
18:25
As far as port forwarding (which is a setting on your router, which could work with either program) and making your Raspberry Pi available on the wider internet, that's quite a bit larger of a topic 🤔
Avatar
Yeah I know I first want to make it so that I can someone see Thron the cam and move it with a slider I also was thinking about something where I need to put a password or so but bc I am New I try some stupid shit xD I Re installed my Old raspberry pi like 40 Times bc I messed someone stuff up xD
18:30
but now I go to training and try more stuff next day
Avatar
hey i am still working on that stuff and got a new problem i have 2 servos and a joistick but when i move up the servo is turning wrong direction how can i like change the +90 to a -90
14:49
612 bytes
14:52
the joystick is givin me a 32.xxx number the "x" couse i dont know the real num,ber right now. the thing is servo can only go from-90 to 90 so i got the 32k : 364 is like 90.100 what ever but thats to high so i use an "Int" so its a solid 90 but now i want that it is -90 or when its 30 it needs -30 like just flipped and no i cant rotate the servo xD
Avatar
Jeff Glass 01/12/2022 14:57
If you want to get the inverse of any input value, you can just add a minus sign - in front of the value: For example:
14:58
>>> x = 42 >>> print(-x) -42
14:58
Or, if I'm understanding you code right: servo1.angle = -int(value/364))
Avatar
ok ill try
15:02
and when its a negativ int and i want a postiv a just do servo1.angle = +int(value/364)) idk how to do it that its looks like a code (edited)
Avatar
Jeff Glass 01/12/2022 15:03
Actually, the - takes care of that too! >>> x = -1000 >>> print(-x) 1000
15:03
It's the same as multiplying the number by -1
15:04
So using servo1.angle = -int(value/364)) will make all positive values into negative, and all negative values into positive
Avatar
ah yeah
15:05
not working xD
15:05
ah wait
15:06
i just changed it in the print and not in the servo output
15:06
Yep this works
620 bytes
Avatar
Jeff Glass 01/12/2022 15:06
👍
Avatar
now its turning left when i joystick to left and now i could try and not the ps4 controller input instad the vr headset input
Avatar
Hello everyone! We are developing a web project in which we need to get the bluetooth data of the surrounding devices (ibeacons) with Python. Actually, we tried to do this on the client side with the google web bluetooth api, but we couldn't because the modules were not working. We want to receive the data we can get with the Python Bleak library on the client side and save it in the session. We think we can do this with the best pyscript. However, our problem is: "The Bleak Library does not work with the pyscript library".
11:55
How can I solve this problem? Could you please add the Bleak library among the libraries that can work integrated with pyscript?
11:56
Or does anyone have a different suggestion?
Avatar
Thank you but we've already tried the modules here and most of them don't work
Avatar
what modules ?
Avatar
for example getDevices
Avatar
it seems logical that you are not allowed to scan agressively a bus you don't own (edited)
😂 1
11:59
you must know the device class and its id range before
Avatar
I absolutely agree with you. We already find it sufficient to access the data of our own ibeacon devices. We can easily do this with the "python bleak" library. We just need to achieve this on the client side. I think the best alternative is "pyscript". But unfortunately it doesn't work with bleak
Avatar
i guess you need to write a platform backend for bleak
12:05
can't you use webserial instead ? it's way simpler to interface ...
Avatar
first time i hear it. Thank you very much i will search it. Thank you again!
👍 1
Avatar
@Jeff Glass heya, I am new to web development as I’ve been stuck in the IDE with python. I am developing web apps for pilots in airlines. How long does the runtime generally stay on the browser? Can a pilot download the runtime before their flight, stick their device in aeroplane mode and pyscript will continue its magic for the next few hours (as long as I have no calls to a server)?
Avatar
Avatar
char
@Jeff Glass heya, I am new to web development as I’ve been stuck in the IDE with python. I am developing web apps for pilots in airlines. How long does the runtime generally stay on the browser? Can a pilot download the runtime before their flight, stick their device in aeroplane mode and pyscript will continue its magic for the next few hours (as long as I have no calls to a server)?
Jeff Glass 19/12/2022 14:39
In theory yes, that would work. However, remember that PyScript lives within a single browser window - without some additional care to make the page at like a Progressive Web App or similar (where state and libraries are preserved/stored), if the pilot in your example were to refresh their browser window, the page would try to reload and their state would be lost (edited)
Avatar
Avatar
Jeff Glass
In theory yes, that would work. However, remember that PyScript lives within a single browser window - without some additional care to make the page at like a Progressive Web App or similar (where state and libraries are preserved/stored), if the pilot in your example were to refresh their browser window, the page would try to reload and their state would be lost (edited)
Ok, so just as it is with other web pages/apps today. Good to know.
Avatar
Avatar
char
@Jeff Glass heya, I am new to web development as I’ve been stuck in the IDE with python. I am developing web apps for pilots in airlines. How long does the runtime generally stay on the browser? Can a pilot download the runtime before their flight, stick their device in aeroplane mode and pyscript will continue its magic for the next few hours (as long as I have no calls to a server)?
tedpatrick 19/01/2023 14:04
See "service workers", it is essentially a js module that caches network resources. In tests, you can cache the entire pyscript/pyodide/whls dependencies and offline them locally. You need to load the url online, then depending on service worker caching you can work 100% offline in browser. We need to expose this in pyscript and make it easy but it works today.
Avatar
Avatar
tedpatrick
See "service workers", it is essentially a js module that caches network resources. In tests, you can cache the entire pyscript/pyodide/whls dependencies and offline them locally. You need to load the url online, then depending on service worker caching you can work 100% offline in browser. We need to expose this in pyscript and make it easy but it works today.
tedpatrick 19/01/2023 14:09
psw. Contribute to tedpatrick/psw development by creating an account on GitHub.
psw. Contribute to tedpatrick/psw development by creating an account on GitHub.
Avatar
Avatar
tedpatrick
See "service workers", it is essentially a js module that caches network resources. In tests, you can cache the entire pyscript/pyodide/whls dependencies and offline them locally. You need to load the url online, then depending on service worker caching you can work 100% offline in browser. We need to expose this in pyscript and make it easy but it works today.
Ok ill have a look at ‘service workers’
Avatar
i have a non pyscript question. i have a terminal app where im using the rich library and its live mode. i have an issue where live crashes in certain terminal sizes. when it happens i see the beginning of a thread traceback, but it gets cut off when rich paints to the screen. i have no idea how i can capture the full traceback and it's driving me nutts
Avatar
holy mother of god that took forever to figure out
02:45
had to disable python stdout buffering. so simple
✨ 1
Avatar
I need some help. I'm like New New to py but have been banging my head over a project I been trying to figure out and even chatgpt gave me a script to run that didn't work.(yeah computers are supposed to make our lives easier not have us yanking our hairs out) anyway here's what chatgpt spit out import iter [1, 2, 8, 9,] list(iter.combinations(numbers,3)) What this was was supposed to output is every combination possible with the numbers 1289, what I kept getting was a syntax error. Tried other scripts and zilch. Any idea what I'm doing wrong?
Avatar
Avatar
D∅Ē
I need some help. I'm like New New to py but have been banging my head over a project I been trying to figure out and even chatgpt gave me a script to run that didn't work.(yeah computers are supposed to make our lives easier not have us yanking our hairs out) anyway here's what chatgpt spit out import iter [1, 2, 8, 9,] list(iter.combinations(numbers,3)) What this was was supposed to output is every combination possible with the numbers 1289, what I kept getting was a syntax error. Tried other scripts and zilch. Any idea what I'm doing wrong?
Jeff Glass 07/02/2023 04:36
I think this may do the trick: import itertools numbers = [1,2,3,9] print(list(itertools.combinations(numbers, 3)))
👍 1
04:37
Here’s some more documentation on the itertools package, lots of useful combinatorial stuff there https://docs.python.org/3/library/itertools.html
04:38
I suspect chatGPT got itertools confused with the built-in function iter, even though that does something quite different https://docs.python.org/3/library/functions.html#iter
Avatar
Deleted User 07/02/2023 15:51
Is it possible to get information from a discord bot with py-script?
Avatar
@Deleted User depends on how the bot works, but if you can use requests for example, then yes (https://docs.pyscript.net/latest/guides/http-requests.html) (edited)
Avatar
Avatar
Jeff Glass
I think this may do the trick: import itertools numbers = [1,2,3,9] print(list(itertools.combinations(numbers, 3)))
You are awesome, thank you so much.it worked.
Avatar
anyone ever get pycharm to work with remote docker via ssh and docker-compose?
18:56
cant tell if EAP pycharm has it in here because it works or because it's a WIP
18:56
so far it isnt working for me
Avatar
Hello
Avatar
is there a way i can drop a file into a project root so it overrides a file in a site-package library. i have a hotfix for something and I dont want to update the whole library to deploy it
19:44
i also dont want to edit any scripts' import lines
Avatar
Avatar
hosler
is there a way i can drop a file into a project root so it overrides a file in a site-package library. i have a hotfix for something and I dont want to update the whole library to deploy it
Jeff Glass 05/03/2023 22:55
Does it need to be a whole file in the package or just a specific object? I’m sure you’ve already considered just monkey patching an object at runtime, more curious why it needs to be a whole file but just one file
Avatar
i think im just gonna copy files to the site-package location
22:57
basically i have a bunch of environments that all have different versions of the same library
22:57
and i have to hotfix a couple objects
Avatar
TobiasPitters 06/03/2023 13:21
@hosler: the standard way to do it is to clone the project and then install it via: pip install -e <projectname> -estands for editable. Then each update to the project is directly reflected in your virtualenv (if you're using one)
Avatar
thanks. doesnt really apply to my current situation since ive already installed the packages without -e, but it seems useful and i will consider using it in future deployments
Avatar
tedpatrick 07/03/2023 13:14
PyScript.com Beta Access for PyScript Discord Members https://bit.ly/psdcbeta (edited)
🚀 3
Avatar
ʟᴜᴍᴀ 30/03/2023 16:23
Hi ! Question, is it possible to sync MEMFS from a <py-script> tag and a pyodide instance from javascript ?
16:24
(i want to avoid use IDBFS since i dont think I can use it from python at all, and accessing files present in the py-script instance would make things greatly better)
Jeff Glass started a thread. 30/03/2023 18:04
prodigy7376 started a thread. 02/05/2023 18:45
Avatar
bugzpodder 23/05/2023 17:13
how do a user know which package is from python stdlib and doesn't need await micropip install, something like this list: https://github.com/jackmaney/python-stdlib-list/blob/master/stdlib_list/lists/3.9.txt I guess you can always import first and if its not available do micropip install but that just sound like not ideal
A list of Python Standard Libraries (2.6-7, 3.2-9). - python-stdlib-list/3.9.txt at master · jackmaney/python-stdlib-list
Avatar
You can see the list of unvendored, removed, and present but not working modules here: https://pyodide.org/en/stable/usage/wasm-constraints.html
Avatar
Jeff Glass 23/05/2023 18:17
And for what it's worth, the current release of PyScript (2023.03.1) is pinned to Pyodide 0.22.1, so you may want to reference the appropriate version of the docs for that version https://pyodide.org/en/0.22.1/usage/wasm-constraints.html
18:22
/unstable (main branch) is also on 0.22.1 by default for now... but someday the Pyodide 0.23 PR will be mergable 🤞 😅
Avatar
Avatar
Jeff Glass
/unstable (main branch) is also on 0.22.1 by default for now... but someday the Pyodide 0.23 PR will be mergable 🤞 😅
bugzpodder 23/05/2023 18:51
I built my own pyscript with pyodide 0.23.2 and it works fine. I also upgraded to panel v1.0.1 and bokeh v3.1.1 and they all work great (edited)
Avatar
Avatar
bugzpodder
I built my own pyscript with pyodide 0.23.2 and it works fine. I also upgraded to panel v1.0.1 and bokeh v3.1.1 and they all work great (edited)
Andrea Giammarchi 24/05/2023 08:57
do you mind sharing your project? I am working on a slightly different PoC myself and I'd be curious to see if we're aligned with simplification / ideas
Avatar
Avatar
Andrea Giammarchi
do you mind sharing your project? I am working on a slightly different PoC myself and I'd be curious to see if we're aligned with simplification / ideas
bugzpodder 24/05/2023 18:16
there isn't much to it. there is a react component which isn't helpful to you but here it is: https://github.com/Py4Js/pyscript-react/issues/1068#issuecomment-1559950370 there is an automatic import plugin based on https://github.com/pyscript/pyscript/pull/1099 It is actually very complicated to get automatic plugin install to work reasonably well but i've left a comment in the PR already discussing some of these issues. otherwise it's just stock pyscript built from main since you guys haven't had a release since March. I think the only noteworthy thing to note is that react components has its own state management so I cannot really use py-script and py-repl tags. I just use the other bits to work with the remote interpreter and pyodides. eg of the functions like display/HTML from pyscript. (edited)
Avatar
I was inspired by the pyscript raycaster demo to try some three.js integration. Specifically I wanted to convert some of the https://globe.gl demos (a higher level library for rendering a 3D globe with Three.js) into PyScript. I've got the most minimal example working, but I run into trouble when I try passing more complex objects to globe.gl. Here's a minimal example that works and renders a plain globe: index.html <!DOCTYPE html> <html lang="en"> <head> <title>Globe.gl Arcs Demo</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1"> <link rel="stylesheet" href="https://pyscript.net/releases/2023.03.1/pyscript.css" /> <script defer src="https://pyscript.net/releases/2023.03.1/pyscript.js"></script> <script src="//unpkg.com/globe.gl"></script> </head> <body> <py-script src="./main.py"></py-script> <div id="globeViz"></div> </body> </html> main.py import js from js import Globe Globe().globeImageUrl( '//unpkg.com/three-globe/example/img/earth-night.jpg' )(js.document.getElementById("globeViz")) (edited)
UI component for Globe Data Visualization using ThreeJS/WebGL
Avatar
I've created a PyScript/Panel app, but I get this warning that apparently comes from something Bokeh is doing under the hood and I don't want that warning being directly visible to users. Is it possible to switch off PyScript from displaying warnings in the browser? In the browser console is fine - I just don't want users seeing them. If this warning is a real issue I believe it is due to something Bokeh itself is doing. Warning comes from this line: https://github.com/bokeh/bokeh/blob/d45de8756e077cf5e2932141ecacc1dd4af0591b/src/bokeh/core/property/bases.py#L273 - I am visualizing some time series Pandas dataframe data and am using some datetime based widgets so I assume (this apparently spurious) warning is originating from that somehow. I'm using: Bokeh 3.1.1 Panel 1.1.0 Pyodide 0.23.3 Pyscript 2023.03.01
Interactive Data Visualization in the browser, from Python - bokeh/src/bokeh/core/property/bases.py at d45de8756e077cf5e2932141ecacc1dd4af0591b · bokeh/bokeh
Owen started a thread. 22/06/2023 00:51
Avatar
I had another (probably naïve) question. Is it or will it ever be possible to debug Python running with PyScript? I don't understand the WebAssembly / Pyodide / PyScript tech stack to know whether that could ever be done or not. I currently struggle with maintaining my PyScript apps as they become more complex and get more state and so far I have to resort to old school print debugging or snipping bits of code out and running them in normal Python environments and Jupyter to debug when logic goes wrong - but both ways are pretty onerous. I'm interested to hear what approaches others have used to manage complexity and diagnose issues. I'm currently trying to figure out if I should try to use conditional imports and checks to decouple the PyScript specific parts of my apps so I can just develop and run most of the app in a normal Python environment for debugging because the experience of diagnosing issues in PyScript can be so painful. (edited)
Avatar
Yeah we're working hard on solving this in a few different ways
15:48
Hopefully one of the next two releases of Pyscript will come with debugger support
👍 1
Avatar
That sounds great, a debugger would be such a useful addition.
Avatar
I am using the @when mechanism to respond to user input. when I create a new dom element dynamically it does not have the listener attached. Understandable. How do I attach it ? Should I have all the event code in an encapsulating class and then make a new instance, or put functions in functions, or ? Any hints as to the 'right thing' to do?
Avatar
I think this has been asked before a while ago but is it possible to use ipywidgets in PyScript? I had an old Panel/ipyleaflet demo I was interested to try porting to PyScript. I suppose I could try converting to Folium but it doesn't have all the features of ipyleaflet.
Jeff Glass started a thread. 27/06/2023 13:23
Jeff Glass started a thread. 27/06/2023 13:45
Avatar
Hi, not sure if this falls under pyscript-help or here. I always thought that python errors get raised via stderr. And pyscript docs say that stderr goes to the py-terminal. But when i have an error in the python code, i don't see any exceptions in the terminal, but i see a pre element with a class py-error. Am i wrong in the understanding that python errors go to stderr?
Avatar
Avatar
sai
Hi, not sure if this falls under pyscript-help or here. I always thought that python errors get raised via stderr. And pyscript docs say that stderr goes to the py-terminal. But when i have an error in the python code, i don't see any exceptions in the terminal, but i see a pre element with a class py-error. Am i wrong in the understanding that python errors go to stderr?
Andrea Giammarchi 12/09/2023 10:04
which version of PyScript are you running? anyway, the stderr in pyodide is a bit weird and not always possible to catch, inevitably ending up in devtools console as error but we also catch at the main/window level and show errors on the page. In PyScript Next you can disable the error via py-config or config attribute by writing plugins = ["!error"] if that bothers you, but also PyScript Next has no terminal (yet).
Avatar
Jeff Glass 12/09/2023 14:13
To build on what Andrea said, since it sounds like you’re using the current PyScript release (“PyScript Classic”) - you can use the stderr attribute of a py-script tag to route things written to stderr to a DOM element with a matching ID.
Avatar
Yes, I am running - https://pyscript.net/latest/pyscript.js which is giving me 2022.12.1.dev. Good to know, thanks for all that info. I'll try out the stderr attribute. I have a weird scenario actually. I am working on a react app which runs in an iframe on another app platform. So the py-script tag runs twice (still trying to figure out why), but based on another suggestion on this discord, I am running the python code using window.self.pyscript.interpreter.interpreter.runPythonAsync(code);. Does this also have all the stderr connections or only the py-script tag?
Avatar
Jeff Glass 12/09/2023 16:47
So to use the stderr attribute you would need to place the code inside a <py-script> tag; but you can also grab the Pyodide runtime itself (which is what pyscript.interpreter.interpreter is a reference to) a use the stdStderr function to provide your own handler: https://pyodide.org/en/0.23.2/usage/api/js-api.html#pyodide.setStderr
16:47
This will apply to the whole runtime and not just that one invocation of runPythonAsync, so may or may not be useful for your use case
16:48
(For what it's worth, we missed updating that version string in a couple releases - the /latest link right now points to what is actually 2023.05.1 😅 )
Avatar
Jeff Glass 12/09/2023 16:58
One way to confirm that that's true is to do from pyscript import when, which was only added in 2023.05.1
👍 1
Avatar
Avatar
Jeff Glass
So to use the stderr attribute you would need to place the code inside a <py-script> tag; but you can also grab the Pyodide runtime itself (which is what pyscript.interpreter.interpreter is a reference to) a use the stdStderr function to provide your own handler: https://pyodide.org/en/0.23.2/usage/api/js-api.html#pyodide.setStderr
setStderr didn't work, probably for the same reason the error didn't go to py-terminal in the first place. But i achieved what i wanted to do!! I am using xterm, so i added a try catch around window.self.pyscript.interpreter.interpreter.runPythonAsync(code); and sent the error to the xterm instance.
Avatar
Avatar
sai
setStderr didn't work, probably for the same reason the error didn't go to py-terminal in the first place. But i achieved what i wanted to do!! I am using xterm, so i added a try catch around window.self.pyscript.interpreter.interpreter.runPythonAsync(code); and sent the error to the xterm instance.
Andrea Giammarchi 12/09/2023 21:10
window.self.pyscript in JS means pyscript ... no need for window.self before, but I am not adding much to the issue/solution, I suppose, just spotted a double redundant reference 😇
😄 1
Avatar
Avatar
sai
setStderr didn't work, probably for the same reason the error didn't go to py-terminal in the first place. But i achieved what i wanted to do!! I am using xterm, so i added a try catch around window.self.pyscript.interpreter.interpreter.runPythonAsync(code); and sent the error to the xterm instance.
Jeff Glass 12/09/2023 23:51
Nice! Are you using the built-in xterm in the py-terminal or rolling your own?
Avatar
Avatar
Jeff Glass
Nice! Are you using the built-in xterm in the py-terminal or rolling your own?
Using the built-in xterm.
Avatar
Avatar
sai
Using the built-in xterm.
Jeff Glass 13/09/2023 04:46
Thanks - it’s useful info as we think about terminal integration for PyScript Next. @Andrea Giammarchi I did start work on that this week; not worth waiting on it to release, my time is limited on pushing it forward, but wanted to let you know I haven’t forgotten
Avatar
Avatar
Jeff Glass
Thanks - it’s useful info as we think about terminal integration for PyScript Next. @Andrea Giammarchi I did start work on that this week; not worth waiting on it to release, my time is limited on pushing it forward, but wanted to let you know I haven’t forgotten
Andrea Giammarchi 13/09/2023 09:31
awesome! please align with @antocuni on this as he also started exploring it and quite successfully so
09:33
I managed to have a blocking input() inside a worker
09:34
anyway, the stderr in pyodide is a bit weird and not always possible to catch
Let's make a 🧵
(edited)
Avatar
Avatar
antocuni
Andrea Giammarchi 13/09/2023 14:16
added a basic test based on this demo so that it's easy to test locally via npm run start reaching http://localhost:8080/test/terminal.html https://github.com/pyscript/pyscript/pull/1696
Description This MR simply adds a very basic terminal test page, originally created by @antocuni, with runtime code evaluation. Changes added test/termina.html added test/terminal.py Checklist ...
👍 1
Avatar
hello everyone i just had a small doubt, for some reason i am not able to run my turtle code using pyscript
19:36
this is the error its showing me
19:37
( I am new to coding)
19:37
pleasehelp
Avatar
Avatar
Boo :3
this is the error its showing me
Josh (EduBlocks) 28/09/2023 19:55
That's to be expected 🙂 Turtle uses Tkinter behind the scenes which has no browser based implemention, so Pyodide has removed turtle from the standard library
19:55
That being said, there are efforts that have got Turtle working with PyScript which you can use, let me find you a link!
20:00
This is based on an implemention from the Basthon project and ported to PyScript by our own @ntoll 🙂
Avatar
Avatar
Josh (EduBlocks)
This is based on an implemention from the Basthon project and ported to PyScript by our own @ntoll 🙂
we should really include this version of turtle.py with pyscript, so that import turtle works out of the box. It's not super clear what is the best way to do it, because currently the stdlib is bundled&downloaded directly by pyodide
Avatar
Avatar
antocuni
we should really include this version of turtle.py with pyscript, so that import turtle works out of the box. It's not super clear what is the best way to do it, because currently the stdlib is bundled&downloaded directly by pyodide
Andrea Giammarchi 30/09/2023 20:00
is there any way to hook into python imports and lazily download modules and patch these? (edited)
Avatar
Yes, there are import hooks. I'd like to experiment with lazy downloading of .py/.pyc files, but this can work only in the workers, because from the point of view of python importing a module is a sync operation
Avatar
I also wonder about our caching stoy, so that libs/modules that are dynamically downloaded don't have to be repeatedly fetched. I also wonder about this for folks visiting PyScript.com.... we automatically download the assests needed (Pyodide, MicroPython), so they're in the browser cache when they actually need them.
Avatar
!KubiFişko 02/10/2023 15:46
Cannot read properties of undefined (reading 'call') (edited)
15:46
<div id="app"> <p>Translate English into Pirate speak...</p> <input type="text" name="english" id="english" placeholder="Type English here..." /> <button py-click="translate_english">Translate</button> <div id="output"></div> <script type="py" src="./main.py" config="./pyscript.toml"></script> </div>
15:46
15:52
i use this
Avatar
Avatar
!KubiFişko
Click to see attachment 🖼️
Andrea Giammarchi 02/10/2023 15:57
a lovely and colorful screenshot but it's the content of the main.py file we're eventually interested in, I think 🙂 (edited)
15:58
also keep in mind latest RC blocks inputs and buttons until the bootstrap is done ... but maybe the issue is not you pressing the button before that happens?
Avatar
!KubiFişko 02/10/2023 15:59
this is same code in website import arrr from js import document def translate_english(event): input_text = document.querySelector("#english") english = input_text.value output_div = document.querySelector("#output") output_div.innerText = arrr.translate(english)
Avatar
Andrea Giammarchi 02/10/2023 16:00
I think we have a live demo in docs about this, have you checked it?
Avatar
!KubiFişko 02/10/2023 16:00
nope i just try first tutorial
Avatar
Andrea Giammarchi 02/10/2023 16:03
summoning @ntoll here
Avatar
Andrea Giammarchi 02/10/2023 16:09
for the sake of helping out ... this is the PyScript test folder demo: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width,initial-scale=1" /> <title>Arrr - Piratical PyScript</title> <link rel="stylesheet" href="https://pyscript.net/snapshots/2023.09.1.RC2/core.css" /> <script type="module" src="https://pyscript.net/snapshots/2023.09.1.RC2/core.js"></script> </head> <body> <h1>Arrr</h1> <p>Translate English into Pirate speak...</p> <input type="text" id="english" placeholder="Type English here..." /> <button py-click="translate_english">Translate</button> <div id="output"></div> <script type="py" src="./piratical.py" config="./piratical.toml"></script> </body> </html> import arrr from js import document def translate_english(event): input_text = document.querySelector("#english") english = input_text.value output_div = document.querySelector("#output") output_div.innerText = arrr.translate(english) packages = ["arrr"]
16:10
arguably, that from js import document should be instead from pyscript import document but from main, everything works as expected anyway
16:11
to clarify, first code is index.html second one is piratical.py and third one is piratical.toml
Avatar
!KubiFişko 02/10/2023 16:13
👍
Avatar
Jeff Glass 02/10/2023 16:18
Think this is an error in our docs, should be an external link
Avatar
Jeff Glass 02/10/2023 16:35
MkDocs treats a lot of things as relative urls (e.g. pyscript.com), which breaks them. Went through and adjusted these. Also adjusted relative links to preferred formatting (pointing to .md files)
17:04
That is a weird error. Thanks for the PR
Avatar
!KubiFişko 02/10/2023 17:50
only doc is this https://docs.pyscript.ne ? i don't know javascript i just know littlebit html and python
Avatar
!KubiFişko 02/10/2023 18:08
this little bit fun from pyscript import document def printTutorial(event): input_text = document.querySelector("#input") #input_text.value if input_text.value == "yes": output_div = document.querySelector("#output") output_div.innerText += "no this is not yes" + "\n" input_text.value = ""
18:10
how i add press keyboard event ?
Avatar
!KubiFişko 02/10/2023 19:36
pyscript can support key input control like if key["Return"]: like ?
Avatar
@!KubiFişko use the FFI to listen for keypress events..?
Avatar
!KubiFişko 03/10/2023 02:37
what is FFI?
Avatar
Avatar
!KubiFişko
what is FFI?
bugzpodder 03/10/2023 02:58
foreign function interface. pyodide can call js functions and js can call python functions defined in python.
Avatar
!KubiFişko 03/10/2023 03:02
this is not in pyscript ? i'm not python pro user (edited)
Avatar
Avatar
!KubiFişko
this is not in pyscript ? i'm not python pro user (edited)
bugzpodder 03/10/2023 03:05
sorry i meant to say pyscript uses pyodide so you can definitely use ffi.
Avatar
!KubiFişko 03/10/2023 03:07
i can't see key or keyboard word in this link ? only button (edited)
Avatar
Avatar
!KubiFişko
i can't see key or keyboard word in this link ? only button (edited)
maybe you want raw keyboard access like to make a game or a terminal ? (edited)
Avatar
Please help someone is using this pyscript along with many many other licenses
Avatar
Quick beginner question? With "PyScript 2023.11.2", what's the simplest method using from pyscript import document to select a <button> element with an ID and trigger from the onclick action?
Avatar
Avatar
Piers
Quick beginner question? With "PyScript 2023.11.2", what's the simplest method using from pyscript import document to select a <button> element with an ID and trigger from the onclick action?
Andrea Giammarchi 04/12/2023 09:09
document.getElementById('your-button').click() ?
Avatar
Avatar
Andrea Giammarchi
document.getElementById('your-button').click() ?
Thanks @Andrea Giammarchi, I'll try that 👍
Avatar
Andrea Giammarchi 04/12/2023 09:17
if it's about reacting to onclick instead you can document.getElementById('your-button').addEventListener('click', your_click_handler) where your_click_handler receives an event object with event things
Avatar
Superb. That covers both use cases and is exactly what I was looking for. Many thanks 🙏
👍 1
Avatar
Given the following JS approach 👇 var elements = document.getElementsByClassName("classname"); var myFunction = function() { var attribute = this.getAttribute("data-myattribute"); alert(attribute); }; for (var i = 0; i < elements.length; i++) { elements[i].addEventListener('click', myFunction, false); } What would be PyScript version using from pyscript import document 🤔 Example attempt: button_elements = document.getElementsByClassName('btn') def button_action_call(button): button_id = button.getAttribute("id") for button in button_elements: button.addEventListener('click', button_action_call, False) Thoughts, suggestions welcome
Avatar
Avatar
Piers
Given the following JS approach 👇 var elements = document.getElementsByClassName("classname"); var myFunction = function() { var attribute = this.getAttribute("data-myattribute"); alert(attribute); }; for (var i = 0; i < elements.length; i++) { elements[i].addEventListener('click', myFunction, false); } What would be PyScript version using from pyscript import document 🤔 Example attempt: button_elements = document.getElementsByClassName('btn') def button_action_call(button): button_id = button.getAttribute("id") for button in button_elements: button.addEventListener('click', button_action_call, False) Thoughts, suggestions welcome
Jeff Glass 05/12/2023 21:17
<button id="hi" class="btn">Hello!</button> <button id="bye" class="btn">Goodbye!</button> <script type="py"> from pyscript import window, document from pyodide.ffi import create_proxy #works in both Pyoide and Micropython elements = document.getElementsByClassName("btn") def handler(evt): id = evt.target.getAttribute("id") window.alert(id) for el in elements: el.addEventListener('click', create_proxy(handler)) </script>
21:18
Although the more 'PyScriptic' way is to just use the @when decorator: from pyscript import when @when('click', '.btn') def handler(evt): id = evt.target.getAttribute("id") window.alert(id) (edited)
👍🏻 1
Avatar
Many thanks @Jeff Glass I've just got the XMLHttpRequest js method working and sending an API request to a simple's Flask app through ngrok Now it's just sorting MQTT on the MicroController and we should have the MeArm controller working 👍
Avatar
As I'm using MicroPython I went with the create_proxy method which worked perfectly .. Thanks .. 🙏
Avatar
Avatar
Jeff Glass
Although the more 'PyScriptic' way is to just use the @when decorator: from pyscript import when @when('click', '.btn') def handler(evt): id = evt.target.getAttribute("id") window.alert(id) (edited)
@Jeff Glass I love the concept of @when. But still does not work when the elements are created dinamically.
Avatar
Avatar
Parviz O
@Jeff Glass I love the concept of @when. But still does not work when the elements are created dinamically.
Jeff Glass 05/12/2023 23:02
It’s true, and wasn’t designed to. But we’ve discussed an additional @whenever decorator that would, via a mutation observed, function dynamically. Hasn’t been high priority, but perhaps soon.
👍 1
Avatar
Avatar
Jeff Glass
It’s true, and wasn’t designed to. But we’ve discussed an additional @whenever decorator that would, via a mutation observed, function dynamically. Hasn’t been high priority, but perhaps soon.
thank @Jeff Glass Jeff
Avatar
Avatar
Piers
As I'm using MicroPython I went with the create_proxy method which worked perfectly .. Thanks .. 🙏
Andrea Giammarchi 06/12/2023 09:28
I think in MicroPython you never need create_proxy but for sure you never need that in workers, Pyodide or MicroPython ... for portability though, you might want to keep the code as it is.
Avatar
Brickblock1 07/12/2023 17:19
Hi, I am having some trouble figuring out why my code is resulting in this error:
17:20
I am trying to use pyfetch with this code and with pyfetch imported
17:20
Avatar
Jeff Glass 07/12/2023 17:37
Does your <script> tag that points to core.js have type="module"? <script type="module" src="https://pyscript.net/releases/2023.12.1/core.js"></script>
Avatar
Brickblock1 07/12/2023 17:39
no it doesn't ill see if that fixes it thx
17:40
I got a new problem now so that is "good" thanks again
👍 1
Avatar
Fireflexor 07/12/2023 18:47
hey, i'm trying to use a python library called pwiki to access the mediawiki API, but when i try to create a wiki object with the code wiki = Wiki(), which should try to create an object for wikipedia, as that's what it defaults to, i am met with a whole lot of errors
A Python library for effortlessly interacting with Wikipedia/MediaWiki
18:48
and i mean a whole lot of errors
18:48
this is not what i like being met with
Avatar
Avatar
Fireflexor
this is not what i like being met with
Jeff Glass 07/12/2023 19:28
Not an ideal presentation for sure, what you're seeing is every line of that Python traceback being emitted as it's own error... The critical line (not that it's obvious at all) is: ImportError: Cannot connect to HTTPS URL because the SSL module is not available
19:29
You can try adding ssl to your packages in py-config and see what happens. But, since it seems urllib3 is in play, you should consider adding pyodide-http to yout config as well and patching that library https://github.com/koenvo/pyodide-http
Avatar
Avatar
Jeff Glass
You can try adding ssl to your packages in py-config and see what happens. But, since it seems urllib3 is in play, you should consider adding pyodide-http to yout config as well and patching that library https://github.com/koenvo/pyodide-http
Fireflexor 07/12/2023 19:39
i added SSL and now i'm getting even more errors
19:39
so guess i'll try the other thing
19:41
can i get some help with doing so however, i'm really not sure what i'm doing when it comes to this stuff
Avatar
Avatar
Jeff Glass
Not an ideal presentation for sure, what you're seeing is every line of that Python traceback being emitted as it's own error... The critical line (not that it's obvious at all) is: ImportError: Cannot connect to HTTPS URL because the SSL module is not available
Josh (EduBlocks) 07/12/2023 20:18
This could be totally wrong, but I have seen an SSL module error when actually the issue is CORS because the API doesn't accept third-party client-side requests. @Fireflexor (edited)
Avatar
Fireflexor 07/12/2023 20:28
is there anything i can like do about that?
Avatar
Avatar
Fireflexor
is there anything i can like do about that?
Josh (EduBlocks) 07/12/2023 21:24
Actually, upon further thinking, I think i am wrong. I would definitely try Jeff's suggestion of pyodide-http.
Avatar
Avatar
Josh (EduBlocks)
Actually, upon further thinking, I think i am wrong. I would definitely try Jeff's suggestion of pyodide-http.
Fireflexor 07/12/2023 21:27
how exactly would i go about doing that?
21:27
i've read the thing but i don't really get how it all works
Avatar
Avatar
Fireflexor
how exactly would i go about doing that?
Josh (EduBlocks) 07/12/2023 22:16
So you'll want to add pyodide_http to your packages list in your pyscript.toml/config file and then add the following at the top of your python code. import pyodide_http pyodide_http.patch_all()
Avatar
Avatar
Josh (EduBlocks)
So you'll want to add pyodide_http to your packages list in your pyscript.toml/config file and then add the following at the top of your python code. import pyodide_http pyodide_http.patch_all()
Fireflexor 07/12/2023 22:19
doesn't seem to have worked, still getting errors
22:22
22:22
i'll be honest i haven't a clue what any of this means
Avatar
Josh (EduBlocks) 07/12/2023 22:27
aha! I think i see the answer
Avatar
Fireflexor 07/12/2023 22:30
mind telling me, since i sure as hell don't
Avatar
Josh (EduBlocks) 07/12/2023 22:32
oops sorry I pressed send too early 😄 Seems like my initial theory was indeed correct, third error is a cross origin one. Essentially wikipedia's CORS headers aren't allowing you to call their API from the browser, resulting in the errors you're seeing.
22:33
Unless you were to proxy their API, which (unless anyone has any better ideas than me) is quite difficult to do given you are using a pre-packaged python module
Avatar
Fireflexor 07/12/2023 22:34
well i don't actually plan on using wikipedia, i plan on using a game wiki that also uses wikimedia, which it works with
22:34
but i have the same problems with that
22:36
so, is there any way i can get this working, or can i just not access it's API from the browser?
Avatar
Josh (EduBlocks) 07/12/2023 22:39
I don't think so, but I wouldn't call myself a CORS expert either. (edited)
Avatar
Avatar
Fireflexor
so, is there any way i can get this working, or can i just not access it's API from the browser?
Jeff Glass 07/12/2023 23:10
StackOverflow implies that adding an origin header manually may do the trick https://stackoverflow.com/a/38921370/19718391
I'm trying to access Wikipedia using JavaScript and CORS. As far as I know, Wikipedia should support CORS: http://www.mediawiki.org/wiki/API:Cross-site_requests I tried the following script: create a
23:10
Sorry, on mobile or I’d try to demo it
Avatar
Avatar
Fireflexor
so, is there any way i can get this working, or can i just not access it's API from the browser?
the simplest way would be to host, secure and provide a CORS brooker eg https://github.com/Rob--W/cors-anywhere/ (edited)
Avatar
Avatar
Piers
Given the following JS approach 👇 var elements = document.getElementsByClassName("classname"); var myFunction = function() { var attribute = this.getAttribute("data-myattribute"); alert(attribute); }; for (var i = 0; i < elements.length; i++) { elements[i].addEventListener('click', myFunction, false); } What would be PyScript version using from pyscript import document 🤔 Example attempt: button_elements = document.getElementsByClassName('btn') def button_action_call(button): button_id = button.getAttribute("id") for button in button_elements: button.addEventListener('click', button_action_call, False) Thoughts, suggestions welcome
chris.laffra 08/12/2023 15:10
I like to use jQuery for this kind of code, in JavaScript, so when I wrote LTK, I simply wrapped LTK around jQuery as well as I could. With LTK, your code fragment could look like this.
Avatar
Avatar
Jeff Glass
StackOverflow implies that adding an origin header manually may do the trick https://stackoverflow.com/a/38921370/19718391
Fireflexor 08/12/2023 18:00
i did actually find that but couldn't figure out how to get it working with pwiki
18:00
so i've decided to just not use pwiki and try do it without
18:02
specifically i'm using a library called requests
18:03
also when i use pyodide_http.patch_all() it seems to give 2 errors in the console
18:03
everything works as inteneded but it annoys me
18:04
also may be something that could become an issue in the future
18:04
so i'd appreciate being told what and why those are
Avatar
Fireflexor 08/12/2023 20:42
ok right there's 8 of them now, this is becoming an issue
Avatar
Andrea Giammarchi 12/01/2024 10:04
IIRC those headers are set by Pyodide but I think you can ignore them as long as your request works.
10:04
apologies, either Pyodide or the patch_all() thing
Avatar
How to install package in pyscript?it says await micropip.install("pandas") where exactly to run ?
Avatar
@zobi you don't need to... just follow the configuration instructions (see especially this bit: https://pyscript.github.io/docs/2024.1.1/user-guide/configuration/#packages)
14:07
e.g. in a settings.json, if you want to use numpy, you'd have an entry something like this: { "packages": ["numpy"] } ....and you'd reference the settings like this: <script type="py" src="./main.py" config="./settings.json"></script>
Avatar
Avatar
ntoll
e.g. in a settings.json, if you want to use numpy, you'd have an entry something like this: { "packages": ["numpy"] } ....and you'd reference the settings like this: <script type="py" src="./main.py" config="./settings.json"></script>
How will i know whether the package is available to use or not?Is there any list of available packages?
Avatar
Avatar
zobi
How will i know whether the package is available to use or not?Is there any list of available packages?
06:58
you have some other wheels here that may not be in pyodide https://github.com/pygame-web/archives/tree/main/repo/pkg
06:58
mvp ones won't load on pyodide/pyscript just the wasm32_bi ones
Avatar
What if i can read a package from my local system? will i be able to use the package in pyscript environment?
Avatar
@zobi if it's a pure Python package, yes. Anything pure Python "just works" ™️
Avatar
chris.laffra 15/01/2024 12:53
@zobi you may need to add those files to your toml. Here is an example for an app I have that loads from local files system and from a remote location.
Avatar
I tried doing this throws an error https://_12.pyscriptapps.com/young-frost/latest/ I am new to pyscript file system.
Avatar
Avatar
zobi
What if i can read a package from my local system? will i be able to use the package in pyscript environment?
if they contain wasm packages some restrictions may apply (edited)
Avatar
Avatar
zobi
I tried doing this throws an error https://_12.pyscriptapps.com/young-frost/latest/ I am new to pyscript file system.
i think your csv file is corrupt it looks like xml (edited)
Avatar
Avatar
chris.laffra
@zobi you may need to add those files to your toml. Here is an example for an app I have that loads from local files system and from a remote location.
can you please share any example related to this?
Avatar
Avatar
zobi
can you please share any example related to this?
chris.laffra 16/01/2024 11:53
You can take a look at the LTK kitchensink, see https://github.com/laffra/ltk/blob/main/kitchensink.toml
LTK is a little toolkit for writing UIs in PyScript - laffra/ltk
Avatar
Avatar
chris.laffra
You can take a look at the LTK kitchensink, see https://github.com/laffra/ltk/blob/main/kitchensink.toml
I think i should explore it in detail.Mean while i have tried doing this https://_12.pyscriptapps.com/small-art/latest/ checkbox is treated as radio buttons prints only the first selected value.Any suggestions how can i differenciate it from radio buttons?
Avatar
Avatar
zobi
I think i should explore it in detail.Mean while i have tried doing this https://_12.pyscriptapps.com/small-art/latest/ checkbox is treated as radio buttons prints only the first selected value.Any suggestions how can i differenciate it from radio buttons?
chris.laffra 16/01/2024 13:31
I created a Pizza parlor to show how I would implement this using LTK: https://laffra.github.io/ltk/?tab=12
Avatar
Avatar
chris.laffra
I created a Pizza parlor to show how I would implement this using LTK: https://laffra.github.io/ltk/?tab=12
I really liked your implementation.I was thinking to try something simple single line of code using list.
Avatar
Avatar
chris.laffra
I created a Pizza parlor to show how I would implement this using LTK: https://laffra.github.io/ltk/?tab=12
Can you display total as well?
Avatar
@zobi Chris just used a label to present the numeric data rolled up into the display string. You might not do it like that if you wanted to sum the values separately. Probably suggest using a class then creating the label strings on the fly. So yes, he could show the price summed but its a visually attractive demo of ltk radio buttons...
Avatar
chris.laffra 17/01/2024 21:00
@zobi this entire UI should be data-driven, including the choices of pizza types and their prizes, instead of being hard-coded as we did. I was mostly showing how you could construct a dynamic UI from Python, rather than using static HTML. Both have their tradeoffs, of course.
Avatar
I was just trying the following code https://stackoverflow.com/questions/42130422/getting-user-inputs-from-html-form/77831859#77831859 and it was having total as well.
I want to be able to get the inputs that a user enters in my HTML form and be able to print them later on my website. I would love to be able to print all the user info with the selections they hav...
Avatar
Avatar
chris.laffra
@zobi you may need to add those files to your toml. Here is an example for an app I have that loads from local files system and from a remote location.
what is static in static/menu.py?
Avatar
How to add file along with package into my pyscript.toml? I tried https://_12.pyscriptapps.com/dark-bonus/latest/ separate read.txt i am able to read but after adding package shows blank.
Avatar
Avatar
zobi
what is static in static/menu.py?
chris.laffra 19/01/2024 10:27
"static/" is a folder in my app's source folders that is used by the web server to deliver files to the web browser. This is a standard pattern used by Flask: https://flask.palletsprojects.com/en/3.0.x/tutorial/static/
Avatar
Avatar
chris.laffra
"static/" is a folder in my app's source folders that is used by the web server to deliver files to the web browser. This is a standard pattern used by Flask: https://flask.palletsprojects.com/en/3.0.x/tutorial/static/
we don't have folders in the pyscript IDE?
Avatar
That's coming very soon @zobi
Avatar
Why terminal doesn't display @stackoverflow?
Avatar
Avatar
zobi
we don't have folders in the pyscript IDE?
chris.laffra 20/01/2024 11:26
When you are hosting an application yourself, from a server, you will need something like Flask or another web server. This is where I took the example from. I developed the app I mentioned using VS Code. On the hosted pyscript.com IDE, you do not have folders, but in other IDEs you do.
👍 1
Avatar
Avatar
ntoll
That's coming very soon @zobi
Does it allow external folder or just an empty folder where we can add files?
Avatar
You'll just be able to drag and drop folders from your local machine into the project on pyscript.com (as well as manually create dirs and drag files into them).
14:50
@zobi ^^^
Avatar
Avatar
ntoll
You'll just be able to drag and drop folders from your local machine into the project on pyscript.com (as well as manually create dirs and drag files into them).
Even the large size folders?Is there any size capacity?
Avatar
I'm not sure. @Martin will likely be able to tell you.
Avatar
Avatar
zobi
Does it allow external folder or just an empty folder where we can add files?
FabioRosado 25/01/2024 18:34
We have been working on supporting folders, both creation of empty or uploading whole folders into the editor. This feature is likely going to be released on Monday so we can tweak some small things 😄
🎉 2
Avatar
How can i clear the terminal output or the DOM output??
Avatar
can any one help me why this code displays blank spaces after display.https://_12.pyscriptapps.com/polished-forest/latest/
Avatar
Avatar
zobi
can any one help me why this code displays blank spaces after display.https://_12.pyscriptapps.com/polished-forest/latest/
anfroholic 28/01/2024 10:42
Not really sure what this html2text library is but it puts newlines at the end of the string If you print the repr you can see the characters. modifying the string with the .strip() method gets rid of whitespace characters. So now code like: from pyscript import display,HTML import html2text html_content = '<html>hello</html>' text_content = html2text.html2text(html_content) print(repr(text_content)) print(text_content.strip()) print(text_content.strip()) print(text_content.strip()) yields: 'hello\n\n' hello hello hello
Avatar
Avatar
anfroholic
Not really sure what this html2text library is but it puts newlines at the end of the string If you print the repr you can see the characters. modifying the string with the .strip() method gets rid of whitespace characters. So now code like: from pyscript import display,HTML import html2text html_content = '<html>hello</html>' text_content = html2text.html2text(html_content) print(repr(text_content)) print(text_content.strip()) print(text_content.strip()) print(text_content.strip()) yields: 'hello\n\n' hello hello hello
Thanks for helping.It's exactly what i wanted.
👍 1
Avatar
How can i write package "from csv import reader" in pyscript.toml?i mean for packages where we have "from" "import"
Avatar
Jeff Glass 30/01/2024 01:14
no need to include “csv” at all - pyscript.toml is for installing packages from PyPI (or similar)
01:14
csv is in the standard library, and included in PyScript/Pyodide
Avatar
so when I use gunicorn gevent with django, each worker gets a db connection. what about each greenlet? do they share the same connection?
Avatar
Avatar
Jeff Glass
no need to include “csv” at all - pyscript.toml is for installing packages from PyPI (or similar)
It's not just about csv. In general if i want to inculde package which has "from" and "import" in it. For say "from ipython import display" or "from math import sqrt"... How can i include it in packages?
Avatar
Avatar
FabioRosado
We have been working on supporting folders, both creation of empty or uploading whole folders into the editor. This feature is likely going to be released on Monday so we can tweak some small things 😄
Are the features released?How can i have access to them?
Avatar
Avatar
zobi
It's not just about csv. In general if i want to inculde package which has "from" and "import" in it. For say "from ipython import display" or "from math import sqrt"... How can i include it in packages?
Jeff Glass 30/01/2024 11:23
You would include the top level package in the toml file, and then write from package import somename into your Python code.
Avatar
Avatar
zobi
Are the features released?How can i have access to them?
FabioRosado 30/01/2024 12:09
We will release this feature today when we do a prod deploy 🙂
Avatar
Avatar
zobi
Are the features released?How can i have access to them?
FabioRosado 30/01/2024 16:48
We just deployed to prod, you should be able to create and upload folders now 😄
Avatar
Avatar
Jeff Glass
You would include the top level package in the toml file, and then write from package import somename into your Python code.
I tried doing this can you help with this?https://_12.pyscriptapps.com/yellow-lab/latest/
Avatar
Avatar
zobi
I tried doing this can you help with this?https://_12.pyscriptapps.com/yellow-lab/latest/
Jeff Glass 30/01/2024 17:16
You don't need to put math in the config file at all - since it's in the Python standard library https://docs.python.org/3/library/index.html and (almost) all of that is installed in Pyodide by default.
Avatar
Avatar
Jeff Glass
You don't need to put math in the config file at all - since it's in the Python standard library https://docs.python.org/3/library/index.html and (almost) all of that is installed in Pyodide by default.
yes it works .
🥳 1
Avatar
Avatar
zobi
How can i clear the terminal output or the DOM output??
print('\x1bc') clears the terminal.
Avatar
How can i display linkification of string on terminal?https://_12.pyscriptapps.com/broken-salad/latest/
Avatar
Without specifying the image names how can I read all images from a folder?
Avatar
Is it possible to use pyscript in jinja files?
09:28
i try it in flask app, but im using jinjax for the template engine instead of flask default render template, here is the code
09:40
here is the pys.py to manipulate the value of id value
09:41
138 bytes
09:41
when i ran it in flask, i got this error unfortunately( without pressing the + button)
09:42
Avatar
i manage to get it work by using jinja's url_for syntax, it would be like easy as this
11:24
Avatar
is it possible to pyscript to pass an attribute value from current html when being clicked on the button? Here is simple app, where i can add quantity of an item from this html
13:08
here is the code for addval function. since i dont know yet how to pass attribute parameter from bid (stands for button id) into pyscript, following function causes a bug where every item will be added by 1 if i press the button
13:09
any help will be appreciated...
13:10
I dont want to do the solutions manually where i have to create 4 functions to handle the addition, what if in instance i have 6 items instead of 4 and so on...
Avatar
Avatar
ReYu
I dont want to do the solutions manually where i have to create 4 functions to handle the addition, what if in instance i have 6 items instead of 4 and so on...
Jeff Glass 18/02/2024 15:55
You can use the getAttribute method on HTML elements to get their html attributes like bid https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute
15:58
You may want to retrieve the element the event was targeting using def addval(event) … event.target.getAttribute(bid) or similar
15:59
Sorry, I would show a better example but I’m currently on mobile
Avatar
Avatar
Jeff Glass
You can use the getAttribute method on HTML elements to get their html attributes like bid https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute
Thankyou so much for the help, now i can do it like this...
👍 1
Avatar
i hit another roadblock here, so what i want to do next is doing like database manipulation inside the pyscript here, what i just want to test out if i can import Item mysql model from flask app package, but i got this error instead
17:26
17:26
i know the code doesnt make sense at the line 9, but i just want to know if it can interact with app package. app is folder that i modularize or something like that for my flask app..., here is the structure of that folder
17:27
17:28
here is what inside of models.py
17:29
my config pyscript is like this idk if this correct or not...
Avatar
Jeff Glass 18/02/2024 17:41
The packages key installs packages from PyPI, or the Pyodide repo, or wheels that you’ve built yourself that are available at a URL. More info here: https://pyscript.recipes/2024.1.1/basic/installing-packages/
17:43
In order to import that package in PyScript, all of its modules would need to be made available in the browser. The files key in pyconfig is the way to do this, though it’s a lot to enumerate https://pyscript.github.io/docs/2024.1.3/user-guide/configuration/
17:43
I’m also not sure exactly what the intent is - you’re using flask to serve a page that includes PyScript, yes?
Avatar
okay thanks for the help
Avatar
Avatar
Jeff Glass
I’m also not sure exactly what the intent is - you’re using flask to serve a page that includes PyScript, yes?
yes
Avatar
I've read the documentation of the files options and i think that is the key, but still, idk how to implement it on my end... heere is what i do best
18:01
the error
Avatar
Jeff Glass 18/02/2024 18:17
Can you share the contents of your pyconfig?
Avatar
you mean the pyscript.json?
18:44
config='{"packages":["setuptools"], "files": {"{TO}" : "./flaskserver/app/", "{FROM}/init.py" : "{TO}", "{FROM}/models.py" : "{TO}"}}'
18:44
tbh, i dont know im doing in this configuration (edited)
Avatar
Jeff Glass 18/02/2024 18:49
So, files is a list of key/value pairs, mapping URLs to the place in the in-browser virtual filesystem to load them, so Python (in the browser) can get access to them. The exception is that any keys which are just an identifier surrounded by curly brackets defines a “placeholder”, whose value can be substituted into other keys or values for brevity
18:50
In your case, the first item in that list defines “{TO}” as a placeholder for ./flaskserver/app
18:50
I don’t think you currently have a definition for {FROM} though
Avatar
i tried to do it like this in the end and still got the error,, if i can import my own app folder inside the pyscript, it would be perfect for my webapp
03:24
03:24
i tried to setup with py env and still got the error unfortunately
Avatar
i found this article that talks about the packaging case just like mine, but still, i cant get it to work, im using case "Multiple Files, Preserving Folder Structure" https://jeff.glass/post/whats-new-pyscript-2022-12-1/#paths
The big changes in PyScript version 2022.12.1
04:09
i tried to do it like this
04:09
i got error like this well, atleast its different error now instead module app not found
Avatar
Avatar
ReYu
i got error like this well, atleast its different error now instead module app not found
Andrea Giammarchi 19/02/2024 09:23
to me it looks like __init__.py is not found and your server produces a 404 with HTML content 🤔
Avatar
Interesting... but it should be not 404 because i can still see the page
10:22
btw im using flask too here, i want to combine flask x pyscript
Avatar
Avatar
ReYu
any help will be appreciated...
the page is like this
Avatar
im scratching my head up until now since yesterday, if pyscript can import files from my own package (the flask package) it'd be great. For context i want to do database (or even payment) manipulation combined with flask sql alchemy and the pyscript it self
Avatar
Avatar
ReYu
im scratching my head up until now since yesterday, if pyscript can import files from my own package (the flask package) it'd be great. For context i want to do database (or even payment) manipulation combined with flask sql alchemy and the pyscript it self
Andrea Giammarchi 19/02/2024 11:11
pyscript runs in a browser, it cannot share anything with the server out of the box ... even same modules, these will be locked into the WASM runtime in the browser so you need to load an sqlite blob, as exmaple, and that will share nothing with the server (no changes, no nothing, it runs independently).
Avatar
i see, so the best thing i can do for now is to initialize sqlite database into the same database in pyscript, separately from my flask-sqlalchemy?
Avatar
Avatar
ReYu
i see, so the best thing i can do for now is to initialize sqlite database into the same database in pyscript, separately from my flask-sqlalchemy?
Andrea Giammarchi 19/02/2024 12:32
I don't know if there's a way to replicate via HTTP your local DB or send its replica to your server but you will be dealing with two completely different DBs and the synchronization will be on you and per each browser session/tab/user.
Avatar
you're right, tried it and got it like this, i hope pyscript will get better and better, the potential of this to be striving is kinda high ngl...
12:38
12:39
Avatar
Avatar
ReYu
Click to see attachment 🖼️
Andrea Giammarchi 19/02/2024 13:31
we can't replace servers out of the box ... specially with MySQL or PostgreSQL kind of DBs ... we could replace sqlite but it will still be persistent only per each user, if not instrumented differently by a backend ... we are constrained by Web standards and features which can go a long way but can't replace 100% what a server can do for security and other obvious reasons (as in access to local machine protocols, files, and whatnot).
13:32
if a library is meant to work through HTTP requests though, we might be able to provide the same functionality but then again, each used should authenticate a part and has its own restricted access or any user could ALTER TABLE prod ... as example.
Avatar
Why Py-script .html doesn't work inside a folder? In Py-charm IDE ,Py-scripts .html works inside a folder?
Avatar
Jeff Glass 20/02/2024 17:47
How do you mean, doesn't work inside a folder?
Avatar
index.html,main.py,pyscript.toml all three inside a folder. (edited)
Avatar
Jeff Glass 21/02/2024 04:56
They should work fine inside a folder? It might have something to do with the way your serving your files for development. What do you do when you want to serve/open an html page for development?
Avatar
I will just run the file in Py script . I tried this way . <py-config> [[fetch]] from = 'folder/' files = ['index.html','main.py','pyscript.toml'] </py-config> (edited)
Avatar
I am having trouble loading an updated package from pypi. The package is not part of the base pyodide packages (pyhfst). When I try to load the package, I get a version that was current until yesterday (February 25, 2024). I have tried all of the suggested alternate package loading strategies from the documentation (specifying the url of the wheel, specifying a version number, copying the wheel into a file that is loaded into the file system), but the first two still resulted in the old version being loaded as far as I can tell, and the last one just makes my script hang and the page never loads. For what it is worth, I did manage to get the updated version of the package for my native python3 installation via pip. Perhaps the problem is with micropip? (edited)
Avatar
I thought for a moment that perhaps my attempt to use a file that was loaded into the virtual memory system had an elementary mistake: the pyscript documentation says to use the prefix emfs://, but it looks like memfs:// is correct. Unfortunately my page still hangs when I try to import the package with the memfs prefix.
Avatar
(if you have read this and are pondering a response, can you say so?)
Avatar
Avatar
sautedman
(if you have read this and are pondering a response, can you say so?)
Jeff Glass 27/02/2024 00:02
Sounds like something odd going on indeed! Let’s centralize the convo over in #╰╸pyscript-help
Avatar
Where do deleted projects go?Is there any chance i can get my project back after deletion?
Avatar
@Martin @almart any idea how we can help @zobi - is there a way to get stuff back..?
Avatar
FabioRosado 21/03/2024 10:26
Hello currently when a project is deleted, they are gone so you wont be able to get it back
Avatar
@zobi there you have it. Sorry, we don't appear to be able to resurrect deleted projects. @FabioRosado many thanks for the answer matey!
Avatar
@zobi sorry to hear that. In the future, we're thinking about having a trash bin where deleted projects would go. (edited)
👍 1
Avatar
Marco Aprea 23/03/2024 17:40
hi
Avatar
elliot0x01 05/04/2024 09:50
Does micropython even support fetch yet ?
Avatar
Avatar
elliot0x01
Does micropython even support fetch yet ?
Yes it does.
Avatar
Avatar
AndrewD
Yes it does.
See recent discussion in #╰╸pyscript-docs
Avatar
Not sure why the following code displays none after print??Can anyone help?https://_12.pyscriptapps.com/late-silence/latest/
Sticker
Avatar
Avatar
zobi
Not sure why the following code displays none after print??Can anyone help?https://_12.pyscriptapps.com/late-silence/latest/
Andrea Giammarchi 08/04/2024 09:06
fun prints the value and return nothing ... or better, if it returns implicitly what print returns that's a None ... you are double printing in short.
09:06
return c instead or don't print(fun(a, b)) just fun(a, b) ... this is the same in native Python.
Avatar
Avatar
Andrea Giammarchi
fun prints the value and return nothing ... or better, if it returns implicitly what print returns that's a None ... you are double printing in short.
How can I print it for the DOM?
11:34
display(fun(a,b)) return none and fun(a,b) goes to terminal.
Avatar
Avatar
zobi
display(fun(a,b)) return none and fun(a,b) goes to terminal.
Andrea Giammarchi 09/04/2024 12:13
don't print in fun, return the value instead
12:14
def fun(x,y): c = f"{int(x)+int(y)}" return c
Avatar
Avatar
Andrea Giammarchi
don't print in fun, return the value instead
I know this would work but I was trying for multiple prints.
Avatar
Avatar
zobi
I know this would work but I was trying for multiple prints.
Andrea Giammarchi 11/04/2024 08:50
print in fun still return a value if you want to assign it or print it outside the func ... this is how Python works.
Avatar
I was asking solution for the following. https://_12.pyscriptapps.com/late-silence/latest/
Avatar
Avatar
zobi
I was asking solution for the following. https://_12.pyscriptapps.com/late-silence/latest/
Andrea Giammarchi 12/04/2024 10:43
def fun(x,y): c = f"{int(x)+int(y)}" print(c) print(x) print(y) return c
10:43
I already gave you the solution
Avatar
Avatar
Andrea Giammarchi
def fun(x,y): c = f"{int(x)+int(y)}" print(c) print(x) print(y) return c
I think here function returns a single value and I want the function to print all three values. The following example shows for terminal. Same think I am expecting for DOM. https://_12.pyscriptapps.com/late-silence/latest/
Avatar
where can I learn async await, I think I know it but always fail - I want to start async/await from zero
Avatar
Avatar
psi2kgcm
where can I learn async await, I think I know it but always fail - I want to start async/await from zero
Jeff Glass 15/04/2024 01:13
The tutorial video from mCoding is pretty good https://youtu.be/ftmdDlwMwwQ?si=-C-QFvvwGpYE-GYw
Avatar
Thanks, the whole mcoding page looks like gold mine 🪙
👍 1
Avatar
Avatar
zobi
Just wanted to check my console session works for others or not. https://www.pythonanywhere.com/shared_console/eabe11e6-ae14-4e92-8c2a-e9452a28b466
Andrea Giammarchi 17/04/2024 15:36
is this a yes?
Avatar
Avatar
Andrea Giammarchi
is this a yes?
Andrea Giammarchi 17/04/2024 15:38
FWIWI it works on both Chrome/ium, Edge, and Safari (Epiphany TP)
Avatar
And FFx too
👍 1
Avatar
Avatar
Andrea Giammarchi
is this a yes?
Fails on mobile and incognito mode
Avatar
Avatar
zobi
Fails on mobile and incognito mode
Andrea Giammarchi 18/04/2024 12:35
this works on mobile though ... https://webreflection.github.io/coincident/test/pyterminal/ so it's not on us, I would say
Avatar
Avatar
zobi
Fails on mobile and incognito mode
Yes it works.I was trying without login.Just another doubt why virtual environment is not added to the pyterminal? Because packages can't be installed in python environment.
Avatar
Avatar
zobi
Yes it works.I was trying without login.Just another doubt why virtual environment is not added to the pyterminal? Because packages can't be installed in python environment.
Andrea Giammarchi 19/04/2024 10:16
not sure I am following ... any concrete example?
Avatar
elliot0x01 19/04/2024 16:32
Did anyone successfully implemented Rich on pyscript yet ? I tried following Jeff's monkeypatch but I am getting errors 😐
Avatar
Avatar
elliot0x01
Did anyone successfully implemented Rich on pyscript yet ? I tried following Jeff's monkeypatch but I am getting errors 😐
rich/textual work on python-wasm, rich need no change and textual need a few lines to force workers to async mode
Avatar
Avatar
elliot0x01
Did anyone successfully implemented Rich on pyscript yet ? I tried following Jeff's monkeypatch but I am getting errors 😐
Jeff Glass 19/04/2024 20:51
That monkey patch blog post is wicked old, it actually pre-dates the py-terminal 😅 I should probably mark it as deprecated. But in theory yes rich should run just fine - are you getting any output at all?
Avatar
Avatar
Andrea Giammarchi
not sure I am following ... any concrete example?
Like in the following image I am not able to import package. I came out of python to virtual env and installed the package and now I am able to import package. Was asking the same why pyterminal doesn't have the virtual env to install packages??
Avatar
Avatar
pmp-p
rich/textual work on python-wasm, rich need no change and textual need a few lines to force workers to async mode
elliot0x01 20/04/2024 09:18
I tried using rich with pyscript but not getting intended output on my end,
09:18
Avatar
elliot0x01 20/04/2024 09:27
So Rich seems to work but the colors are not being reflected on the terminal
Avatar
Avatar
elliot0x01
So Rich seems to work but the colors are not being reflected on the terminal
iirc you need to ask for them explicitely when not on a real TTY
09:30
smthing like "force_terminal on the rich console object"
Avatar
btw you should be able to inline image with something like sys.stdout.buffer.write( b"\x1b7\033]1337;File=inline=1:") sys.stdout.buffer.write( base64.b64encode(img.read()) ) sys.stdout.buffer.write( b"\a\x1b8") sys.stdout.flush()
🚀 1
🔥 1
09:58
you can also render pygame/panda3d in the terminal if that works ( see https://github.com/jerch/xterm-addon-image/issues/57) (edited)
Avatar
elliot0x01 20/04/2024 10:49
Thank you so much for the info
Avatar
Avatar
elliot0x01
Thank you so much for the info
Jeff Glass 20/04/2024 13:40
IIRC rich also tries to detect what colors the terminal it’s in can use via environment vars or something, but this fails in the browser and so no colors are output. Try adding this before your code: from rich.console import Console as RichConsole rich._console = RichConsole(color_system="256")
🥳 1
Avatar
elliot0x01 20/04/2024 15:04
Works like charm, rich looks super cool. Made an awesome looking portfolio with panels and layouts just the initial loading time for python is bit more compared to what it was for micropython :/
❤️ 1
Avatar
Avatar
elliot0x01
Works like charm, rich looks super cool. Made an awesome looking portfolio with panels and layouts just the initial loading time for python is bit more compared to what it was for micropython :/
Jeff Glass 20/04/2024 19:10
There’s a bit of old discussion about rich and micropython here: https://github.com/Textualize/rich/discussions/2065
I wanted to write a small (yet colourful) command line installer. So far I have been working with bash and some 3rd part libraries. Last nigh it struck me rich and a small foot print python (microp...
Avatar
Avatar
Jeff Glass
There’s a bit of old discussion about rich and micropython here: https://github.com/Textualize/rich/discussions/2065
elliot0x01 21/04/2024 06:56
Damnn...it never made it 😢
Avatar
Avatar
zobi
Like in the following image I am not able to import package. I came out of python to virtual env and installed the package and now I am able to import package. Was asking the same why pyterminal doesn't have the virtual env to install packages??
Andrea Giammarchi 22/04/2024 08:47
you need to specify packages in the config but if this lands any time soon you would be able to await python modules lazily (at runtime) https://github.com/pyscript/polyscript/pull/95
This MR would like to enable/allow our users to eventually lazily load modules as opposite of having these pre-fetched and already available via the config. It exposes a polyscript.lazy_py_modules(...
Avatar
Avatar
Andrea Giammarchi
you need to specify packages in the config but if this lands any time soon you would be able to await python modules lazily (at runtime) https://github.com/pyscript/polyscript/pull/95
Andrea Giammarchi 22/04/2024 08:48
there's no pip in PyScript, there's micropip in Pyodide and mip in MicroPython but these are not directly exposed to the running Python env
👍 1
Avatar
Following code displays content of the file. How can I display the outputs instead of content? https://_12.pyscriptapps.com/rapid-field/latest/
Avatar
elliot0x01 28/04/2024 16:09
I am trying to validate a domain in micropython but seems like complex re patterns are not supported in mpy, can anyone give me solution. The pattern I tried using is domain_pattern = r"^(?![0-9]+$)(?!-)(?:[a-zA-Z0-9-]{0,62}[a-zA-Z0-9]\.)+(?:[a-zA-Z]{2,})$"
16:10
Also, thank you so much @Andrea Giammarchi for fixing the mpy's display issue in latest release of pyscript 🥳
Avatar
elliot0x01 28/04/2024 16:20
Reduced the regex to this, domain_pattern = r"^[a-zA-Z0-9-]{1,63}\.[a-zA-Z]{2,}$" and it stop giving errors but for some wired reason it won't match even on valid input 🤔
16:21
inp=document.getElementById("inp") if(re.match(domain_pattern,str(inp.value))):
Avatar
Avatar
elliot0x01
I am trying to validate a domain in micropython but seems like complex re patterns are not supported in mpy, can anyone give me solution. The pattern I tried using is domain_pattern = r"^(?![0-9]+$)(?!-)(?:[a-zA-Z0-9-]{0,62}[a-zA-Z0-9]\.)+(?:[a-zA-Z]{2,})$"
Andrea Giammarchi 29/04/2024 08:32
I think you might have better luck in MicroPython repository as we don't get to change or control interpreters' internals
Avatar
Avatar
zobi
Following code displays content of the file. How can I display the outputs instead of content? https://_12.pyscriptapps.com/rapid-field/latest/
Got the solution but works perfectly on DOM not the terminal. https://_12.pyscriptapps.com/rapid-field-copy-copy/latest/
Avatar
Avatar
zobi
Got the solution but works perfectly on DOM not the terminal. https://_12.pyscriptapps.com/rapid-field-copy-copy/latest/
Andrea Giammarchi 29/04/2024 10:46
I am not following but display shows content on the DOM, not the terminal
10:47
the terminal is handled by XTerm.js and you better not inject DOM content explicitly in there or other things might break.
10:48
for the terminal you have process(code) to write code in the terminal but it might interaction but then again, I am not sure I understand what you are trying to do
Avatar
Avatar
Andrea Giammarchi
I am not following but display shows content on the DOM, not the terminal
I understood where I was going wrong. I corrected it.👍
Avatar
Can textarea have Python syntax highlighting?
Avatar
Avatar
zobi
Can textarea have Python syntax highlighting?
Jeff Glass 01/05/2024 14:30
You could use something like highlight.js to highlight it, or use a more fully featured editor block like codemirror or ace or monaco
Avatar
@zobi alas, a textarea's content cannot be styled. @Jeff Glass 's suggestion is probably best. Why not just use the <py-editor>: https://docs.pyscript.net/2024.4.1/user-guide/editor/ ???
Avatar
chris.laffra 01/05/2024 21:37
@zobi, if you use LTK, you can use the ltk.Code widget. It automatically highlights the code. The LTK Kitchensink uses the widget to render its code fragments. https://github.com/pyscript/ltk/blob/03bcd98b08c6545d2cdd5b428696142ce3518003/ltk/widgets.py#L799
LTK is a little toolkit for writing UIs in PyScript - pyscript/ltk
21:39
In PySheets, which is a PyScript application, I use CodeMirror to edit scripts. See https://pysheets.app
Avatar
chris.laffra 01/05/2024 21:48
So, depending on if you are just rendering or allowing people to edit, you have two choices.
Avatar
Avatar
ntoll
@zobi alas, a textarea's content cannot be styled. @Jeff Glass 's suggestion is probably best. Why not just use the <py-editor>: https://docs.pyscript.net/2024.4.1/user-guide/editor/ ???
I am trying for live code editor using python, CSS and html I don't think Py-editor will fit in. And in Py-editor I don't have control over the green run button😉 . (edited)
👍 1
Avatar
Then what @chris.laffra says is your best bet.
Avatar
How to clear the DOM?
Avatar
chris.laffra 02/05/2024 22:15
clear what? where? when? If you use LTK, it wraps jQuery, and with jQuery, to remove an element and all its children, you use ".remove()"
Avatar
Avatar
chris.laffra
clear what? where? when? If you use LTK, it wraps jQuery, and with jQuery, to remove an element and all its children, you use ".remove()"
I tried writing .remove() but it didn't clear in the example. https://_12.pyscriptapps.com/pyodide-create-proxy-demo-copy/latest/
Avatar
chris.laffra 03/05/2024 10:40
@zobi: this example shows how to add new elements to the DOM and how to remove them. Maybe that helps? https://pyscript.github.io/ltk/?tab=1
Avatar
Avatar
chris.laffra
@zobi: this example shows how to add new elements to the DOM and how to remove them. Maybe that helps? https://pyscript.github.io/ltk/?tab=1
yes,this will help me.
Avatar
Hi, I am having some difficulty passing a numpy array to JavaScript. It works fine for a while, then slows down considerably. I assume there is a memory leak somewhere but I can't find it. Below is my code. On the Python side, I have this:
14:04
def vertices(self, coordinates): proxy = create_proxy(coordinates.astype(np.float32)) self._instance.vertices(proxy) proxy.destroy() (edited)
14:04
on the JavaScript side I have this:
14:05
drawing.vertices = function(coordinates) { let buffer = coordinates.getBuffer(); for (let i = 0; i < buffer.data.length; i += 2) { this.vertex(buffer.data[i], buffer.data[i + 1]); } buffer.release(); coordinates.destroy(); }; (edited)
Avatar
Hmmmm, it seems if I change this.vertex to console.log, I don't see the performance tank. There must be some other JavaScript thing I don't understand at work here.
Avatar
I figured out my problem. It works fine now. Sorry taking up space here.
Avatar
Before I go, can someone tell me if all those calls to destroy() are necessary? How would I know if I had a memory leak in my code?
Avatar
And does that code successfully avoid a memory copy of my data? And how does that work, anyway? My python code can access the same memory space as the JavaScript code?
Avatar
Is there a PyPi stubb or something I can add, so Pylance plays nice with pyweb?
Avatar
Avatar
hx2A
Before I go, can someone tell me if all those calls to destroy() are necessary? How would I know if I had a memory leak in my code?
Andrea Giammarchi 06/05/2024 08:33
you have devtools to check memory leaks or consumption in your tab + an explicit button to perform garbage collection. About destroy() , when available (i.e. it's not a thing in MicroPython) you should always invoke it. Alternatively you can use experimental_create_proxy = "auto" in your py-config and see how that goes and forget about all these details but when you are in charge, we all know explicit is better than implicit.
🙏 1
Avatar
How to display DOM and terminal next to each other? (edited)
Avatar
Avatar
zobi
How to display DOM and terminal next to each other? (edited)
Andrea Giammarchi 07/05/2024 13:52
define next
Avatar
Avatar
Andrea Giammarchi
define next
Can you please share an example?
Avatar
Avatar
zobi
Can you please share an example?
Andrea Giammarchi 08/05/2024 12:25
it's eventually you needing to provide an example ... I don't understand your meaning of next there ... does it mean after ? does it mean before ? does it mean on the right or the left? what are you trying to do?
Avatar
Hi all, Can anyone please confirm if it is possible to pass a list from pyscript to respective html id and convert the list to separate html button
Avatar
Sorry I misunderstood your answer "define next" to be the solution to my question. mylist = iter(["apple", "banana", "cherry"]) x = next(mylist) so that's the reason was asking for an example.The following image displays DOM and terminal up and down.Can I display it left and right?
Avatar
Avatar
zobi
Sorry I misunderstood your answer "define next" to be the solution to my question. mylist = iter(["apple", "banana", "cherry"]) x = next(mylist) so that's the reason was asking for an example.The following image displays DOM and terminal up and down.Can I display it left and right?
Andrea Giammarchi 08/05/2024 20:32
use a container and CSS flexbox to keep it simple to make items beside each other? https://css-tricks.com/snippets/css/a-guide-to-flexbox/#aa-flex-direction
Our comprehensive guide to CSS flexbox layout. This complete guide explains everything about flexbox, focusing on all the different possible properties for the parent element (the flex container) and the child elements (the flex items). It also includes history, demos, patterns, and a browser support chart.
Avatar
Avatar
Andrea Giammarchi
use a container and CSS flexbox to keep it simple to make items beside each other? https://css-tricks.com/snippets/css/a-guide-to-flexbox/#aa-flex-direction
When I tried CSS it was being applied to the JS script not sure how to have control on the python script.
Avatar
Avatar
ntoll
@zobi alas, a textarea's content cannot be styled. @Jeff Glass 's suggestion is probably best. Why not just use the <py-editor>: https://docs.pyscript.net/2024.4.1/user-guide/editor/ ???
If I use Py-editor I am able to run the code only when I add my code in the textarea of my .html file and not during runtime.Runtime code doesn't display the result.In the image last print is not displayed because I added it at run time.How can I correct it?
Avatar
Floppypants 11/05/2024 22:33
How do I use Pyscript.com to make a simple drag and drop program using Pyscript? I tried one video, and could not read the code in the video. I tried another video and entered the code and it didn't work even after checking for typos. My function in the main.py file called handleFile(event) does not run. The first statement in handleFile(event) is print("Function is running."). I did a Google search and cannot seem to find anything like this. I'm on Windows 10 Home and using Pyscript.com account to make my test programs. I also turned off my Ad blocker for Pyscript.com. I also just signed up for Pyscript today. The Hello World program worked. This drag and drop program does not work. (edited)
22:37
Here's my main.py file. The message "This is main.py" does run. def handleFile(event): print("Function is running. Please wait...") # Get the dropped file object dropped_file = event.target.files[0] # Get the file object. # Access file information like name and size file_name = dropped_file.name file_size = dropped_file.size # Process the file content (read as bytes) file_content = dropped_file.read() # Perform actions on the file content based on your needs # (e.g., display information, upload to server) print(f"File Name: {file_name}, Size: {file_size}") # ... your processing logic here ... print("This is main.py") # This runs.
Avatar
Avatar
Floppypants
How do I use Pyscript.com to make a simple drag and drop program using Pyscript? I tried one video, and could not read the code in the video. I tried another video and entered the code and it didn't work even after checking for typos. My function in the main.py file called handleFile(event) does not run. The first statement in handleFile(event) is print("Function is running."). I did a Google search and cannot seem to find anything like this. I'm on Windows 10 Home and using Pyscript.com account to make my test programs. I also turned off my Ad blocker for Pyscript.com. I also just signed up for Pyscript today. The Hello World program worked. This drag and drop program does not work. (edited)
Jeff Glass 11/05/2024 22:40
Can you share your html as well? What are you doing to hook up handleFile as an event handler?
Avatar
Floppypants 11/05/2024 22:41
HTML FILE: <!DOCTYPE html> <html lang="en"> <head> <title>DragDrop1</title> <!-- Recommended meta tags --> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <!-- PyScript CSS --> <link rel="stylesheet" href="https://pyscript.net/releases/2024.5.1/core.css"> <!-- This script tag bootstraps PyScript --> <script type="module" src="https://pyscript.net/releases/2024.5.1/core.js"></script> </head> <body> Drag the file to the area below and wait for a message. You don't need to click a button or anything else. <p/> <input type="file" id="fileInput" onchange="handleFile(event)"> <p/> <script type="py" src="./main.py" config="./pyscript.toml" terminal></script> </body> </html> (edited)
22:42
There's not much in my pyscript.toml file. name = "DragDrop1"
22:43
I don't see an error window nor do I get any errors when I run it. (edited)
22:48
Ok I checked my Brave console and am getting this error: net::ERR_BLOCKED_BY_CLIENT. I think Brave also has a built-in blocker. I will try to turn it off.
22:50
I stopped the Brave shields for pyscript.com and now I get this browser console error when I run my program: Uncaught ReferenceError: handleFile is not defined at HTMLInputElement.onchange I'm not familiar with Javascript so I don't know what I would be doing wrong. (edited)
Avatar
Jeff Glass 11/05/2024 23:04
You'll want to use the py-change attribute for attaching event handlers, instead of onchange https://docs.pyscript.net/2024.5.1/user-guide/builtins/#html-attributes
👍 1
Avatar
You could use the drag example in the ltk kitchensink: https://pyscript.github.io/ltk/?tab=5
03:29
remember if you're dropping files you want to do a file upload like here: https://pyscript.recipes/2024.4.1/basic/file-upload/
Avatar
Floppypants 12/05/2024 19:03
@Jeff Glass @Neon22 Thanks all! I'll look at it later.
Avatar
Avatar
Neon22
remember if you're dropping files you want to do a file upload like here: https://pyscript.recipes/2024.4.1/basic/file-upload/
Floppypants 12/05/2024 22:04
I got this recipe working. Thanks!
Avatar
Avatar
Jeff Glass
You'll want to use the py-change attribute for attaching event handlers, instead of onchange https://docs.pyscript.net/2024.5.1/user-guide/builtins/#html-attributes
Floppypants 12/05/2024 22:12
What is https://pyscript.recipes? Is that site just for you to use? I'm not seeing a login page or About page. I thought I might browse some more recipes to see what they do to help me learn Pyscript. (edited)
Avatar
Jeff Glass 12/05/2024 22:15
That's a static site I publish as an additional source of guideance and tutorials for PyScript/Pyodide. It lives outside the docs, since it has a somewhat different style and goals.
👍 1
Avatar
Jeff Glass 12/05/2024 22:25
I spend a decent amount of time trying to answer questions on Discord - though as this server has grown there are more and more community members around to do the same. https://pyscript.recipes started as a central repository for code samples and explanations that I found myself typing in frequently, both here and on Stack Overflow 😅
Avatar
and uploading and downloading are excellent super useful recipes, thanks heaps @Jeff Glass
🎉 1
Avatar
Avatar
Floppypants
What is https://pyscript.recipes? Is that site just for you to use? I'm not seeing a login page or About page. I thought I might browse some more recipes to see what they do to help me learn Pyscript. (edited)
pyscript.recipes is awesome. If ever you meet Jeff in person, buy him a beer because he's built something amazing there.
Avatar
Avatar
Floppypants
How do I use Pyscript.com to make a simple drag and drop program using Pyscript? I tried one video, and could not read the code in the video. I tried another video and entered the code and it didn't work even after checking for typos. My function in the main.py file called handleFile(event) does not run. The first statement in handleFile(event) is print("Function is running."). I did a Google search and cannot seem to find anything like this. I'm on Windows 10 Home and using Pyscript.com account to make my test programs. I also turned off my Ad blocker for Pyscript.com. I also just signed up for Pyscript today. The Hello World program worked. This drag and drop program does not work. (edited)
Andrea Giammarchi 14/05/2024 13:18
as former AdBlock Plus core developer, what is the exact issue with Ads blockers, if I might ask?
I also turned off my Ad blocker for Pyscript.com ... Ok I checked my Brave console and am getting this error: net::ERR_BLOCKED_BY_CLIENT ...
this feels like screaming for a F.A.Q. entry to me, as I know how popular these browsers/extensions are ... please let me know what are your findings around these (I might test myself though).
Avatar
Avatar
ntoll
pyscript.recipes is awesome. If ever you meet Jeff in person, buy him a beer because he's built something amazing there.
Andrea Giammarchi 14/05/2024 13:19
+1 that, but also we have new documentation with some snippet in it, the upload is one of these: https://docs.pyscript.net/2024.5.2/faq/#upload
Avatar
How to change the color of button in Py-script?
Avatar
Avatar
Andrea Giammarchi
as former AdBlock Plus core developer, what is the exact issue with Ads blockers, if I might ask?
I also turned off my Ad blocker for Pyscript.com ... Ok I checked my Brave console and am getting this error: net::ERR_BLOCKED_BY_CLIENT ...
this feels like screaming for a F.A.Q. entry to me, as I know how popular these browsers/extensions are ... please let me know what are your findings around these (I might test myself though).
Floppypants 15/05/2024 11:46
I just turn off my ad blocker for any web sites I'm working on as a rule, to eliminate the ad blocker as a problem. There's no specific bug for my case. (edited)
👍 1
Avatar
The following code clears both DOM and terminal part. How can I make only the DOM part clear?? https://_12.pyscriptapps.com/summer-rain/latest/
Avatar
Avatar
chris.laffra
@zobi: this example shows how to add new elements to the DOM and how to remove them. Maybe that helps? https://pyscript.github.io/ltk/?tab=1
@chris.laffra do you have any example which will remove the DOM elements when the terminal is present?
Avatar
chris.laffra 23/05/2024 19:26
Not sure what you mean. a call like "ltk.find('#elementID').remove()" should work whatever else is present in the DOM.
👍 1
Avatar
What I understood is if it's a JavaScript DOM element I am able to delete using function Clear(){ document.getElementById('demo').innerHTML=''; } but display("hello world") this is python DOM element and python DOM element and terminal are connected and the clears terminal along with DOM. https://_12.pyscriptapps.com/summer-rain/latest/ Not sure how to clear python DOM alone. (edited)
Avatar
Avatar
zobi
What I understood is if it's a JavaScript DOM element I am able to delete using function Clear(){ document.getElementById('demo').innerHTML=''; } but display("hello world") this is python DOM element and python DOM element and terminal are connected and the clears terminal along with DOM. https://_12.pyscriptapps.com/summer-rain/latest/ Not sure how to clear python DOM alone. (edited)
Andrea Giammarchi 27/05/2024 09:54
to remove a DOM element use .remove() which is a standard API
Avatar
Avatar
Andrea Giammarchi
to remove a DOM element use .remove() which is a standard API
.remove() for Python DOM or the JavaScript DOM?
Avatar
Avatar
zobi
.remove() for Python DOM or the JavaScript DOM?
Andrea Giammarchi 28/05/2024 08:09
grab the node refrence then remove() ... I don't know if latest PyDOM has that method, LTK seems to be fine there.
Avatar
Avatar
Andrea Giammarchi
grab the node refrence then remove() ... I don't know if latest PyDOM has that method, LTK seems to be fine there.
I think I can't make the python DOM part completely disappear but the alternative is clear and update. It works fine in Py script but not the automated version of Py script. What could be the reason any idea?
Avatar
Even this doesn't work?
Avatar
Avatar
zobi
I think I can't make the python DOM part completely disappear but the alternative is clear and update. It works fine in Py script but not the automated version of Py script. What could be the reason any idea?
Andrea Giammarchi 29/05/2024 10:27
display has an append=True option by default, you pass append=False and it should clear/replace whatever was there before ... is this what you are asking? I am not sure I am following out of screenshots
Avatar
Avatar
Andrea Giammarchi
display has an append=True option by default, you pass append=False and it should clear/replace whatever was there before ... is this what you are asking? I am not sure I am following out of screenshots
I am not sure you are talking about JavaScript DOM or python DOM. If you can share an example I can understand seeing the code?
Avatar
johntimtemp 30/05/2024 05:04
hi
05:04
Is there any way to us matplotlib in py-editor?
05:05
I got this error "ModuleNotFoundError: The module 'matplotlib' is included in the Pyodide distribution, but it is not installed."
05:06
Avatar
Avatar
johntimtemp
Is there any way to us matplotlib in py-editor?
Andrea Giammarchi 30/05/2024 08:07
like with everything else, you need a config attribute that points at something like packages = ["matplotlib"] in it (if TOML)
Avatar
Avatar
zobi
I am not sure you are talking about JavaScript DOM or python DOM. If you can share an example I can understand seeing the code?
Andrea Giammarchi 30/05/2024 08:07
the display you are using as Python function, accepts an accpet=Flase which replaces the previous content
Avatar
johntimtemp 30/05/2024 08:30
Avatar
Avatar
johntimtemp
Click to see attachment 🖼️
Andrea Giammarchi 30/05/2024 08:33
the py-editor is not a py ... it's a different type, a different "beast", with a completely different environment ... you need to pass a config="./editor.toml" within that editor, the rest of the py scripts won't, and can't, also shouldn't, ever affect an editor
08:34
all this should be added to the docs, I'll file an issue around it
Avatar
johntimtemp 30/05/2024 08:38
08:38
08:38
no error , no display
08:39
I
08:39
I need call display function?
Avatar
Avatar
johntimtemp
I need call display function?
Andrea Giammarchi 30/05/2024 08:40
well, yes ...
08:40
I am rather worried about that deadlock message ...
08:41
it's hard to help out of screenshots though ... if only you could point at pyscript.com so we can have a look
08:45
btw, you can find matplotlib examples and see the source: https://pyscript.com/@examples/matplotlib/latest
Avatar
johntimtemp 30/05/2024 08:49
no need call display()
08:50
08:50
if just text output is ok, but Graphics output is failed
Avatar
johntimtemp 30/05/2024 09:01
I want show graphics result on the page, without use display(). Any suggestion?
Avatar
@johntimtemp why don't you want to use display() (out of interest).
Avatar
Avatar
ntoll
@johntimtemp why don't you want to use display() (out of interest).
johntimtemp 30/05/2024 11:00
just want purity python experience in <py-editor> , I want make a page for learn python, matplotlib ... , so non-python language should not appear
Avatar
@johntimtemp right, but I'd argue (playing devil's advocate here... this is totally your gig 😉 ) that display is just a Python-in-the-browser way of doing print
11:04
Basically, the alternative is to reimplement display
11:04
I.e. reach into the DOM, create a new image element, attach the data from MPL onto the img src and insert it into the DOM.
11:05
That's quite a few (messy?) steps hidden by display.
11:05
(Again, playing devil's advocate here...)
Avatar
johntimtemp 30/05/2024 11:07
Maybe hooks can help. https://docs.pyscript.net/2024.5.2/user-guide/plugins/ before run, do something
11:07
users just write the python part, hooks do the display()
11:09
but I found the hooks hard use in <py-editor> sad
Avatar
Sure. That's a possibility. But there's also a precedent for using display in IPython notebooks (they have a similar function).
11:10
At some point, with MPL, you need to tell it to display the plot, right..?
Avatar
johntimtemp 30/05/2024 11:10
yes indeed
Avatar
If you're in a notebook, you display it, if you're in PyScript, you display it. If you're in "vanilla" Python you plot.show() it right..?
11:11
Perhaps just explaini to the learners that there are different ways to display the plot, depending on the environment in which they're working. This is, in itself, an important lesson to learn. (edited)
11:11
(Again, devil's advocate... 😉 )
Avatar
johntimtemp 30/05/2024 11:13
Yes, it's should be known before they write code.
Avatar
OK. So (trying to save you effort here), if they already understand the contextual nature of how to display a plot, why not just use display..?
Avatar
johntimtemp 30/05/2024 11:15
fine
Avatar
Avatar
johntimtemp
fine
I tried text area instead of Py-editor it doesn't need display() and I got nice colorful bar plots.
Avatar
Avatar
johntimtemp
but I found the hooks hard use in <py-editor> sad
Andrea Giammarchi 30/05/2024 14:47
hooks are really for advanced usage ... in PyEditor though, you have a setup node where you can expose, override, or change the print function to have it do whatever you like if the file="element-id" is used, as example, so that you would display instead of using the builtin print
14:48
print(image, file="#css-selector")
14:48
as example, could override default print but as you still need to tell Python where to print stuff, I don't find it particularly better than display where the intent is explicit.
14:49
arguably you could instead check the print(arg) in there and, if it's not a string, use display behind the scene ... maybe that's a bit better
Avatar
Avatar
zobi
I tried text area instead of Py-editor it doesn't need display() and I got nice colorful bar plots.
Andrea Giammarchi 30/05/2024 14:51
I don't understand what you mean there but if it's another project, they might have their own overrides for some module (I suppose) otherwise I am not sure python modules for WASM automagically do weird things but that looks like it would always append new charts, as example, or maybe not? it'd be lovely to see what you have there in pyscript.com to have a look and help more.
Avatar
Avatar
johntimtemp
just want purity python experience in <py-editor> , I want make a page for learn python, matplotlib ... , so non-python language should not appear
Andrea Giammarchi 30/05/2024 14:54
out of curiosity, what does Python REPL do when you do that? wouldn't it just create a buffer of the image and give you back that instead? how would you show (ahem, display) that image in a terminal with pure Python? 🤔 Honest question, as I've never even tried that.
Avatar
with IIP or sixel, btw Panda3D/pygame-ce support that quite easily (edited)
15:26
15:29
and i think i've heard someone is working on adding some image support to Textual https://github.com/Textualize/rich/discussions/384#discussioncomment-9286378 (edited)
Hi Will, I was wandering if you had any plan about adding support for images in rich? Or something like ascii drawings (e.g. see braille)? Cheers, Fede
Avatar
Andrea Giammarchi 30/05/2024 15:37
would that work via SSH too? it's pretty awesome but a bit too much magic to me 😅 ... although even in good ol DOS days I could play games so maybe that's fine.
15:38
@ntoll I don't have any strong opinion but imho if this stuff works on terminal out of just print maybe we should think about improving the current state and use display behind the scene automagically? seems like other pakcages are able to do that (or not require print at all but I don't understand how that would work).
Avatar
Avatar
Andrea Giammarchi
would that work via SSH too? it's pretty awesome but a bit too much magic to me 😅 ... although even in good ol DOS days I could play games so maybe that's fine.
indeed it does on SSH , and also is the only graphic output device you could have to run a wasi program which makes it still very usefull ( above screenshot is python 3.13 wasi running Panda3D on wasmtime ) , and for the original real thing ( the DEC terminal ) iirc it was around DOS 3.0. (edited)
Avatar
WOW - that's pretty cool. Playing something like good old DOS games 🤣 ... come back Dune2, all is forgiven. 😉 If we can make this as easy as possible for folks, I vote we make it happen. 😉
Avatar
Avatar
zobi
I tried text area instead of Py-editor it doesn't need display() and I got nice colorful bar plots.
johntimtemp 31/05/2024 01:28
I think this is CodeMirror too
Avatar
Avatar
johntimtemp
I think this is CodeMirror too
Yes this is CodeMirror too.As of now not everything which works in Py-script works here but still trying to figure them out.
Avatar
Avatar
Andrea Giammarchi
I don't understand what you mean there but if it's another project, they might have their own overrides for some module (I suppose) otherwise I am not sure python modules for WASM automagically do weird things but that looks like it would always append new charts, as example, or maybe not? it'd be lovely to see what you have there in pyscript.com to have a look and help more.
https://_12.pyscriptapps.com/noisy-math-copy-copy-copy-copy/latest/ even I am not sure why it displays multiple colors. For every run it was suppose to display new plot since I am still working on display (accept=False)but for this it displays single plot with multiple colors.
Avatar
Avatar
zobi
https://_12.pyscriptapps.com/noisy-math-copy-copy-copy-copy/latest/ even I am not sure why it displays multiple colors. For every run it was suppose to display new plot since I am still working on display (accept=False)but for this it displays single plot with multiple colors.
johntimtemp 31/05/2024 09:24
the color is not a problem
👍 1
Avatar
Avatar
zobi
https://_12.pyscriptapps.com/noisy-math-copy-copy-copy-copy/latest/ even I am not sure why it displays multiple colors. For every run it was suppose to display new plot since I am still working on display (accept=False)but for this it displays single plot with multiple colors.
johntimtemp 31/05/2024 09:25
accept=False is more important
👍 1
Avatar
johntimtemp 31/05/2024 09:52
👍 1
Avatar
Avatar
zobi
https://_12.pyscriptapps.com/noisy-math-copy-copy-copy-copy/latest/ even I am not sure why it displays multiple colors. For every run it was suppose to display new plot since I am still working on display (accept=False)but for this it displays single plot with multiple colors.
Andrea Giammarchi 31/05/2024 11:12
I see you are using exec function https://docs.python.org/3.12/library/functions.html#exec and I think pyodide does something magic in there ... that's still a command you need to run as opposite of using display which doesn't need you to evaluate the whole thing ... it gives you more fine tuned control within the code you run.
The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order.,,,, Built-in Functions,,, A, abs(), aiter(), all(), a...
11:13
it's not clear to me how builtins work in exec but I suppose these are smart enough to append to the body the latest image. You also have less control of where you want to show the image but regardless this is an interesting feature of pyodide
Avatar
Avatar
Andrea Giammarchi
display has an append=True option by default, you pass append=False and it should clear/replace whatever was there before ... is this what you are asking? I am not sure I am following out of screenshots
What is the syntax for display append=False? I didn't find anything in the documentation. I tried the following display("hello",append="false")
Avatar
Avatar
zobi
What is the syntax for display append=False? I didn't find anything in the documentation. I tried the following display("hello",append="false")
in python False (with a capital) is the correct term. display("hello", append=False) (edited)
Avatar
Avatar
zobi
What is the syntax for display append=False? I didn't find anything in the documentation. I tried the following display("hello",append="false")
docs for display are here: https://docs.pyscript.net/2024.2.1/user-guide/builtins/ don't forget the target= keyword if you want to stick the output somewhere specific instead of at the end of the doc (edited)
22:38
actually that's 2024.2.1 now at 2024.5.2 but display remains unchanged... (edited)
Avatar
Avatar
Neon22
docs for display are here: https://docs.pyscript.net/2024.2.1/user-guide/builtins/ don't forget the target= keyword if you want to stick the output somewhere specific instead of at the end of the doc (edited)
Thanks for helping it worked.
Avatar
Can someone help me with this code. Not sure why it's not displaying the result https://_12.pyscriptapps.com/noisy-math-copy-copy-copy-copy-copy/latest/
Avatar
Avatar
zobi
Can someone help me with this code. Not sure why it's not displaying the result https://_12.pyscriptapps.com/noisy-math-copy-copy-copy-copy-copy/latest/
I can't work out what you're doing :(. The main.py is basically empty, the toml file is loading heaps of packages you are not using. You seem to be wanting to run the contents of a textarea. This seems like a dangerous security problem if you got it working. Please reconsider your approach. Why not use the pyeditor as shown here https://docs.pyscript.net/2024.5.2/user-guide/editor/ (I am assuming you want to show code and run that code and see the results of running that code.) Sorry but just don't understand what your goal is... 😦
Avatar
Andrea Giammarchi 03/06/2024 08:45
FYI we have a lazy way to load packages on demand, as opposite of requiring these in the TOML prematurely
08:45
will be documented soon
Avatar
Avatar
Andrea Giammarchi
FYI we have a lazy way to load packages on demand, as opposite of requiring these in the TOML prematurely
Oh that would be awesome.😀
Avatar
Avatar
Neon22
I can't work out what you're doing :(. The main.py is basically empty, the toml file is loading heaps of packages you are not using. You seem to be wanting to run the contents of a textarea. This seems like a dangerous security problem if you got it working. Please reconsider your approach. Why not use the pyeditor as shown here https://docs.pyscript.net/2024.5.2/user-guide/editor/ (I am assuming you want to show code and run that code and see the results of running that code.) Sorry but just don't understand what your goal is... 😦
I am trying to make https://_12.pyscriptapps.com/icy-haze/latest/ work in https://_12.pyscriptapps.com/noisy-math-copy-copy-copy-copy-copy/latest/ as well. In Py-editor there is no display and only prints so it's not possible to display the html part I think. I can probably try using old version Py-editor(but few imports won't work in the old version).In python we have both html and python and html is only the run button so I thought to get everything to python.I have added beginner level packages in .toml so we don't need to install them every time.It will be great if you can suggest something. (edited)
Avatar
Avatar
zobi
I am trying to make https://_12.pyscriptapps.com/icy-haze/latest/ work in https://_12.pyscriptapps.com/noisy-math-copy-copy-copy-copy-copy/latest/ as well. In Py-editor there is no display and only prints so it's not possible to display the html part I think. I can probably try using old version Py-editor(but few imports won't work in the old version).In python we have both html and python and html is only the run button so I thought to get everything to python.I have added beginner level packages in .toml so we don't need to install them every time.It will be great if you can suggest something. (edited)
I think it works this way https://_12.pyscriptapps.com/noisy-math-copy-copy-copy-78391/latest/ .Is there any way I can get the script tag to the text area and main.py file will display instead of the code?
Avatar
Andrea Giammarchi 04/06/2024 18:00
@zobi display is from pyscript ... from pyscript import display ... what do you mean there's no display in the PyEditor? the pyscript namespace is there.
Avatar
Avatar
Andrea Giammarchi
@zobi display is from pyscript ... from pyscript import display ... what do you mean there's no display in the PyEditor? the pyscript namespace is there.
Andrea Giammarchi 04/06/2024 18:03
to be honest, I don't understand why you keep trying to avoid the PyEditor as it is ... if you orchestrate through your own textarea it's hard for us to provide any meaningful support out of the box
18:03
if interested, with tomorrow release you'll have also script.code and script.code = "print(1 + 2)" as PyEditor script tag feature.
18:03
not sure that solves everything you need to solve though
Avatar
Avatar
Andrea Giammarchi
@zobi display is from pyscript ... from pyscript import display ... what do you mean there's no display in the PyEditor? the pyscript namespace is there.
As of what I know there is no display in PyEditor and print goes to DOM in PyEditor.
Avatar
Avatar
Andrea Giammarchi
to be honest, I don't understand why you keep trying to avoid the PyEditor as it is ... if you orchestrate through your own textarea it's hard for us to provide any meaningful support out of the box
I was told there are two different sources and I observed that if code displays in the source1 only then I can deploy the application.You can help me make the souces1 same as the source2 only then I can make use of PyEditor.
Avatar
johntimtemp 05/06/2024 04:04
pyscript is design for use python write html website, so use display() or not is not very important. If you just want use python in Browser, maybe you should try other way @zobi And indeed there is many other ways
04:06
and pyscript has a defect: slow. Loading data slow and first run slow.
Avatar
Avatar
zobi
As of what I know there is no display in PyEditor and print goes to DOM in PyEditor.
Andrea Giammarchi 05/06/2024 08:56
I just tried this without any issue whatsoever: <script type="mpy-editor"> import sys from pyscript import display display(sys.version, target="the_target", append=False) </script> <div id="the_target"></div> I'd like to add that if that's the default behavior you want, you can create a setup node and override the print function to use display instead and the target you want as node to show things. (edited)
Avatar
Avatar
johntimtemp
and pyscript has a defect: slow. Loading data slow and first run slow.
Andrea Giammarchi 05/06/2024 08:58
you mean pyodide, right? try micropython instead and move pyodide to a worker if needed for more complex modules/computations. It's true that we're not using the lockfile yet for pyodide only but that won't solve the first load, as it needs to be generated anyway yet it might be faster next time ... still, pyodide bootstrap with zero dependencies takes more than a second on average, it's not PyScript being slow, it's Pyodide being very complete and full of features. Again, <script type="mpy"> is not there by accident so when bootstrap performance matters, feel free to use it.
Avatar
Avatar
Andrea Giammarchi
I just tried this without any issue whatsoever: <script type="mpy-editor"> import sys from pyscript import display display(sys.version, target="the_target", append=False) </script> <div id="the_target"></div> I'd like to add that if that's the default behavior you want, you can create a setup node and override the print function to use display instead and the target you want as node to show things. (edited)
Andrea Giammarchi 05/06/2024 09:06
example: <script type="mpy-editor" env="print-override" setup> from pyscript import display def print(what, target=None, append=False): if target is None: target = "the_target" display(what, target=target, append=append) </script> <script type="mpy-editor" env="print-override"> import sys print(sys.version) </script> <div id="the_target"></div> (edited)
Avatar
Avatar
Andrea Giammarchi
I just tried this without any issue whatsoever: <script type="mpy-editor"> import sys from pyscript import display display(sys.version, target="the_target", append=False) </script> <div id="the_target"></div> I'd like to add that if that's the default behavior you want, you can create a setup node and override the print function to use display instead and the target you want as node to show things. (edited)
Yes.Throws value error but still works.displays only if target is given i think. (edited)
Avatar
Avatar
zobi
Yes.Throws value error but still works.displays only if target is given i think. (edited)
Andrea Giammarchi 05/06/2024 11:30
you need to specify a target with a valid ID
Avatar
Avatar
Andrea Giammarchi
you need to specify a target with a valid ID
print and display both goto DOM i think?
Avatar
Has anyone used service workers with PyScript? (Not web workers... I mean service workers as defined here: https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers ) Or better yet, has anyone made a PWA?
This article provides information on getting started with service workers, including basic architecture, registering a service worker, the installation and activation process for a new service worker, updating your service worker, cache control and custom responses, all in the context of a simple app with offline functionality.
14:01
(I found this, https://pyscript.com/@6fd75ce3-df0a-4384-b255-195e41c4f02f/service-worker-example/latest, but it seems to be an example of someone implemeneting a service worker in JavaScript and using it alongside Pyodide, not really writing the actual service worker in Python, which is my goal)
Avatar
Avatar
bouncing
Has anyone used service workers with PyScript? (Not web workers... I mean service workers as defined here: https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers ) Or better yet, has anyone made a PWA?
Jeff Glass 05/06/2024 15:22
It's a little bit older, but you should check out the pyscript.sw chunk of the PyScript repo. It's a demo of bootrapping pyodide in a service worker, and using a FastAPI app to provide 'backend' responses in the browser
15:23
One of my tinkering projects since PyCon has been trying to run pypiserver in a service worker, so you can run pip on the frontend (as a teaching tool for pip). Not quite there yet, but it's been interesting to try. Using httpx's AsyncClient like pyscript.sw does is hugely helpful - most server clients assume the existance of threads
Avatar
Avatar
zobi
print and display both goto DOM i think?
Andrea Giammarchi 05/06/2024 16:00
these do what you want these to do ... by default, the editor print on the DOM as that's a direct feedback people expect, as opposite of needing to open devtools and see nothing on the page.
16:00
the display is simply there because it's part of pyscript namespace ... it has no default target node because codemirror is a different thing as target, is where you want your code to be highltagted and worked on
Avatar
Avatar
Jeff Glass
It's a little bit older, but you should check out the pyscript.sw chunk of the PyScript repo. It's a demo of bootrapping pyodide in a service worker, and using a FastAPI app to provide 'backend' responses in the browser
Thanks, I'll take a look at that!
Avatar
Avatar
zobi
I think it works this way https://_12.pyscriptapps.com/noisy-math-copy-copy-copy-78391/latest/ .Is there any way I can get the script tag to the text area and main.py file will display instead of the code?
<iframe> </iframe>displays the main.py code. But I am getting attribute error not sure why. Can someone help me with it? Is there any alternate solution? https://_12.pyscriptapps.com/dry-voice-copy-copy-copy-86086/latest/
Avatar
Avatar
zobi
<iframe> </iframe>displays the main.py code. But I am getting attribute error not sure why. Can someone help me with it? Is there any alternate solution? https://_12.pyscriptapps.com/dry-voice-copy-copy-copy-86086/latest/
Can you post a link to where the source lives?
Avatar
Avatar
bouncing
Can you post a link to where the source lives?
I solved it by myself.😀
👍 1
Avatar
How to make <iframe></iframe> content editable?I tried contenteditable="true" but it makes the html display editable.https://_12.pyscriptapps.com/restless-water/latest/
Avatar
Avatar
zobi
How to make <iframe></iframe> content editable?I tried contenteditable="true" but it makes the html display editable.https://_12.pyscriptapps.com/restless-water/latest/
Andrea Giammarchi 11/06/2024 14:34
this is not really a Python related question, rather an HTML one 😉 https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/contenteditable
The contenteditable global attribute is an enumerated attribute indicating if the element should be editable by the user. If so, the browser modifies its widget to allow editing.
14:35
the iframe is a "window" to another page, you want to edit content in that page, not within the iframe itself, I suppose
Avatar
Avatar
Andrea Giammarchi
this is not really a Python related question, rather an HTML one 😉 https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/contenteditable
Is there any other way to make it editable?
Avatar
Avatar
zobi
Is there any other way to make it editable?
Andrea Giammarchi 11/06/2024 16:22
what is an editable iframe if I might ask?
Avatar
Some thing like https://codepen.io/mturek/pen/oZwBee .you should be able to change the text inside iframe. (edited)
Avatar
Avatar
Andrea Giammarchi
what is an editable iframe if I might ask?
I tried a little more "edit button" will edit the code inside the iframe which is done.I want to make changes in edit and "save button" has to append it back to iframe.I am struck in that. Can some one help?https://_12.pyscriptapps.com/important/latest/
Avatar
Avatar
zobi
I tried a little more "edit button" will edit the code inside the iframe which is done.I want to make changes in edit and "save button" has to append it back to iframe.I am struck in that. Can some one help?https://_12.pyscriptapps.com/important/latest/
Andrea Giammarchi 12/06/2024 13:38
honestly ... the whole thing is editable, I can't even click on View Code so it's hard to help but it looks to me you are doing something not meant to be done with that property and removing the ability to even see its source code is not nice at all.
13:39
@zobi can I actually ask you what are you trying to do?
13:40
not the tiny detail, the final goal, if possible to share, thanks
Avatar
Avatar
Andrea Giammarchi
honestly ... the whole thing is editable, I can't even click on View Code so it's hard to help but it looks to me you are doing something not meant to be done with that property and removing the ability to even see its source code is not nice at all.
I was told https://_12.pyscriptapps.com/noisy-math-copy-copy-copy-copy-copy/latest/ using text area is not secure and I should use main.py. so I got main.py using <iframe></iframe>.But iframe in python is not editable like textarea so the next option is to get the code to html and make changes and append it back to iframe.That's what I am trying.
Avatar
Avatar
zobi
I was told https://_12.pyscriptapps.com/noisy-math-copy-copy-copy-copy-copy/latest/ using text area is not secure and I should use main.py. so I got main.py using <iframe></iframe>.But iframe in python is not editable like textarea so the next option is to get the code to html and make changes and append it back to iframe.That's what I am trying.
Andrea Giammarchi 13/06/2024 14:17
I think textarea content doesn't suffer parsing issues ... example: <textarea> <script>alert("nope")</script> </textarea> this just shows <script>alert("nope")</script> as is, there's no parsing and the only issue you might have is if your code includes a </textarea> but that's also true for inline scripts if the code includes </script> in it ... can you point me at the discussion around this textearea insecurity?
14:19
that being said, content editable and iframes are rarely the answer to anything so it'd be great if I could really understand what is your issue with PyEditor or why you prefer to have all these other issues instead of just using display on occasions.
Avatar
Avatar
Andrea Giammarchi
I think textarea content doesn't suffer parsing issues ... example: <textarea> <script>alert("nope")</script> </textarea> this just shows <script>alert("nope")</script> as is, there's no parsing and the only issue you might have is if your code includes a </textarea> but that's also true for inline scripts if the code includes </script> in it ... can you point me at the discussion around this textearea insecurity?
I will surely point about the issue in the discussion.With iframe i am doubtful of using js functionality for user inputs.
Avatar
Hi guys, does anyone here have any idea about how we can create a pyscript component that can be called to create editable code blocks. Preferably something like writing a js function & calling it through activecode. But if you have any idea on how I can do that or what I can refer for the same. Pls let me know.
Avatar
Avatar
ChaTTy
Hi guys, does anyone here have any idea about how we can create a pyscript component that can be called to create editable code blocks. Preferably something like writing a js function & calling it through activecode. But if you have any idea on how I can do that or what I can refer for the same. Pls let me know.
Andrea Giammarchi 17/06/2024 21:58
is this like a py-editor thing?
Avatar
Thanks! I will try this out.
Avatar
Even after including <script src="/mini-coi.js" scope="./"></script> my page shows blank?
Avatar
Is it possible to write something like the following? <script src=./main.js > <script type="py" config="./pyscript.toml" terminal> </script> </script> (edited)
Avatar
@zobi what exactly are you trying to do?
Avatar
Avatar
ntoll
@zobi what exactly are you trying to do?
I am trying to make the following code work in micropython https://_12.pyscriptapps.com/shy-leaf/latest/ .I know python but very little of javascript.I am struggling with the javascript part.Is there anyway python code can display in javascript without iframe?
Avatar
Code inside <pre></pre> tag I am able to get result but when I add extra code on browser it goes to <div></div> tag not sure how to deal with it?
Avatar
Avatar
zobi
Is it possible to write something like the following? <script src=./main.js > <script type="py" config="./pyscript.toml" terminal> </script> </script> (edited)
Andrea Giammarchi 24/06/2024 08:52
<script><script></script></script> breaks HTML parser so the answer is no but also it's likely you never want to do that
👍 1
Avatar
Avatar
zobi
I am trying to make the following code work in micropython https://_12.pyscriptapps.com/shy-leaf/latest/ .I know python but very little of javascript.I am struggling with the javascript part.Is there anyway python code can display in javascript without iframe?
Andrea Giammarchi 24/06/2024 08:53
why do you need an iframe at all?
08:54
cross frames interaction is very old style and mostly broken these days ... the only good use of iframes is usually embedded stuff form other sites such as tweets or YouTube videos, or Twitch, not much else in general is a good candidate.
👍 1
Avatar
Avatar
zobi
Code inside <pre></pre> tag I am able to get result but when I add extra code on browser it goes to <div></div> tag not sure how to deal with it?
What about the solution for this?
11:29
Avatar
Avatar
zobi
Click to see attachment 🖼️
I solved it by myself.
Avatar
Avatar
Andrea Giammarchi
cross frames interaction is very old style and mostly broken these days ... the only good use of iframes is usually embedded stuff form other sites such as tweets or YouTube videos, or Twitch, not much else in general is a good candidate.
I dont think so.iframe is more secured when compared to textarea.Textarea looks like common for javascript and python but iframe isn't common for javascript and python which makes it more secure.The only issue i am facing is to get the python syntax highlighter inside iframe. (edited)
Avatar
Avatar
zobi
I dont think so.iframe is more secured when compared to textarea.Textarea looks like common for javascript and python but iframe isn't common for javascript and python which makes it more secure.The only issue i am facing is to get the python syntax highlighter inside iframe. (edited)
Andrea Giammarchi 26/06/2024 07:42
iframe is so common in JS that you have a global frames reference on the main to access these ... it's really a 90s' style to sandbox but there's nothing inherently more secure with iframes in general. To style these your iframe needs css dependencies (in case of code-mirror) ... or you just use the PyEditor which runs in Workers which are, in turn, more secure than iframes as there's no parent attached to these.
Avatar
Avatar
Andrea Giammarchi
iframe is so common in JS that you have a global frames reference on the main to access these ... it's really a 90s' style to sandbox but there's nothing inherently more secure with iframes in general. To style these your iframe needs css dependencies (in case of code-mirror) ... or you just use the PyEditor which runs in Workers which are, in turn, more secure than iframes as there's no parent attached to these.
My codes don't run in PyEditor.I am not sure how to make html work in PyEditor and even not getting deployed. (edited)
Avatar
Avatar
Andrea Giammarchi
iframe is so common in JS that you have a global frames reference on the main to access these ... it's really a 90s' style to sandbox but there's nothing inherently more secure with iframes in general. To style these your iframe needs css dependencies (in case of code-mirror) ... or you just use the PyEditor which runs in Workers which are, in turn, more secure than iframes as there's no parent attached to these.
Why is @Josh using iframe for his project if it's 90s' style?🤔
Avatar
Avatar
zobi
Why is @Josh using iframe for his project if it's 90s' style?🤔
Andrea Giammarchi 28/06/2024 08:28
they are not mutually exclusive approaches ... it's just that these days use cases for iframes are extremely rare and there are other primitives. I didn't mean to say "don't use iframes", they are 90s' means these are surely usable cross browser and yet credentialless attribute is not widely supported and there are other issues related to frames since about ever.
08:29
I am still confused by your claim you can't wotk with the PyEditor but then again, if you are happy with whatever stack you are using, we are happy too.
👍 1
Avatar
I'm using PyScript to run a simple Python script in my HTML file to display a pandas DataFrame. However, after loading the page in browser and clicking the run button of the code block I'm encounte...
Avatar
Avatar
Andrea Giammarchi
iframe is so common in JS that you have a global frames reference on the main to access these ... it's really a 90s' style to sandbox but there's nothing inherently more secure with iframes in general. To style these your iframe needs css dependencies (in case of code-mirror) ... or you just use the PyEditor which runs in Workers which are, in turn, more secure than iframes as there's no parent attached to these.
I am confused.Having parent is secure or no parent is secure?For Textarea @Neon22 suggested me to use main.py (i.e parent) because it's more secure and according to @Andrea Giammarchi no parent attached is more secure.
Avatar
Avatar
zobi
I am confused.Having parent is secure or no parent is secure?For Textarea @Neon22 suggested me to use main.py (i.e parent) because it's more secure and according to @Andrea Giammarchi no parent attached is more secure.
Andrea Giammarchi 01/07/2024 08:42
if you own the iframe reference and it's same domain there is no security concern. If you embed in iframe randoms stuff and that can access the parent you have security concerns. This is all about Web DOM best practices and security though, not much to do with PyScript or Python in general. Your goal, and that's usually mine too, is to achieve what you want to do. If security is OK and it works, I'd say job done?
08:42
P.S. parent is as insecure as opener for window opened popups ... it's all on MDN though
Avatar
hey everyone! I'm developing app that returns data gathered through APIs. My function "preveri" already works on one of the pages, it takes address and prints data. Now I decided to use that function to output data for 10 different wallets in one click. so i made function like shown on screenshot, but i just cant make it work
11:28
i also added lines to the end of "preveri" function
11:28
if anyone has any suggestions i would appreciate it 🙂
11:32
+ my html
Avatar
chris.laffra 01/07/2024 14:00
@Shaman it is hard to imagine what this code should do. Are you getting any error messages? Have you checked the browser devtools console?
14:19
thats the example my "preveri" function does
14:20
14:20
i get this now
14:21
value is the input for the function
14:22
it should be wallet address, which is needed to get data through APIs
14:23
what i want to do now is to use the same function but insted of inputing value through frontend i just want to process 10 predefined wallets
Avatar
Avatar
zobi
I am confused.Having parent is secure or no parent is secure?For Textarea @Neon22 suggested me to use main.py (i.e parent) because it's more secure and according to @Andrea Giammarchi no parent attached is more secure.
I think I implied do not use eval for code users can type in.
Avatar
Najmul Sharif 02/07/2024 08:35
Hello pyscript expert how are you everybody ? i have start learn the pyscript . but i have face some error to implement it to my main.py file according to follow the pyscript documentation . i install the pyscript package from "pip install pyscript" and try to import this below function and write this code from the . pyscript documentation site . the screenshot is hear . but the " from pyscript import document " is not imported . i just want to say that how to solve this error . i try to import it to the main.py file . thank you
Avatar
Avatar
Najmul Sharif
Hello pyscript expert how are you everybody ? i have start learn the pyscript . but i have face some error to implement it to my main.py file according to follow the pyscript documentation . i install the pyscript package from "pip install pyscript" and try to import this below function and write this code from the . pyscript documentation site . the screenshot is hear . but the " from pyscript import document " is not imported . i just want to say that how to solve this error . i try to import it to the main.py file . thank you
chris.laffra 02/07/2024 11:01
See my answers in the pyscript-help channel.
Avatar
Avatar
Neon22
I think I implied do not use eval for code users can type in.
The problem statement was I wasn't able to deploy the py-editor that how I started to find alternatives for py-editor.I am able to deploy javascript not python console or editor alone.But javascript involved with python I am able to deploy.That was the main goal.
Avatar
Is it possible to import main and make code work in type="py-editor " like type="py" https://_12.pyscriptapps.com/rough-dew/latest/
Avatar
@zobi that link doesn't work.
Avatar
Avatar
ntoll
@zobi that link doesn't work.
Doesn't work? It works for me.
Avatar
Can someone help me with this code it displays result on terminal but still shows error message?https://_12.pyscriptapps.com/shy-leaf-copy/latest/
10:19
Avatar
@zobi i think has to do with <button py-click="myFunction" id="add">Submit</button> , you don;t need the py-click="myFunction" .
Avatar
import time import pydirectinput import keyboard try: # Wait for 5 seconds before starting key presses time.sleep(5) # Simulate pressing 'o' key multiple times with small delays for _ in range(6): pydirectinput.press('o') time.sleep(0.1) # Simulate pressing 'Page Up' key multiple times with small delays for _ in range(3): keyboard.press_and_release('page up') time.sleep(0.1) # Print end message after all key presses are done print("end") except Exception as e: print(f"Error occurred: {e}") Nothing works to use Page Up Tried pyautogui and pydirectinput and running it as admin, everything is installed
Avatar
Avatar
Parviz O
@zobi i think has to do with <button py-click="myFunction" id="add">Submit</button> , you don;t need the py-click="myFunction" .
Superb👍 .You are right. I didn't observe that.Thank you for helping. (edited)
Avatar
Avatar
beez131
import time import pydirectinput import keyboard try: # Wait for 5 seconds before starting key presses time.sleep(5) # Simulate pressing 'o' key multiple times with small delays for _ in range(6): pydirectinput.press('o') time.sleep(0.1) # Simulate pressing 'Page Up' key multiple times with small delays for _ in range(3): keyboard.press_and_release('page up') time.sleep(0.1) # Print end message after all key presses are done print("end") except Exception as e: print(f"Error occurred: {e}") Nothing works to use Page Up Tried pyautogui and pydirectinput and running it as admin, everything is installed
It worked in pycharm as python file.I think the problem is with the package installation part in pyscript.Pyscript runs on browser and most packages don't work on browser.
Avatar
this is just a normal python script, i use visual studio
Avatar
@beez131 please remember that some Python scripts assume Python is running on certain operating systems. When it comes to PyScript the browser is the equivalent of the OS and so these scripts may not work as you expect. You may get more mileage proxying a JS library designed to do the same thing (emulate keyboard input) but made for the browser. A quick Google should turn some things up... This section of the user guide tells you how to use JS libs in PyScript: https://docs.pyscript.net/2024.7.1/user-guide/dom/#working-with-javascript
15:58
Let us know how you get on.
Avatar
Avatar
ntoll
@beez131 please remember that some Python scripts assume Python is running on certain operating systems. When it comes to PyScript the browser is the equivalent of the OS and so these scripts may not work as you expect. You may get more mileage proxying a JS library designed to do the same thing (emulate keyboard input) but made for the browser. A quick Google should turn some things up... This section of the user guide tells you how to use JS libs in PyScript: https://docs.pyscript.net/2024.7.1/user-guide/dom/#working-with-javascript
This is just a normal python script, not using pyscript, the channel is #╰╸python-help and there is also a #╰╸pyscript-help so it would make sense to ask for regular python help in here right?
Avatar
Avatar
beez131
This is just a normal python script, not using pyscript, the channel is #╰╸python-help and there is also a #╰╸pyscript-help so it would make sense to ask for regular python help in here right?
sure, but what @ntoll means is python help with pyscript. This entire discord is a pyscript discord not a python discord. You should ask questions that relate to pyscript and python within that framework. If you just have a straightforward python question, well you might be better off on StackExchange. I mean you might get an answer that's useful, but everyone here is going to assume you're asking this question in a pyscript context.
Avatar
oh ok
Avatar
There is also a Python discord, with many participants.
Avatar
Avatar
beez131
oh ok
chris.laffra 10/07/2024 20:09
Not sure what the imports in your code do, but "time.sleep(...)" has no meaning in PyScript, as Python runs as a single-threaded application in the browser.
20:11
@beez131 : the way I verify if Python code works correctly in PyScript is by loading it in https://pyscript.com. It sets up the the PyScript environment in a highly predictable fashion.
Avatar
I want the terminal to be hidden in few pages and the terminal to be seen in few pages. Using multiple .html pages its possible but is there any way I can make it work using single .html page https://_12.pyscriptapps.com/shy-leaf-copy-copy/latest/ For the first page I want the terminal to be hidden and for the rest I want the terminal to be seen.
Avatar
Avatar
zobi
I want the terminal to be hidden in few pages and the terminal to be seen in few pages. Using multiple .html pages its possible but is there any way I can make it work using single .html page https://_12.pyscriptapps.com/shy-leaf-copy-copy/latest/ For the first page I want the terminal to be hidden and for the rest I want the terminal to be seen.
Andrea Giammarchi 19/07/2024 09:43
why don't you just remove terminal attribute when you don't want a terminal? any particular reason for wanting but not seeing it?
Avatar
Avatar
Andrea Giammarchi
why don't you just remove terminal attribute when you don't want a terminal? any particular reason for wanting but not seeing it?
If I remove terminal attribute I think the terminal wont be seen for all pages.Terminal looks like useless part of the page when there is no code in the page so I dont want it to be seen.
Avatar
Older version used to display terminal only when needed. https://_12.pyscriptapps.com/small-haze/latest/ Is there any way I can make it work in new version?There is either page load or button click not sure how to make both work together. (edited)
Avatar
Avatar
zobi
Older version used to display terminal only when needed. https://_12.pyscriptapps.com/small-haze/latest/ Is there any way I can make it work in new version?There is either page load or button click not sure how to make both work together. (edited)
Andrea Giammarchi 21/07/2024 13:12
the old way was implicit and we had complains around it ... the current way is explicit which is AFAIK the Pythonic way. If you don't have code that prints anything, or you never want those prints visible on the page, don't use terminal attribute. If you want to see prints on the page, use terminal attribute ... it's more about you deciding what you want. If your template can't decide if terminal attribute should be there or not, consider updating or changing template engine as that's a pretty simple to ask/demand from a templating engine?
Avatar
Avatar
Andrea Giammarchi
the old way was implicit and we had complains around it ... the current way is explicit which is AFAIK the Pythonic way. If you don't have code that prints anything, or you never want those prints visible on the page, don't use terminal attribute. If you want to see prints on the page, use terminal attribute ... it's more about you deciding what you want. If your template can't decide if terminal attribute should be there or not, consider updating or changing template engine as that's a pretty simple to ask/demand from a templating engine?
Andrea Giammarchi 21/07/2024 13:16
anyway, you cna always hide and show a terminal node ... the script has a target you can use to make it hiden or not so you can easily decide when it should be shown or not on the page, if SPA (Single Page Application) is what you are after.
Avatar
Avatar
Andrea Giammarchi
anyway, you cna always hide and show a terminal node ... the script has a target you can use to make it hiden or not so you can easily decide when it should be shown or not on the page, if SPA (Single Page Application) is what you are after.
Andrea Giammarchi 21/07/2024 13:16
if you need an example on how to hide or show a terminal, let me know, thanks!
Avatar
Avatar
Andrea Giammarchi
if you need an example on how to hide or show a terminal, let me know, thanks!
Yes , I need the example. (edited)
Sticker
Avatar
Avatar
zobi
Yes , I need the example. (edited)
Andrea Giammarchi 22/07/2024 09:33
this is an example based you your demo https://pyscript.com/@agiammarchi/shy-leaf-copy-copy-copy/latest ... you are using onclick there, in the HTML ... to refer to Python functions, which I removed, as that's not valid and in conflict with when decorator ... there are other gotchas around the layout (<p> elements can't contain block elements and other things) but at least you can see that showing/hiding the terminal element is a terminal.element.hidden = True/False operation away. I hope this helps. (edited)
Avatar
Avatar
Andrea Giammarchi
this is an example based you your demo https://pyscript.com/@agiammarchi/shy-leaf-copy-copy-copy/latest ... you are using onclick there, in the HTML ... to refer to Python functions, which I removed, as that's not valid and in conflict with when decorator ... there are other gotchas around the layout (<p> elements can't contain block elements and other things) but at least you can see that showing/hiding the terminal element is a terminal.element.hidden = True/False operation away. I hope this helps. (edited)
10:53
It's exactly what I wanted. Thanks for helping.
👍 1
Avatar
How can I write terminal print only once on button click https://_12.pyscriptapps.com/yellow-moon/latest/ (edited)
Avatar
Avatar
zobi
How can I write terminal print only once on button click https://_12.pyscriptapps.com/yellow-moon/latest/ (edited)
Andrea Giammarchi 25/07/2024 15:54
do you mean how would cancel a @when event? I see it printing hello once per each click otherwise ...
Avatar
Avatar
Andrea Giammarchi
do you mean how would cancel a @when event? I see it printing hello once per each click otherwise ...
Andrea Giammarchi 25/07/2024 16:04
about @when decorator, I don't see any mechanism to make it dispatch the event once and clean up ... when it comes to DOM methods though, you can pass {"once": True} as third and last argument https://pyscript.com/@agiammarchi/yellow-moon-copy/latest
16:07
arguably, we could provide a @when_once utility for this use case, as it's fairly common on the Web /cc @ntoll @Jeff Glass
Avatar
Avatar
Andrea Giammarchi
about @when decorator, I don't see any mechanism to make it dispatch the event once and clean up ... when it comes to DOM methods though, you can pass {"once": True} as third and last argument https://pyscript.com/@agiammarchi/yellow-moon-copy/latest
It's one of the solution.Simple print('\x1bc') clears and prints but it shows one line gap.Is there any way I can remove that one line gap? https://_12.pyscriptapps.com/yellow-moon/latest/
Avatar
Avatar
zobi
It's one of the solution.Simple print('\x1bc') clears and prints but it shows one line gap.Is there any way I can remove that one line gap? https://_12.pyscriptapps.com/yellow-moon/latest/
Andrea Giammarchi 26/07/2024 08:03
this is a question for xterm or terminals' special escape chars in general, not strictly PyScript or Python related. You need to understand those special chars, the cursor position and so on ... it's a huge topic and you have better chances looking online for better, more exhaustive, answers.
👍 1
08:04
not that I don't want to help ... just that if I give you one answer you'll ask me instantly another one after if you don't fully understand what is going on, which I suggest you should instead understand and not just copy/paste escape chars in your project. I hope this makes sense.
Avatar
@Andrea Giammarchi or perhaps you pass in a once=True flag into the @when decorator..?
Avatar
Avatar
ntoll
@Andrea Giammarchi or perhaps you pass in a once=True flag into the @when decorator..?
Andrea Giammarchi 26/07/2024 09:16
the issue is that we end up here https://github.com/pyscript/pyscript/blob/main/pyscript.core/src/stdlib/pyscript/event_handling.py#L3-L9 and while it's easy and possible to add that logic to MicroPython we don't get to do the same in pyodide so the logic must fallback anyway but I am not sure what's special about Pyodide add_event_lister but it doesn't accept special events use cases https://pyodide.org/en/stable/usage/api/python-api/ffi.html#pyodide.ffi.wrappers.add_event_listener ... once is only one of the options we could pass, there are more https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#options
The addEventListener() method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target.
Avatar
Avatar
Andrea Giammarchi
the issue is that we end up here https://github.com/pyscript/pyscript/blob/main/pyscript.core/src/stdlib/pyscript/event_handling.py#L3-L9 and while it's easy and possible to add that logic to MicroPython we don't get to do the same in pyodide so the logic must fallback anyway but I am not sure what's special about Pyodide add_event_lister but it doesn't accept special events use cases https://pyodide.org/en/stable/usage/api/python-api/ffi.html#pyodide.ffi.wrappers.add_event_listener ... once is only one of the options we could pass, there are more https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#options
Andrea Giammarchi 26/07/2024 09:18
in retrospective I did, in fact, propose to stop using these dedicated wrappers because they just branch logic more than we need/want for our utilities https://github.com/pyscript/pyscript/discussions/1952
We currently have PyWeb (or PyDom) broken in MicroPython and the reason is almost always the same: we use specific pyodide APIs that we don't get to control neither in Pyodide space nor MicroPy...
Avatar
Hmm... ok, understood. That's a bit of a pain.
Avatar
Avatar
ntoll
Hmm... ok, understood. That's a bit of a pain.
Andrea Giammarchi 26/07/2024 09:24
in general I think @when should accept more named properties and we should provide identical behavior across interpreters. My feeling is that Pyodide does something special related to the proxy/callback life-cycle which is something harder to orchestrate manually on our side unless the experimental_proxy_auto flag is enabled so that we have automatic disposal of those functions once the related node doesn't exist anymore (it's garbage collected). Alternatively I can ask Pyodide folks if they'd be happy to add an extra optional parameter usable to add more Web standard features.
Avatar
I think it probably better for more people if Pyodide folks make it possible to pass through these options.
Avatar
Andrea Giammarchi 26/07/2024 09:26
it looks like @Jeff Glass was on the case already indeed ... https://github.com/pyodide/pyodide/issues/3879 ... 1+ year after, crickets ... I'll try to ask more details as @hood also suggested to use just DOM standard API like we do in MicroPython
🚀 Feature The functions pyodide.ffi.wrappers.add_event_listener and remove_event_listener are useful wrappers around the browser's native functionality. However, the APIs for addEventListener a...
👍 1
Avatar
Avatar
Andrea Giammarchi
it looks like @Jeff Glass was on the case already indeed ... https://github.com/pyodide/pyodide/issues/3879 ... 1+ year after, crickets ... I'll try to ask more details as @hood also suggested to use just DOM standard API like we do in MicroPython
Andrea Giammarchi 26/07/2024 09:33
🚀 Feature The functions pyodide.ffi.wrappers.add_event_listener and remove_event_listener are useful wrappers around the browser's native functionality. However, the APIs for addEventListener a...
👍 1
Avatar
Avatar
Andrea Giammarchi
this is a question for xterm or terminals' special escape chars in general, not strictly PyScript or Python related. You need to understand those special chars, the cursor position and so on ... it's a huge topic and you have better chances looking online for better, more exhaustive, answers.
But if I add your code to my project its affecting my buttons...I am unable to click my buttons(HOME,Example1) not more than once. Is there any way to fix it? I think its the problem when I am not using @when decorator. https://_12.pyscriptapps.com/nasrin-website/latest/ where as print('\x1bc') is not affecting my buttons https://_12.pyscriptapps.com/nasrin-website-copy/latest/
Avatar
Avatar
zobi
But if I add your code to my project its affecting my buttons...I am unable to click my buttons(HOME,Example1) not more than once. Is there any way to fix it? I think its the problem when I am not using @when decorator. https://_12.pyscriptapps.com/nasrin-website/latest/ where as print('\x1bc') is not affecting my buttons https://_12.pyscriptapps.com/nasrin-website-copy/latest/
Andrea Giammarchi 28/07/2024 16:04
I don't understand either what you are trying to do or your question ... you asked me to have a way to click once a button, I gave you one ... if you need a state-machine logic instead for the same button to click and/or not click or do something or something else, use a state-machine logic? you can have an outer variable you check and change to have any state you like too, so you can decide what to do on each state.
Avatar
I think if I use your code terminal goes to previous page may be because js is involved current page terminal goes to previous page https://www.youtube.com/watch?v=ytBngZ8ITEc but using print('\033[H', end = "") the pages are independent.https://www.youtube.com/watch?v=Qixr0z3RjjA for this link https://_12.pyscriptapps.com/nasrin-website-copy-copy/latest/
Avatar
How can I add append=True or False when I am using exec()?https://_12.pyscriptapps.com/sparkling-field-copy/latest/ I am trying to make it work like https://_12.pyscriptapps.com/sparkling-field/latest/
Avatar
Avatar
chris.laffra
@zobi you may need to add those files to your toml. Here is an example for an app I have that loads from local files system and from a remote location.
@chris.laffra can u please share the code link of the image.I am struggling with reading multiple .py files and exec them and your code will be a great help.
Avatar
Avatar
zobi
@chris.laffra can u please share the code link of the image.I am struggling with reading multiple .py files and exec them and your code will be a great help.
chris.laffra 30/07/2024 16:52
Source for PySheets. Contribute to PySheets/pysheets development by creating an account on GitHub.
Avatar
This looks different.I want the code for https://pyscript.github.io/ltk/
Sticker
Avatar
LTK is a little toolkit for writing UIs in PyScript - pyscript/ltk
Avatar
chris.laffra 01/08/2024 03:16
Or click on the "built with LTK" link, or the big LTK at the top of the page.
👍 1
Avatar
Not sure why mpy worker terminal which supports user inputs displays just the first line in the source1 page.https://_12.pyscriptapps.com/crimson-mountain/latest/
Avatar
can someone help me with the following code.I am struggling with the following code.I am trying to call a function which has display1 and display2.On button click i want both displays to get printed(which works) but i dont want them to be printed multiple times every time i click the button.When i use append=False it replaces display1 with display2.I want both displays to be displayed but only once on button click.https://_12.pyscriptapps.com/green-dream-copy/latest/
Avatar
I'm not sure what you're asking for here @zobi
Avatar
Avatar
ntoll
I'm not sure what you're asking for here @zobi
For my website whenever there is an output related to button -result displays every time i click the button but if i want to make it display once i need to write append=true but it replaces the page.I want both pages to be seen without replacement and display once.I think there should be something like display(function(),append=false) like thing.🤔 https://_12.pyscriptapps.com/nasrin-website/latest/ https://www.youtube.com/watch?v=Fb8Yf3xGFRs (edited)
Avatar
In pyscript.com how to add your project to pyscript.com examples?
Avatar
You could raise an issue on the 'examples github repo' with your code in a branch. with documentation.
Avatar
Code in a branch?How to create a branch for a project in pyscript.com?
Avatar
Avatar
zobi
Code in a branch?How to create a branch for a project in pyscript.com?
The code is on github. If you want your code added as an example so everyone can see it - then you'll need to raise an issue on github to add it to eth examples. pyscript examples. Or do you mean something else ?
Avatar
Avatar
Neon22
The code is on github. If you want your code added as an example so everyone can see it - then you'll need to raise an issue on github to add it to eth examples. pyscript examples. Or do you mean something else ?
Code is on pyscript.com with my username profile.If i want to shift it to examples then whats the process I was asking.Without the involvement of github.
Avatar
I can't speak for pyscript.com but the examples are clearly not personal examples but public examples posted by the organisation. These all come from pyscript examples github. I think what you're asking for is not something that is offered or possible. but as I said - I'm not pyscript,com.
Avatar
Avatar
Neon22
I can't speak for pyscript.com but the examples are clearly not personal examples but public examples posted by the organisation. These all come from pyscript examples github. I think what you're asking for is not something that is offered or possible. but as I said - I'm not pyscript,com.
Is there any easy way i can shift my project from pyscript.com to my GitHub or else i need to copy paste each and every page?
Avatar
Avatar
zobi
Is there any easy way i can shift my project from pyscript.com to my GitHub or else i need to copy paste each and every page?
I think they intend to help with this at some point but for now I copy and paste....
👍 1
Avatar
Avatar
Neon22
I think they intend to help with this at some point but for now I copy and paste....
Just another doubt if the examples come from the organization not pyscript.com how they are made using pyscript.com?
Avatar
Is there a way to use other python modules such as numpy, matplotlib, pandas, networkX?
Avatar
yes they should all work with the pyodide runtime
Avatar
Avatar
teknomo.
Is there a way to use other python modules such as numpy, matplotlib, pandas, networkX?
check out the detailed help. the toml file includes them. https://docs.pyscript.net/2024.8.2/user-guide/configuration/#packages
Avatar
It's just a novelty question, like, the answer doesn't really impact what I can do much. But is it possible to, from the python side, add something to the global scope as a const?
Avatar
Avatar
Manock
It's just a novelty question, like, the answer doesn't really impact what I can do much. But is it possible to, from the python side, add something to the global scope as a const?
Not quite sure I understand your question totally. but python can access javascript variables and vice versa. Read about it here: https://docs.pyscript.net/2024.8.2/user-guide/ffi/
Avatar
Yeah but I can't use python to make a const in the global scope, right?
14:21
Anyway here's a serious question.
14:22
It seems I can't use instance methods as a callback. Is this correct or am I missing something? I could always wrap it, but that's just the tiniest bit inconvenient. (edited)
Avatar
Avatar
Manock
Anyway here's a serious question.
unfortunately not enough info for me to work out what you mean. You might need to use a proxy for this as python GCs it away before it has a chance to be used. In the ltk there is ltk.proxy(). E.g. something like this: ltk.Input(self.shortname).on("change", ltk.proxy(lambda event: rename_color(event, self))). The proxty inside pyscript is detailed? here - https://docs.pyscript.net/2024.8.2/user-guide/ffi/
21:28
I'm not sure what you mean about "I can't use python to make a const in the global scope". Just make a global variable. But you could be talking about the dom, or the JS side of global scope...? (edited)
Avatar
Avatar
Neon22
unfortunately not enough info for me to work out what you mean. You might need to use a proxy for this as python GCs it away before it has a chance to be used. In the ltk there is ltk.proxy(). E.g. something like this: ltk.Input(self.shortname).on("change", ltk.proxy(lambda event: rename_color(event, self))). The proxty inside pyscript is detailed? here - https://docs.pyscript.net/2024.8.2/user-guide/ffi/
Doesn't work for instance methods.
Avatar
Avatar
Neon22
I'm not sure what you mean about "I can't use python to make a const in the global scope". Just make a global variable. But you could be talking about the dom, or the JS side of global scope...? (edited)
JavaScript's global scope.
Avatar
Avatar
Manock
Doesn't work for instance methods.
I did some kind of workaround and got it working. but these days I admit to using a top level function for this. You can pass your class object around in a global if you need access to it. Its not ideal...
Avatar
I mean you can also wrap a lambda around the method call and proxy that.
Avatar
yes - that's my example (I think)
Avatar
Yeah but that will default to using var.
22:27
That's not a particularly serious question.
22:28
Just curiosity because I'm weird like that.
Avatar
ffi.to_js(reference)
Avatar
Yeah but that won't make it not a var.
22:29
Python doesn't do the whole var let const thing.
22:29
So it just defaults to being a var on the js side.
Avatar
When the pyscript guys get back from holiday - @Andrea Giammarchi would be ideal person to answer
Avatar
It seems I can make a property nonwritable by using js.Object.defineProperty()
Avatar
Oh, it seems I had a fundamental misunderstanding of how things worked in javascript anyway. Block scoped values are added to the scope, not the window object.
14:13
So my question was entirely moot.
Avatar
Avatar
Neon22
When the pyscript guys get back from holiday - @Andrea Giammarchi would be ideal person to answer
Andrea Giammarchi 26/08/2024 08:32
FYI I am back but glad it got solved ... to attach things globally window.thing = anyPythonThing btw, where from pyscript import window but you could also use window.Object.defineProperty(window, 'thing', { value: anyPythonThing }) although in latter case, if it's a callback, you might need pyscript.ffi.create_proxy there.
Avatar
From my understanding create proxy is only really necessary if the function is in danger of falling out of scope.
Avatar
Avatar
Manock
From my understanding create proxy is only really necessary if the function is in danger of falling out of scope.
chris.laffra 03/09/2024 17:56
And only needed on PyOdide, not on MicroPython...
Avatar
Avatar
Manock
From my understanding create proxy is only really necessary if the function is in danger of falling out of scope.
Andrea Giammarchi 11/09/2024 17:29
it' a matter of GC orchestration across runtimes / interpreters ... in Pyodide they have some utility that uses FinalizationRegistry out of the box but for some reason they decided to not use that utility everywhere due concerns about predictability for the API itself which indeed doesn't expose any details on purpose ... however ... if you use in your pyodide (py) related config experimental_create_proxy = "auto" flag, you probably never need ever again to worry about this in Pyodide, while MicroPython uses that primitive out of the box so that don't need a special flag around it. (edited)
Avatar
Well, @when creates proxies for me anyway.
Avatar
Andrea Giammarchi 11/09/2024 17:38
basically, the issue can be summarized as such: el = document.getElementById("test") el.addEventListener("click", lambda e: print(e.type)) here you are telling the JS side of affair to add a listener that will print the event type (click) once clicked ... now, because there is no interoperability across PLs in the WASM to JS world. how does Pyodide know that such lambda can be destroyed from its own memory stack? In WASM, allocated memory to work is crucial so far so the more it's free, the better it is for your software not to crash or just keep growing RAM requirements over time ... so they confined a FinalizationRegistry orchestration in their ffi utilities to add listeners, but they are asking you to decide when that listener should be destroyed, which is only related to the lifecycle of that el reference, not only in Python, also in JS / DOM world. Without explicit proxy.destroy() that cannot be decided for a generic listener out there if nobody knows when it's going to be collected, they actually (imho) created another problem ... nobody knows, or care about, destroying proxies, so that the FinalizationRegistry automated dance would be better for everyone, because once that el is not existent anymore on the DOM, and that el reference can be collected on the Python side too, that listener would be automatically collected. They know that for the DOM ffi related API, but this pattern is actually all over the place, not just listeners, yet I haven't convinced them they should trust more the FinalizationRegistry and erase create_proxy and its expectations from their API as that causes more troubles than it solves, imho 🤷 (edited)
17:42
a concrete example: def addClick(css): # el is locally scoped el = document.querySelector(css) el.addEventListener("click", lambda e: print(e.type)) # meaning, here el can be collected, without retaining # a reference needed to exist on the JS/DOM side # that lambda though ... exists until the `el` in the # JS/DOM side is live or referenced # so here Python flags el as collectable, but on the JS side # that lambda must be invokable until the element exist
Avatar
Hahah this is all getting very technical.
17:43
I just imagined it as python garbage collecting it because there is no reference to it anymore (on the python side).
17:44
And what's passed to the js side is some kind of callable wrapper that python doesn't see as a proper reference.
17:45
I guess the truth is a bit more complicated.
17:45
But it's a little bit beyond me.
17:46
I just assumed that create_proxy just creates a reference to it in some registry somewhere to make sure it's not garbage collected until the registry itself is released by unloading the page. (edited)
Avatar
Avatar
Manock
I just assumed that create_proxy just creates a reference to it in some registry somewhere to make sure it's not garbage collected until the registry itself is released by unloading the page. (edited)
Andrea Giammarchi 11/09/2024 17:46
that's what it does ... forever though, unless you p.destroy() it
17:47
this is all documented in Pyodide project, in MicroPython we don't care as it uses the FinalizationRegistry as it should
Avatar
By "forever" do you mean until the page is unloaded?
Avatar
Andrea Giammarchi 11/09/2024 17:51
in MocroPython if you create_proxy has (known) no side-effects, in Pyodide it means "retain that thing until you decide it should not be retained anymore" ... which is cool and everything, but if you defined a timer in JS world? maybe that would never be called ... you define a listener? that should work until that related element exist ... you define any handler of any feature exposed to Python? same as DOM element listeners ... so here be careful, just using create_proxy is not a long-term, long-living, solution to anything, it actually puts more weight on your shoulders ... if you do use that a lot, I strongly suggest the config flag I've mentioned so that most (but not all) things would just work without you needing to even think about create_proxy wraps ... and "that's a wrap" (no pun intended).
Avatar
Avatar
Manock
By "forever" do you mean until the page is unloaded?
Andrea Giammarchi 11/09/2024 17:52
that's forever in any tab meaning, yes.
Avatar
I'm just a hobbyist though, I don't make any big applications that could run into huge memory leakage that way. XD
❤️ 1
Avatar
Avatar
Manock
I'm just a hobbyist though, I don't make any big applications that could run into huge memory leakage that way. XD
Andrea Giammarchi 11/09/2024 17:59
I'm just a developer, I tend to answer with overly-verbose technical details nobody cares about ... but maybe somebody else in this channel would appreciate, althought I am sorry if I didn't provide the kind of answer you were looking for.
Avatar
It's fine, I understand enough now.
Avatar
Andrea Giammarchi 11/09/2024 20:42
I wish pyodide folks would read last exchange because it's an ever coming matter to discuss with our own community, you are a good (by all means) example around this topic ... so I might summon @hood here to provide even more details, but I think my previous summaries explain well the current state ... I am just hoping that would change, at some point , but it's a long, full of details, related discussion. (edited)
20:45
@hood the topic was explained in here https://discord.com/channels/972017612454232116/972020231293771786/1283466694299353109 but before that there were questions too
Avatar
Right the problem is that a reference loop from Python to JavaScript to Python cannot be garbage collected unless someone manually breaks the loop (or the wasm runtime is built with wasm gc)
20:48
So we've designated that the references from js to Python have to be manually broken and the references from Python to js are dealt with automatically
20:50
create_proxy exists because otherwise it wouldn't be possible to break certain js to Python references manually so we do the reverse
20:51
I assume that micropython deals with this by just leaking reference loops because as of yet there is no way to use wasm gc from c and micropython is implemented in C
20:51
I'm not sure that this is helpful to @Manock but I can answer more specific questions...
Avatar
Uh, helpful? I am currently not in need of help with anyhthing I don't think.
21:51
I mean this discussion is very interesting, don't get me wrong.
Avatar
Avatar
hood
I assume that micropython deals with this by just leaking reference loops because as of yet there is no way to use wasm gc from c and micropython is implemented in C
Andrea Giammarchi 12/09/2024 08:15
by reference loop you mean a JS proxy that references a Python reference that references a JS proxy, right? I think that would indeed leak in MicroPython but why does this matter for callbacks? 🤔 Anyway, thanks for chiming in, I keep forgetting that caveat to consider.
Avatar
How to read csv or xlsx file from url?I remember @Chris Laffra sharing the code in community call. Can you please check where I am going wrong? https://_12.pyscriptapps.com/silent-sun/latest/
Avatar
Avatar
zobi
How to read csv or xlsx file from url?I remember @Chris Laffra sharing the code in community call. Can you please check where I am going wrong? https://_12.pyscriptapps.com/silent-sun/latest/
Chris Laffra 14/09/2024 08:44
I see this error...
08:44
BTW. This is a PyScript question, not Python.
Avatar
Chris Laffra 14/09/2024 09:10
It works fine on PySheets.
Avatar
Avatar
Chris Laffra
I see this error...
@Neon22 Mentioned earlier that whole discord is pyscript so i thought can write it anywhere.Is there any other way to import pyodide or can i import pysheets and make it work in pyscript?
Avatar
Chris Laffra 14/09/2024 15:47
There is no need to add pyodide to your package list. Just import it in your Python code.
15:48
The source to PySheets (that loads the Excel as shown above) can be found at https://pysheets.app/git
15:49
We have "pyscript-help" and "python-help", to me those names suggest different topics.... The problem you raised is only relevant to PyScript, not Python.
👍 1
15:50
But, I am just another user here...
Avatar
Avatar
Parviz O
used /See channel's stats
Statbot BOT 14/09/2024 17:46
(edited)
Avatar
Avatar
zobi
@Neon22 Mentioned earlier that whole discord is pyscript so i thought can write it anywhere.Is there any other way to import pyodide or can i import pysheets and make it work in pyscript?
clearly this whole discord is about pyscript. but the difference between the groups pyscript-help and python-help suggests one is about help for pyscript and one is about help for python the language. If they were the same then there would only be one of them. I am surprised I have to write this down. Also I don't work here either - I'm just a committed user of pyscript.
👍 3
Avatar
Andrea Giammarchi 17/09/2024 18:02
AFAIK the Python philosophy is that explicit is better than implicit which is why, I believe and speculate about, we have those two channels, simply to disambiguate the kind of help is needed. For Python, likely anyone in this channel could help, for PyScript, both users and core teams members can surely try to help out too.
👍 1
Avatar
Avatar
Neon22
clearly this whole discord is about pyscript. but the difference between the groups pyscript-help and python-help suggests one is about help for pyscript and one is about help for python the language. If they were the same then there would only be one of them. I am surprised I have to write this down. Also I don't work here either - I'm just a committed user of pyscript.
And we appreciate you being here (along with everyone else helping, growing and supporting PyScript). 👍 Your assessment is right... PyScript specific questions go in #pyscript-help whereas general Python questions go in this channel. However, we are NOT a Python support network so you should expect the sort of support in here to be of the form, "good question, why not look over here..?" rather than any in depth help.
Avatar
Avatar
ntoll
And we appreciate you being here (along with everyone else helping, growing and supporting PyScript). 👍 Your assessment is right... PyScript specific questions go in #pyscript-help whereas general Python questions go in this channel. However, we are NOT a Python support network so you should expect the sort of support in here to be of the form, "good question, why not look over here..?" rather than any in depth help.
@Neon22 Looks like helping ghost.He/She should attend the community call as well.Atleast we could see the face behind the helping ghost 👻
Avatar
Chris Laffra 19/09/2024 05:15
For some people, the time zone they live in does not make it easy to attend.
Avatar
Avatar
Chris Laffra
For some people, the time zone they live in does not make it easy to attend.
I do agree 👍 .I like this DISCORD because I can see people here. Other DISCORDS make me feel as if copilot is answering my questions.
Avatar
Al (@alxrms) 19/12/2024 19:26
Hey folks! I’m new to PyScript, but a long time Python developer and a once-upon-a-time Wasmer. I am beginning to dream up a design for a PyScript project, and I’d love to bounce ideas off experienced folks here. What is the best way we could get Zarr and Xarray to run on micropython? My initial guess would involve the development of two “micro” packages: a replacement for numpy that used micropython uarrays via a custom Xarray ChunkManager (https://docs.xarray.dev/en/latest/internals/chunked-arrays.html#xarray.namedarray.parallelcompat.ChunkManagerEntrypoint), second, a wasm-ready fsspec reader to work with Zarr v3 (which is now async; other takeaways from this long thread): https://github.com/zarr-developers/community/issues/43. I suspect that one or both of these would need to be web- or service- worker aware to function in this paradigm. In this relatively advanced stage of both Zarr and PyScript, I have a hunch that implementing Xarray/Zarr visualization in normal PyScript on Pyodide is tractable today (I plan on working on a prototype around the holidays), but running on something as lightweight as micropython would be a significant challenge (which I’m excited about). How reasonable are these thoughts? Am I missing something obvious? If you wanted to visualize Zarr data with Xarray in the browser and have it be lightning fast, how would you go about it?
Learned recently that Pyodide is including Zarr, which is great to hear 😄 Also happy to learn folks are able to build Numcodecs. Would be interested to learn more about how folks are using Pyodide ...
Xarray can wrap chunked dask arrays (see Parallel Computing with Dask), but can also wrap any other chunked array type that exposes the correct interface. This allows us to support using other fram...
Avatar
Avatar
Al (@alxrms)
Hey folks! I’m new to PyScript, but a long time Python developer and a once-upon-a-time Wasmer. I am beginning to dream up a design for a PyScript project, and I’d love to bounce ideas off experienced folks here. What is the best way we could get Zarr and Xarray to run on micropython? My initial guess would involve the development of two “micro” packages: a replacement for numpy that used micropython uarrays via a custom Xarray ChunkManager (https://docs.xarray.dev/en/latest/internals/chunked-arrays.html#xarray.namedarray.parallelcompat.ChunkManagerEntrypoint), second, a wasm-ready fsspec reader to work with Zarr v3 (which is now async; other takeaways from this long thread): https://github.com/zarr-developers/community/issues/43. I suspect that one or both of these would need to be web- or service- worker aware to function in this paradigm. In this relatively advanced stage of both Zarr and PyScript, I have a hunch that implementing Xarray/Zarr visualization in normal PyScript on Pyodide is tractable today (I plan on working on a prototype around the holidays), but running on something as lightweight as micropython would be a significant challenge (which I’m excited about). How reasonable are these thoughts? Am I missing something obvious? If you wanted to visualize Zarr data with Xarray in the browser and have it be lightning fast, how would you go about it?
Chris Laffra 19/12/2024 21:53
Can you use pyodide?
Avatar
Avatar
Al (@alxrms)
Hey folks! I’m new to PyScript, but a long time Python developer and a once-upon-a-time Wasmer. I am beginning to dream up a design for a PyScript project, and I’d love to bounce ideas off experienced folks here. What is the best way we could get Zarr and Xarray to run on micropython? My initial guess would involve the development of two “micro” packages: a replacement for numpy that used micropython uarrays via a custom Xarray ChunkManager (https://docs.xarray.dev/en/latest/internals/chunked-arrays.html#xarray.namedarray.parallelcompat.ChunkManagerEntrypoint), second, a wasm-ready fsspec reader to work with Zarr v3 (which is now async; other takeaways from this long thread): https://github.com/zarr-developers/community/issues/43. I suspect that one or both of these would need to be web- or service- worker aware to function in this paradigm. In this relatively advanced stage of both Zarr and PyScript, I have a hunch that implementing Xarray/Zarr visualization in normal PyScript on Pyodide is tractable today (I plan on working on a prototype around the holidays), but running on something as lightweight as micropython would be a significant challenge (which I’m excited about). How reasonable are these thoughts? Am I missing something obvious? If you wanted to visualize Zarr data with Xarray in the browser and have it be lightning fast, how would you go about it?
Hi @Al (@alxrms) - so MicroPython has a ulab package that gives you a bunch of Numpy like capabilities. We're currently discussing with Damien (i.e. 5mins ago I just pinged him an email about this very thing before checking discord 😉 ) ways in which folks can get "custom" builds of MicroPython so they get the additional features they need for PyScript-y apps. As for Zarr (this is my first encounter with that project, so thanks for the heads up), I guess this is all about knowing which layer of the stack needs to be changed. I.e. PyScript sits atop MicroPython, but it feels to me like MicroPython is the layer into which the Zarr integration should fit. My suggestion is for you to join the MicroPython discord, visit the WASM channel and start asking questions. Damien and the other MP folks are all very friendly and collaborative... and @dpgeorge is also aware that MicroPython in WASM is both an actual thing AND a completely new (and perhaps unforeseen) opportunity for MicroPython to flourish and thrive. So this is early days... and any collaboration/initial steps would be very welcome... TL;DR: it's an exciting time to be involved because we're the first ones taking steps in these fresh fields of snow </poeticmetaphors>. 😉
❤️ 1
👍 1
10:36
Also, what a fun holiday project. 😄
Avatar
Al (@alxrms) 20/12/2024 14:49
Thanks so much for the thoughtful response, Nicholas. And especially so for the pointers! I’ll check out ulab, I think that’s just what I need.
14:50
I’ll definitely post here as I pursue this project.
👍 1
❤️ 1
Avatar
Looking forward to seeing what you cook up!
❤️ 1
Avatar
trying to run this test code but i get error that dht syntax is invalid from flask import Flask import time import board import adafruit_dht app = Flask(__name__) @app.route("/") dht = adafruit_dht.DHT11(board.D2) while True: try: temperature = dht.temperature humidity = dht.humidity # Print what we got to the REPL print("Temp: {:.1f} *C \t Humidity: {}%".format(temperature, humidity)) except RuntimeError as e: # Reading doesn't always work! Just print error and we'll try again print("Reading from DHT failure: ", e.args) time.sleep(1)
Avatar
The examples code for DHT_Adafruit suggests that you get eth readings by using humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
21:12
Python library to read the DHT series of humidity and temperature sensors on a Raspberry Pi or Beaglebone Black. - adafruit/Adafruit_Python_DHT
Avatar
But I am using adafruit_circuitpython_dht
Avatar
Avatar
igilq
But I am using adafruit_circuitpython_dht
but you are importing import adafruit_dht and not import adafruit_circuitpython_dht
12:00
CircuitPython support for DHT11 and DHT22 type temperature/humidity devices - adafruit/Adafruit_CircuitPython_DHT
12:01
remember to update your toml to point to the right one (actually both because one calls the other)
12:03
sorry - i forgot - you're not using pyscript but flask... so you just need to add the import and call the right functin as per the examples
Avatar
I used this but it still gives me same error
Avatar
It might be confusing some stuff because when flask part it commented out it works normally
Avatar
Update, flask is colliding with this library
22:17
Without flask everything works fine. When I add flask code crashes
Avatar
how are people usually hosting/deploying their pyscript apps?
Avatar
Avatar
Djo
how are people usually hosting/deploying their pyscript apps?
did you have a look to pyscript.com ?
Avatar
Avatar
Djo
how are people usually hosting/deploying their pyscript apps?
PyScript.com is the usual answer, although any static hosting site will do (for the sake of balance). Supporting PyScript.com supports the oss project though. 👍
Avatar
ok nice thank you 🙂
Avatar
Chris Laffra 26/02/2025 22:49
You can also host your project on GitHub Pages. See this example: https://pyscript.github.io/ltk/. That make deploying code hosted on GitHub very easy, with a simple GitHub action.
Avatar
Avatar
Chris Laffra
You can also host your project on GitHub Pages. See this example: https://pyscript.github.io/ltk/. That make deploying code hosted on GitHub very easy, with a simple GitHub action.
Andrea Giammarchi 27/02/2025 10:33
you have that copy pasted script that does nothing in there too 😉 ... but in GitHub you can use mini-coi.js the proper way, just not as copy/paste script, it should be the first <script src="mini-coi.js"></script> tag on that HTML (and every other) and you'll be good to go with workers too
Avatar
Chris Laffra 27/02/2025 10:36
Hi @Andrea Giammarchi LTK is part of PyScript, so I welcome PRs 🤓
👍 1
Avatar
Avatar
Chris Laffra
Hi @Andrea Giammarchi LTK is part of PyScript, so I welcome PRs 🤓
Andrea Giammarchi 27/02/2025 10:44
Copying inline mini-coi cannot possibly work because the Service Worker must be a file a part or it&#39;s incapable of being registered. This MR adds mini-coi file and it uses it properly so th...
👍 1
Avatar
ThisIsMyUsername 17/03/2025 15:07
@Andrea Giammarchi I am having an issue with mini-coi. I am working with our system administrator to host my website on our servers. We noticed that there are no issues with mini-coi when using my local ip address, but it does not work when using a public ip address. This is the error that I am getting. mini-coi is in the root directory, but I am using flask. I am not sure if this is a flask related issue or if I have something setup wrong. Uncaught TypeError: Cannot read properties of undefined (reading 'register') at mini-coi.js:6:11 at mini-coi.js:28:7
15:07
Any help would be aprreciated.
Avatar
ThisIsMyUsername 17/03/2025 15:15
Can you help me with this?
Avatar
Avatar
ThisIsMyUsername
Can you help me with this?
Andrea Giammarchi 17/03/2025 15:29
it has to be HTTPS or ServiceWorker won't work ... to use a local IP address you need to bootstrap Chrome/ium with forced-enabled SharedArrayBuffer, there is no other way (edited)
15:31
unless, of course, your server provides HTTPS certificates ... this is not a mini-coi issue, this is how every new Web feature works out there ... HTTPS or forget about it.
15:32
if your flask server can provide handshake for HTTPS and promote every http://128.128.128.X agent to use that https://.... version and it has recognizable certificates, you're done, but it might be a bumpy ride.
15:33
this is an extremely old, likely outdated post of mine, but it explains the issue everyone has with testing locally via netwrok addresses, mobile, intranet, or whatnot https://webreflection.co.uk/blog/2015/08/08/bringing-ssl-to-your-private-network/
Avatar
ThisIsMyUsername 17/03/2025 15:34
Thanks for the feedback. I will keep working on it.
Avatar
Avatar
ThisIsMyUsername
Thanks for the feedback. I will keep working on it.
Andrea Giammarchi 17/03/2025 16:39
to test what I am saying try to launch your chrome/ium like this: https://github.com/WebReflection/coincident-oled?tab=readme-ov-file#launch-chromeium (edited)
The electroff RapberryPi demo via coincident/server - WebReflection/coincident-oled
Avatar
Avatar
Andrea Giammarchi
to test what I am saying try to launch your chrome/ium like this: https://github.com/WebReflection/coincident-oled?tab=readme-ov-file#launch-chromeium (edited)
Andrea Giammarchi 17/03/2025 16:40
you can omit the --kiosk argument to not have it full screen
Avatar
ThisIsMyUsername 17/03/2025 17:22
Thanks.
Avatar
Avatar
Andrea Giammarchi
this is an extremely old, likely outdated post of mine, but it explains the issue everyone has with testing locally via netwrok addresses, mobile, intranet, or whatnot https://webreflection.co.uk/blog/2015/08/08/bringing-ssl-to-your-private-network/
Andrea Giammarchi 17/03/2025 17:34
just realized that post has 10 years now and still actual 🥳
🤗 1
Avatar
I am soooo confused how vue.js can work with py-script
16:14
I am getting the following error:
16:14
vue.global.js:2263 [Vue warn]: Failed to resolve component: py-script If this is a native custom element, make sure to exclude it from component resolution via compilerOptions.isCustomElement. at <App>
Avatar
Avatar
agile_prg
vue.global.js:2263 [Vue warn]: Failed to resolve component: py-script If this is a native custom element, make sure to exclude it from component resolution via compilerOptions.isCustomElement. at <App>
someone else asked about this last year in the pyscript help thread (search discord for "Vue") - I don't think there was a satisfactory answer. You could look at pyscript.com which seems to be using Vue as a wrapper. Good luck. The most likely cause of this error appears to be that whatever you are indicating is a "component" is not actually a component. Maybe if you posted in the pyscript-help thread and pointed to a demo on pyscript.com you might get some feedback but maybe you can't get Vue working over there (probably you can).
Avatar
Avatar
agile_prg
vue.global.js:2263 [Vue warn]: Failed to resolve component: py-script If this is a native custom element, make sure to exclude it from component resolution via compilerOptions.isCustomElement. at <App>
Josh (EduBlocks) 16/04/2025 07:39
Using the py-script tag will conflict with Vue. If you can use workers, you probably want to look at using the donkey API instead https://docs.pyscript.net/2024.10.1/api/#pyscriptcoredonkey
Avatar
Having real difficulty with async/await and the pyscript storage module. Can anyone offer advice ? The docs say: from pyscript import storage store = await storage("my-storage-name") and store will be a dictionary. This seems to be taking advantage of the hidden top level async that pyscript is called with. However I want to start the store and read values from within a class (specifically a reactive model class within the class which is the ltk.) So that each UI component can be independent of global variables. I know I can't do an await inside an __init__ function. So what is the best way to get something working which would behave like this: class Reactive_component(ltk.Model): def __init__(self): super().__init__() self.store = await self.start_store() async def start_store(self): self.store = await storage("my-storage-name") So I can then do reads and writes(syncs) to self.store. I have seen a solution that adds a class method to an async_init alongside the __init__ like this @classmethod async def build(cls): instance = cls() await instance.async_init() return instance but as this would be called from inside the parent __init__ (from the ltk) I seem to be cascading these all the way to the top. Is there another way - maybe using asyncio.run() or somesuch ? (although asyncio.run cannot be called from a running event loop(I.e. inside an __init__)
Avatar
Avatar
Neon22
Having real difficulty with async/await and the pyscript storage module. Can anyone offer advice ? The docs say: from pyscript import storage store = await storage("my-storage-name") and store will be a dictionary. This seems to be taking advantage of the hidden top level async that pyscript is called with. However I want to start the store and read values from within a class (specifically a reactive model class within the class which is the ltk.) So that each UI component can be independent of global variables. I know I can't do an await inside an __init__ function. So what is the best way to get something working which would behave like this: class Reactive_component(ltk.Model): def __init__(self): super().__init__() self.store = await self.start_store() async def start_store(self): self.store = await storage("my-storage-name") So I can then do reads and writes(syncs) to self.store. I have seen a solution that adds a class method to an async_init alongside the __init__ like this @classmethod async def build(cls): instance = cls() await instance.async_init() return instance but as this would be called from inside the parent __init__ (from the ltk) I seem to be cascading these all the way to the top. Is there another way - maybe using asyncio.run() or somesuch ? (although asyncio.run cannot be called from a running event loop(I.e. inside an __init__)
Andrea Giammarchi 14/05/2025 15:54
However I want to start the store and read values from within a class
why can't you just initialize the store once outside the class? having dozen stores is not going to be super performant + the overhead IndexedDB might have on multiple init might be huge ... but because the IndexedDB API is inevitably async, there is no way to avoid awaiting somewhere in your logic, being that an async read or an async write method or having an explicit await ref.init_storage() after initializing that ref.
(edited)
15:55
that, of course, unless you await the storage once on top of your module
15:56
in such case the sync nature of the sotarge is mimicked
15:56
but behind the scene it's still async due IndexedDB API
15:58
if interested about the JS module behind, you have the sync init option here, then every read/write/has operation requires to be awaited: https://github.com/WebReflection/idb-map/?tab=readme-ov-file#example
Contribute to WebReflection/idb-map development by creating an account on GitHub.
Avatar
Avatar
Andrea Giammarchi
However I want to start the store and read values from within a class
why can't you just initialize the store once outside the class? having dozen stores is not going to be super performant + the overhead IndexedDB might have on multiple init might be huge ... but because the IndexedDB API is inevitably async, there is no way to avoid awaiting somewhere in your logic, being that an async read or an async write method or having an explicit await ref.init_storage() after initializing that ref.
(edited)
The ONLY reason I was trying to do it from within the code was because I am trying to write UI modules that are entirely independent of each other. Its working quite well. I can make ltk based UI elements in a single file - that work (thanks to __main__) and that can also be imported to be used by amore complex UI that refers to them, and which in turn can be imported to even higher levels of hierarchy. If I define the access to store as a global in each I "think" I might be generating problems for myself. That is my only reason. For now I will continue with globals. Thanks for trying to help. Cheers...
21:38
maybe I have to put it in its own module and then import that at whatever the top level module is
Avatar
Avatar
Neon22
maybe I have to put it in its own module and then import that at whatever the top level module is
Andrea Giammarchi 15/05/2025 09:40
that works too, I assume!
Avatar
Avatar
Andrea Giammarchi
that works too, I assume!
alas you can't import a module that has an await in it. It arrives unresolved with no internals. Sigh. Guess I just have to manually edit every file for now...
Avatar
Avatar
Neon22
alas you can't import a module that has an await in it. It arrives unresolved with no internals. Sigh. Guess I just have to manually edit every file for now...
Andrea Giammarchi 19/05/2025 13:53
bummer ... it's always possible in JS to do so, apologies for misleading there
Avatar
Its ok. I worked out how to do it using the tip about defining your own class inheriting from Storage (capital S) as described in the docs. I will "soon" be adding the demo to the example PR I have already submitted
Avatar
Wheatley62 21/05/2025 15:11
Honestly, I don't know if the problem is related to pyscript, but I'm still wondering if you have any ideas. I'm following a tutorial to display a spreadsheet from a csv file on my page using the <p id="csv"> tag. Here's the script for the tutorial in question: import pandas as pd from pyodide.http import open_url url = 'list.csv' df = pd.read_csv(open_url(url)) csv = Element('csv') csv.write(df.head()) The problem is that it doesn't recognize the Element() function. I've searched for Element() in the API documents (whether pandas, pyscript, or other support sites), without success. Thanks. (edited)
Avatar
Avatar
Wheatley62
Honestly, I don't know if the problem is related to pyscript, but I'm still wondering if you have any ideas. I'm following a tutorial to display a spreadsheet from a csv file on my page using the <p id="csv"> tag. Here's the script for the tutorial in question: import pandas as pd from pyodide.http import open_url url = 'list.csv' df = pd.read_csv(open_url(url)) csv = Element('csv') csv.write(df.head()) The problem is that it doesn't recognize the Element() function. I've searched for Element() in the API documents (whether pandas, pyscript, or other support sites), without success. Thanks. (edited)
Andrea Giammarchi 21/05/2025 15:26
we have display utility in PyScript but also a fetch one ... synchronous API will fail on the main thread + we always run top-level await so that open_url sohuld likely not be used unless you are sure you can use it (i.e. in a worker)
👍 1
Avatar
Following on from Andrea's advice. when making a worker it appears you will have most success with a "Named worker" which is started in index.html. This does indeed make it easier to compartmentalise these aspects. Named worker is embedded in this section of docs - https://docs.pyscript.net/2025.3.1/user-guide/workers/#worker-interactions
Avatar
Avatar
Wheatley62
Honestly, I don't know if the problem is related to pyscript, but I'm still wondering if you have any ideas. I'm following a tutorial to display a spreadsheet from a csv file on my page using the <p id="csv"> tag. Here's the script for the tutorial in question: import pandas as pd from pyodide.http import open_url url = 'list.csv' df = pd.read_csv(open_url(url)) csv = Element('csv') csv.write(df.head()) The problem is that it doesn't recognize the Element() function. I've searched for Element() in the API documents (whether pandas, pyscript, or other support sites), without success. Thanks. (edited)
I don't have an example of p=csv. I use the ltk.Table and regular import csv in python. No example for you from me but the kitchensink for ltk has one here: https://pyscript.github.io/ltk/?tab=4&runtime=mpy . Also (on a previous note - here is a demo of Named worker. It hasn't been cleaned up yet so its not ready for a tutorial but it does work and will make an OK example eventually. - https://pyscript.com/@neon22/starter-05-workers/latest?files=README.md Personally I find the ltk very capable and the examples good.
👍 1
Avatar
i'm quite new and don't have much experience with js practices, but i can't seem to pass arguments to a function through py-click. if i read correctly, was it patched out for security?
Avatar
Avatar
haohaohao
i'm quite new and don't have much experience with js practices, but i can't seem to pass arguments to a function through py-click. if i read correctly, was it patched out for security?
it sounds like you might be using a very old version of pyscript. No security problem but consult the latest docs here to get started: https://docs.pyscript.net/2025.8.1/
Avatar
ohhhhh. i just realized i've been using 2024.2.1. thank you
21:50
after updating, it still doesn't work? so far i'm just trying to get a button to run a function that takes a string parameter, but it keeps telling me that the "call" property is undefined. i've already asked google.
Avatar
Avatar
haohaohao
after updating, it still doesn't work? so far i'm just trying to get a button to run a function that takes a string parameter, but it keeps telling me that the "call" property is undefined. i've already asked google.
are you experimenting using pyscript.com ? if so - feel free to post a link and we can have a look
Avatar
oh it's fine now, i found out that you can use event.currentTarget for my function, thanks for helping :)
Avatar
Original message was deleted or could not be loaded.
Does spam like this actually work? I doubt you'll find any success here.
Exported 1,072 message(s)
Timezone: UTC+0