Re: Sanitise user input for a script

2024-08-30 Thread Simon Connah via Python-list
On Friday, 30 August 2024 at 21:23, Peter J. Holzer via Python-list 
 wrote:

> 

> 

> On 2024-08-30 19:18:29 +, Simon Connah via Python-list wrote:
> 

> > I need to write a script that will take some user input (supplied on a
> > website) and then execute a Python script on a host via SSH. I'm
> > curious what the best options are for protecting against malicious
> > input in much the smae way as you sanitise SQL to protect against SQL
> > injections.
> 

> 

> (Aside: Don't "sanitize" SQL. Use placeholders.)
> 

> > I could do it either on the website itself or by doing it on the host
> > machine.
> 

> 

> You will have to do it in the web site.
> 

> The SSH manual states:
> 

> | If supplied, the arguments will be appended to the command, separated by
> | spaces, before it is sent to the server to be executed.
> 

> So whether you call
> ssh myhost print_args a b c
> or
> ssh myhost print_args a "b c"
> in both cases exactly the same string will be sent to myhost, and it
> won't have any chance to distinguish them.
> 

> So you will either have to filter ("sanitize") the arguments or properly
> quote them before invoking SSH.
> 

> > If someone has any suggestions I'd appreciated it. If you need more
> > information then please let me know.
> 

> 

> First, if there is any chance that your arguments can contain characters
> with meaning to the shell (like an apostrophe in a name), get the
> quoting correct. If you can, transmit those arguments in a different way
> (e.g. as input, maybe just nul-separated, may as JSON, or whatever).
> 

> That removes the SSH-specific problems. There may still be problems with
> the python script on the host.
> 

> Then, do all the validation you can on the web server. Reject all
> requests which aren't valid. But be sure to check against the relevant
> specifications, not your prejudices (You may not think that an
> apostrophe in an email address is valid, but it is). Include meaningful
> error messages (not just "input invalid"). Helping your legitimate users
> is more important than slightly inconveniencing an attacker.
> 


Thank you very much. That is very useful.

Simon.

signature.asc
Description: OpenPGP digital signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Sanitise user input for a script

2024-08-30 Thread Simon Connah via Python-list
On Friday, 30 August 2024 at 23:35, Thomas Passin via Python-list 
 wrote:

> 

> 

> On 8/30/2024 3:18 PM, Simon Connah via Python-list wrote:
> 

> > I need to write a script that will take some user input (supplied on a 
> > website) and then execute a Python script on a host via SSH. I'm curious 
> > what the best options are for protecting against malicious input in much 
> > the smae way as you sanitise SQL to protect against SQL injections.
> 

> 

> You should never, never, never "sanitize" SQL. Use prepared statements
> instead.

Yes. Sorry. I forgot what it was called and accidentally called it sanitising 
instead but I'm using prepared statements in psycopg 3 for SQL.

> 

> What kind of user input do you expect to get that would need to be
> "sanitized"? How are you going to use it such that malicious input might
> cause trouble? I hope you aren't planning to exec() it. Are you
> expecting a user to send in a script and your server will execute it?
> Better read up on sandboxing, then.

No. I'm not planning on exec() a random script. I have a prepared Python script 
which configures various things. The web server connects to the server via SSH 
and runs my Python script which then runs commands like bhyve (FreeBSD) and it 
also does things like configure the firewall config file to change firewall 
rules. The customer has no direct access to the Python script.

In terms of arguments the script that deals with bhyve for instance takes 
arguments such as CPU count and RAM amount.

> 

> If you won't be exec()ing a script, then you can consider creating an
> API where each method of the API can only do limited things, and only
> with certain parameters not all of all them. The SSH message can include
> the name of the method to use.
> 

> And follow what Peter Holzer wrote. Don't forget that quoting practices
> are not the same between Windows and Linux.

Thank you. I'll look into this. Makes sense.

> 

> > I could do it either on the website itself or by doing it on the host 
> > machine.
> > 

> > I'm thinking of using argparse but I'm aware it does not offer any 
> > protection itself.
> > 

> > If someone has any suggestions I'd appreciated it. If you need more 
> > information then please let me know.
> > 

> > Simon.
> 

> 

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

signature.asc
Description: OpenPGP digital signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Sanitise user input for a script

2024-08-30 Thread Thomas Passin via Python-list

On 8/30/2024 3:18 PM, Simon Connah via Python-list wrote:

I need to write a script that will take some user input (supplied on a website) 
and then execute a Python script on a host via SSH. I'm curious what the best 
options are for protecting against malicious input in much the smae way as you 
sanitise SQL to protect against SQL injections.


You should never, never, never "sanitize" SQL. Use prepared statements 
instead.


What kind of user input do you expect to get that would need to be 
"sanitized"? How are you going to use it such that malicious input might 
cause trouble?  I hope you aren't planning to exec() it.  Are you 
expecting a user to send in a script and your server will execute it? 
Better read up on sandboxing, then.


If you won't be exec()ing a script, then you can consider creating an 
API where each method of the API can only do limited things, and only 
with certain parameters not all of all them. The SSH message can include 
the name of the method to use.


And follow what Peter Holzer wrote.  Don't forget that quoting practices 
are not the same between Windows and Linux.




I could do it either on the website itself or by doing it on the host machine.

I'm thinking of using argparse but I'm aware it does not offer any protection 
itself.

If someone has any suggestions I'd appreciated it. If you need more information 
then please let me know.

Simon.




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


Re: Sanitise user input for a script

2024-08-30 Thread Peter J. Holzer via Python-list
On 2024-08-30 19:18:29 +, Simon Connah via Python-list wrote:
> I need to write a script that will take some user input (supplied on a
> website) and then execute a Python script on a host via SSH. I'm
> curious what the best options are for protecting against malicious
> input in much the smae way as you sanitise SQL to protect against SQL
> injections.

(Aside: Don't "sanitize" SQL. Use placeholders.)


> I could do it either on the website itself or by doing it on the host
> machine.

You will have to do it in the web site.

The SSH manual states:

| If supplied, the arguments will be appended to the command, separated by
| spaces, before it is sent to the server to be executed.

So whether you call 
ssh myhost print_args a b c
or
ssh myhost print_args a "b c"
in both cases exactly the same string will be sent to myhost, and it
won't have any chance to distinguish them.

So you will either have to filter ("sanitize") the arguments or properly
quote them before invoking SSH.

> If someone has any suggestions I'd appreciated it. If you need more
> information then please let me know.

First, if there is any chance that your arguments can contain characters
with meaning to the shell (like an apostrophe in a name), get the
quoting correct. If you can, transmit those arguments in a different way
(e.g. as input, maybe just nul-separated, may as JSON, or whatever). 

That removes the SSH-specific problems. There may still be problems with
the python script on the host.

Then, do all the validation you can on the web server. Reject all
requests which aren't valid. But be sure to check against the relevant
specifications, not your prejudices (You may not think that an
apostrophe in an email address is valid, but it is). Include meaningful
error messages (not just "input invalid"). Helping your legitimate users
is more important than slightly inconveniencing an attacker.

hp


-- 
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | h...@hjp.at |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"


signature.asc
Description: PGP signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Sanitise user input for a script

2024-08-30 Thread Simon Connah via Python-list
I need to write a script that will take some user input (supplied on a website) 
and then execute a Python script on a host via SSH. I'm curious what the best 
options are for protecting against malicious input in much the smae way as you 
sanitise SQL to protect against SQL injections.

I could do it either on the website itself or by doing it on the host machine.

I'm thinking of using argparse but I'm aware it does not offer any protection 
itself.

If someone has any suggestions I'd appreciated it. If you need more information 
then please let me know.

Simon.

signature.asc
Description: OpenPGP digital signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: From geeksforgeeks.org, on converting the string created by the input() to an INT

2023-05-25 Thread Chris Angelico
On Fri, 26 May 2023 at 09:58, Kevin M. Wilson via Python-list
 wrote:
>
> So, why can't a string of an integer be converted to an integer, via 
> print(int(str('23.5')))???

23.5 is not an integer, so "23.5" is not the string of an integer.

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


From geeksforgeeks.org, on converting the string created by the input() to an INT

2023-05-25 Thread Kevin M. Wilson via Python-list
We can first convert the string representation of float into float using 
float() function and then convert it into an integer using int().So, why can't 
a string of an integer be converted to an integer, via 
print(int(str('23.5')))???
Perplexed






| print(int(float('23.5'))) |



"When you pass through the waters, I will be with you: and when you pass 
through the rivers, they will not sweep over you. When you walk through the 
fire, you will not be burned: the flames will not set you ablaze."      
Isaiah 43:2
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: pygame.midi input/output not working

2022-12-22 Thread Thomas Passin
This issue thread on Github says that everyone is waiting on the 
packaging maintainer, but nothing from him for some time.


On 12/22/2022 5:04 AM, Peter J. Holzer wrote:

On 2022-12-21 17:23:47 -0500, Thomas Passin wrote:

The pygame web site says this:

"Pygame still does not run on Python 3.11"


This doesn't sound like "we haven't got around to preparing packages
yet" and more like "there's a serious incompatibility we haven't solved
yet".

Does anybody know what the issue is?

 hp




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


Re: pygame.midi input/output not working

2022-12-22 Thread Weatherby,Gerard
https://github.com/pygame/pygame/issues/3522

From: Python-list  on 
behalf of Peter J. Holzer 
Date: Thursday, December 22, 2022 at 5:06 AM
To: python-list@python.org 
Subject: Re: pygame.midi input/output not working
On 2022-12-21 17:23:47 -0500, Thomas Passin wrote:
> The pygame web site says this:
>
> "Pygame still does not run on Python 3.11"

This doesn't sound like "we haven't got around to preparing packages
yet" and more like "there's a serious incompatibility we haven't solved
yet".

Does anybody know what the issue is?

hp

--
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | h...@hjp.at |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: pygame.midi input/output not working

2022-12-22 Thread Peter J. Holzer
On 2022-12-21 17:23:47 -0500, Thomas Passin wrote:
> The pygame web site says this:
> 
> "Pygame still does not run on Python 3.11"

This doesn't sound like "we haven't got around to preparing packages
yet" and more like "there's a serious incompatibility we haven't solved
yet".

Does anybody know what the issue is?

hp

-- 
   _  | Peter J. Holzer| Story must make more sense than reality.
|_|_) ||
| |   | h...@hjp.at |-- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |   challenge!"


signature.asc
Description: PGP signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Fwd: pygame.midi input/output not working

2022-12-21 Thread Patrick EGLOFF
Hi Thomas,

Thanks for the answer AND solution !
That was it... shame on me, I didn't notice this warning.

I uninstalled 3.11.1 and installed 3.10.9, and my software is back to live
!

Now I have to figure out another problem. I will make another post about
this serial weird behavior.

Thanks for making my day !
Patrick

Le mer. 21 déc. 2022 à 23:27, Thomas Passin  a écrit :

> On 12/21/2022 4:32 PM, Patrick EGLOFF wrote:
> > HI,
> > Some time ago I wrote a small software using pygame.midi
> > It worked just fine with Win10/ python 3.9 / SDL 2.0.14 / pygame 2.0.1
> >
> > I had to change my computer and now I installed Win10 / Python 3.11.1 /
> SDL
> > 2.0.18 / pygame 2.1.2
> >
> > The following instructions don't work anymore, making the IDE stop
> > execution :
> >
> > my_input = pygame.midi.Input(MidiDeviceIn)
> > midi_out = pygame.midi.Output(MidiDeviceOut)
> >
> > Does someone have a suggestion?
>
> The pygame web site says this:
>
> "Pygame still does not run on Python 3.11"
>
> Also from the same page:
>
> "Make sure you install python with the "Add python to PATH" option
> selected. This means that python, and pip will work for you from the
> command line."
>
> See https://www.pygame.org/wiki/GettingStarted#Pygame%20Installation
>
> So what to do until pygame runs in Python 3.11?  I'd install an earlier
> version of Python.  You can have several versions on your machine at the
> same time.  Remember, you have to install all the required packages with
> each version of Python - they don't use each other's code or libraries.
> --
> https://mail.python.org/mailman/listinfo/python-list
>


-- 
Patrick Egloff
email : pegl...@gmail.com
Web page : http://www.egloff.eu


-- 
Patrick Egloff
email : pegl...@gmail.com
Web page : http://www.egloff.eu
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: pygame.midi input/output not working

2022-12-21 Thread Thomas Passin

On 12/21/2022 4:32 PM, Patrick EGLOFF wrote:

HI,
Some time ago I wrote a small software using pygame.midi
It worked just fine with Win10/ python 3.9 / SDL 2.0.14 / pygame 2.0.1

I had to change my computer and now I installed Win10 / Python 3.11.1 / SDL
2.0.18 / pygame 2.1.2

The following instructions don't work anymore, making the IDE stop
execution :

my_input = pygame.midi.Input(MidiDeviceIn)
midi_out = pygame.midi.Output(MidiDeviceOut)

Does someone have a suggestion?


The pygame web site says this:

"Pygame still does not run on Python 3.11"

Also from the same page:

"Make sure you install python with the "Add python to PATH" option 
selected. This means that python, and pip will work for you from the 
command line."


See https://www.pygame.org/wiki/GettingStarted#Pygame%20Installation

So what to do until pygame runs in Python 3.11?  I'd install an earlier 
version of Python.  You can have several versions on your machine at the 
same time.  Remember, you have to install all the required packages with 
each version of Python - they don't use each other's code or libraries.

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


pygame.midi input/output not working

2022-12-21 Thread Patrick EGLOFF
HI,
Some time ago I wrote a small software using pygame.midi
It worked just fine with Win10/ python 3.9 / SDL 2.0.14 / pygame 2.0.1

I had to change my computer and now I installed Win10 / Python 3.11.1 / SDL
2.0.18 / pygame 2.1.2

The following instructions don't work anymore, making the IDE stop
execution :

my_input = pygame.midi.Input(MidiDeviceIn)
midi_out = pygame.midi.Output(MidiDeviceOut)

Does someone have a suggestion?

Thanks,

-- 
Patrick Egloff
email : pegl...@gmail.com
Web page : http://www.egloff.eu
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to test input via subprocess.Popen with data from file

2022-03-11 Thread Tobiah

Why not just have scripts that echo out the various sets of test
data you are interested in?  That way, Popen would
always be your interface and you wouldn't have to
make two cases in the consumer script.

In other words, make program that outputs test
data just like your main data source program.
Then the consumer would only have to work in one way.







On 3/10/22 04:16, Loris Bennett wrote:

Hi,

I have a command which produces output like the
following:

   Job ID: 9431211
   Cluster: curta
   User/Group: build/staff
   State: COMPLETED (exit code 0)
   Nodes: 1
   Cores per node: 8
   CPU Utilized: 01:30:53
   CPU Efficiency: 83.63% of 01:48:40 core-walltime
   Job Wall-clock time: 00:13:35
   Memory Utilized: 6.45 GB
   Memory Efficiency: 80.68% of 8.00 GB

I want to parse this and am using subprocess.Popen and accessing the
contents via Popen.stdout.  However, for testing purposes I want to save
various possible outputs of the command as text files and use those as
inputs.

What format should I use to pass data to the actual parsing function?

I could in both production and test convert the entire input to a string
and pass the string to the parsing method.

However, I could use something like

test_input_01 = subprocess.Popen(
 ["cat test_input_01.txt"],
 stdout=subprocess.PIPE,
 )
   
for the test input and then pass a Popen object to the parsing function.


Any comments on these alternative or suggestions for doing something
completely different?

Cheers,

Loris
  


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


Re: How to test input via subprocess.Popen with data from file

2022-03-11 Thread Roel Schroeven

Op 11/03/2022 om 10:11 schreef Roel Schroeven:

Op 10/03/2022 om 13:16 schreef Loris Bennett:

Hi,

I have a command which produces output like the
following:

   Job ID: 9431211
   Cluster: curta
   User/Group: build/staff
   State: COMPLETED (exit code 0)
   Nodes: 1
   Cores per node: 8
   CPU Utilized: 01:30:53
   CPU Efficiency: 83.63% of 01:48:40 core-walltime
   Job Wall-clock time: 00:13:35
   Memory Utilized: 6.45 GB
   Memory Efficiency: 80.68% of 8.00 GB

I want to parse this and am using subprocess.Popen and accessing the
contents via Popen.stdout.  However, for testing purposes I want to save
various possible outputs of the command as text files and use those as
inputs.

What format should I use to pass data to the actual parsing function?

Is this a command you run, produces that output, and then stops (as 
opposed to a long-running program that from time to time generates a 
bunch of output)?
Because in that case I would use subprocess.run() with 
capture_output=True instead of subprocess.Popen(). subprocess.run() 
returns a CompletedProcess instance wich has stdout and stderr members 
that contain the captured output as byte sequences or strings, 
depending on the parameters you passed.


So in your case I would simply read the content of each text file as a 
whole into a string, and use subprocess.run() to get the command's 
output also as a string. Then you can have a parse function that 
accepts such strings, and works exactly the same for the text files as 
for the command output. Your parse function can then use splitlines() 
to access the lines individually. The data size is very small so it's 
not a problem to have it all in memory at the same time (i.e. no need 
to worry about trying to stream it instead).



Very simple example:

    import subprocess
    from pprint import pprint

    def parse(state_data):
    lines = state_data.splitlines(keepends=False)
    state_dict = {}
    for line in lines:
    key, value = line.split(': ')
    state_dict[key] = value
    return state_dict

    def read_from_command():
    return subprocess.run(['./jobstate'], capture_output=True, 
check=True, encoding='UTF-8').stdout


    def read_from_file(fn):
    with open(fn, 'rt', encoding='UTF-8') as f:
    return f.read()

    pprint(parse(read_from_command()))
    pprint(parse(read_from_file('jobfile')))

--
"Iceland is the place you go to remind yourself that planet Earth is a
machine... and that all organic life that has ever existed amounts to a greasy
film that has survived on the exterior of that machine thanks to furious
improvisation."
-- Sam Hughes, Ra

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


Re: How to test input via subprocess.Popen with data from file

2022-03-11 Thread Roel Schroeven

Op 10/03/2022 om 13:16 schreef Loris Bennett:

Hi,

I have a command which produces output like the
following:

   Job ID: 9431211
   Cluster: curta
   User/Group: build/staff
   State: COMPLETED (exit code 0)
   Nodes: 1
   Cores per node: 8
   CPU Utilized: 01:30:53
   CPU Efficiency: 83.63% of 01:48:40 core-walltime
   Job Wall-clock time: 00:13:35
   Memory Utilized: 6.45 GB
   Memory Efficiency: 80.68% of 8.00 GB

I want to parse this and am using subprocess.Popen and accessing the
contents via Popen.stdout.  However, for testing purposes I want to save
various possible outputs of the command as text files and use those as
inputs.

What format should I use to pass data to the actual parsing function?

Is this a command you run, produces that output, and then stops (as 
opposed to a long-running program that from time to time generates a 
bunch of output)?
Because in that case I would use subprocess.run() with 
capture_output=True instead of subprocess.Popen(). subprocess.run() 
returns a CompletedProcess instance wich has stdout and stderr members 
that contain the captured output as byte sequences or strings, depending 
on the parameters you passed.


So in your case I would simply read the content of each text file as a 
whole into a string, and use subprocess.run() to get the command's 
output also as a string. Then you can have a parse function that accepts 
such strings, and works exactly the same for the text files as for the 
command output. Your parse function can then use splitlines() to access 
the lines individually. The data size is very small so it's not a 
problem to have it all in memory at the same time (i.e. no need to worry 
about trying to stream it instead).


--
"Don't Panic."
-- Douglas Adams, The Hitchhiker's Guide to the Galaxy

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


Re: How to test input via subprocess.Popen with data from file

2022-03-10 Thread Dieter Maurer
Loris Bennett wrote at 2022-3-11 07:40 +0100:
> ... I want to test the parsing ...
>Sorry if I was unclear but my question is:
>
>Given that the return value from Popen is a Popen object and given that
>the return value from reading a file is a single string or maybe a list
>of strings, what should the common format for the argument which is
>passed to the actual parsing function be?

What methods (of its input argument) does the parsing use?
If it uses `Popen` methods, then you pass a `POpen` object;
if it uses only (typical) file methods, then you pass a file object;
if it assumes its input to be a (line) interator, you pass
a (line) iterator (such as a "file" object).

I would design the parsing that it makes as few assumptions
about its input as possible -- to ease testing
and increase the chance for reuse.

That said, I would not design it to work with `Popen` objects
but likely to have a line iterator as input.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to test input via subprocess.Popen with data from file

2022-03-10 Thread Loris Bennett
Dieter Maurer  writes:

> Loris Bennett wrote at 2022-3-10 13:16 +0100:
>>I have a command which produces output like the
>>following:
>>
>>  Job ID: 9431211
>>  Cluster: curta
>>  User/Group: build/staff
>>  State: COMPLETED (exit code 0)
>>  Nodes: 1
>>  Cores per node: 8
>>  CPU Utilized: 01:30:53
>>  CPU Efficiency: 83.63% of 01:48:40 core-walltime
>>  Job Wall-clock time: 00:13:35
>>  Memory Utilized: 6.45 GB
>>  Memory Efficiency: 80.68% of 8.00 GB
>>
>>I want to parse this and am using subprocess.Popen and accessing the
>>contents via Popen.stdout.  However, for testing purposes I want to save
>>various possible outputs of the command as text files and use those as
>>inputs.
>
> What do you want to test? the parsing? the "popen" interaction?
> You can separately test both tasks (I, at your place, would do this).

I just want to test the parsing.

> For the parsing test, it is not relevant that the actual text
> comes from an external process. You can directly read it from a file
> or have it in your text.

As mentioned in the original post, for the tests I indeed want to read
the input from files.

> In my view, you do not need a test for the `Popen` interaction:
> if it works once, it will work always.

Sorry if I was unclear but my question is:

Given that the return value from Popen is a Popen object and given that
the return value from reading a file is a single string or maybe a list
of strings, what should the common format for the argument which is
passed to the actual parsing function be?

Cheers,

Loris
-- 
This signature is currently under construction.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to test input via subprocess.Popen with data from file

2022-03-10 Thread Dieter Maurer
Loris Bennett wrote at 2022-3-10 13:16 +0100:
>I have a command which produces output like the
>following:
>
>  Job ID: 9431211
>  Cluster: curta
>  User/Group: build/staff
>  State: COMPLETED (exit code 0)
>  Nodes: 1
>  Cores per node: 8
>  CPU Utilized: 01:30:53
>  CPU Efficiency: 83.63% of 01:48:40 core-walltime
>  Job Wall-clock time: 00:13:35
>  Memory Utilized: 6.45 GB
>  Memory Efficiency: 80.68% of 8.00 GB
>
>I want to parse this and am using subprocess.Popen and accessing the
>contents via Popen.stdout.  However, for testing purposes I want to save
>various possible outputs of the command as text files and use those as
>inputs.

What do you want to test? the parsing? the "popen" interaction?
You can separately test both tasks (I, at your place, would do this).

For the parsing test, it is not relevant that the actual text
comes from an external process. You can directly read it from a file
or have it in your text.

In my view, you do not need a test for the `Popen` interaction:
if it works once, it will work always.
-- 
https://mail.python.org/mailman/listinfo/python-list


How to test input via subprocess.Popen with data from file

2022-03-10 Thread Loris Bennett
Hi,

I have a command which produces output like the
following:

  Job ID: 9431211
  Cluster: curta
  User/Group: build/staff
  State: COMPLETED (exit code 0)
  Nodes: 1
  Cores per node: 8
  CPU Utilized: 01:30:53
  CPU Efficiency: 83.63% of 01:48:40 core-walltime
  Job Wall-clock time: 00:13:35
  Memory Utilized: 6.45 GB
  Memory Efficiency: 80.68% of 8.00 GB

I want to parse this and am using subprocess.Popen and accessing the
contents via Popen.stdout.  However, for testing purposes I want to save
various possible outputs of the command as text files and use those as
inputs. 

What format should I use to pass data to the actual parsing function?

I could in both production and test convert the entire input to a string
and pass the string to the parsing method.

However, I could use something like

   test_input_01 = subprocess.Popen(
["cat test_input_01.txt"],
stdout=subprocess.PIPE,
)
  
for the test input and then pass a Popen object to the parsing function.

Any comments on these alternative or suggestions for doing something
completely different?

Cheers,

Loris
 
-- 
This signature is currently under construction.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: python: server is not receiving input from client flask

2021-06-29 Thread Chris Angelico
On Wed, Jun 30, 2021 at 6:21 AM Jerry Thefilmmaker
 wrote:
> @app.route("/check_answer/", methods = ['POST'])
> def check_answer(ans):
>
> 
> Enter your answer: 
>  
> 

What you're creating here is a route with a placeholder. The
check_answer function will handle POST requests to /check_answer/foo,
/check_answer/spam, /check_answer/barney, /check_answer/whatever. In
each case, the variable "ans" will be given the part of the URL that
 represents - the string "foo" or "spam" or "barney" or whatever.
It's never going to carry a dictionary around.

I'll stress this again: *Your requests must be independently handled*.
You can't think of passing information from one request to another,
because there might not have been a previous request. Moving to the
web means thinking differently about things; you no longer have
control flow from one part of the program to another, you instead have
independent handlers that have to think exclusively about their own
requests.

This might mean carrying some extra information through the form. For
instance, you could include a question ID of some sort (using  for that purpose), and then you could have a global
constant with all of your prewritten questions. There are other ways
to carry information around, but they have to go via the request
itself; you can't keep variables from one function to another.

> Also, where do I see my print statement in this case? Mind you the codes 
> worked fine before I attempted to use flask.

Hmm, that depends on how you're running your code. Ideally, you should
have a server running somewhere - a terminal window or equivalent -
and if you're using Flask's default server (werkzeug), it will be
reporting every request as it goes through. It might look something
like this:

INFO:geventwebsocket.handler:127.0.0.1 - - [2021-06-30 06:30:51] "GET
/ HTTP/1.1" 200 10267 1.569960
INFO:geventwebsocket.handler:127.0.0.1 - - [2021-06-30 06:30:52] "GET
/api/twitch_schedule?channelid=49497888 HTTP/1.1" 200 593 1.403456
INFO:geventwebsocket.handler:127.0.0.1 - - [2021-06-30 06:31:06] "GET
/ HTTP/1.1" 200 10267 1.724949
INFO:geventwebsocket.handler:127.0.0.1 - - [2021-06-30 06:31:07] "GET
/api/twitch_schedule?channelid=49497888 HTTP/1.1" 200 593 1.277206

Your print calls will insert messages into that log, prior to their
corresponding summary lines (the summary is written when you return a
response, so that's at the very end of your function).

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


Re: python: server is not receiving input from client flask

2021-06-29 Thread Jerry Thefilmmaker
On Tuesday, June 29, 2021 at 2:03:58 PM UTC-4, Chris Angelico wrote:
> On Wed, Jun 30, 2021 at 3:38 AM Jerry Thefilmmaker 
>  wrote: 
> > Thanks for taking the time to explained, Chris. Believe me, it helps. It 
> > had me thinking for a while. So, All the stuff about HTTP makes sense. I've 
> > been studying and trying to wrap my head around the rest of your 
> > explanation and see how I can apply it to my codes. 
> >
> Glad to hear it :)
> > So, if I separate my GET method which would be to get the web page from my 
> > POST method which would be assigned to returning value from my form, 
> > wouldn't I have to dedicate 2 functions for any given requests in that 
> > sense? 
> >
> The web page and form response are two completely separate requests. 
> You can't think of them as a single request; in fact, it's entirely 
> possible for someone to send the POST request without first getting 
> the page at all.
> > The only reason I have parameters in my functions is so I can pass value 
> > from 1 function to another which is just stuff that happens in the 
> > background. Is it necessary to have them in my decorators as well, or is it 
> > that these values won't get passed around if they're not integrated in the 
> > decorators? 
> >
> They won't get passed around. The only way to share that information 
> is via the page itself (or something along those lines, like a session 
> variable - which is some magic built on top of cookies). Think about 
> the two requests completely independently, and make sure that (a) the 
> GET request sends back the correct page, and (b) the POST request does 
> whatever it needs to, and sends back a new page. 
> 
> Hopefully that should set you in the right direction! 
> 
> ChrisA

Got it. It all makes sense. It feels like I'm doing all the right things, 
accounting for all functions but somehow it's not working.

I changed my methods. Adjusted my routes. Still the same thing. Now I get this 
error:
  i3 = ans.get(answers, '')
AttributeError: 'str' object has no attribute 'get'

Which doesn't make sense because my object ans is a dictionary and get method 
here is supposed to get another value within the dictionary based on the key 
value of answers which is passed from the client. Does that make sense?

--

Here's my modified code by the way:

@app.route("/")
def main():
return render_template('app.html')

@app.route("/play", methods = ['GET']) 
def play():

qa = questions.qa #list of dict with questions
#user1, user2 = [], [] #containers for each player's answers

if request.method == 'GET':
answers = request.form.get('answers')
random.shuffle(questions.qa)
response = quiz(qa)
print(answers)
return response 

def quiz(qa):
for rand_q in qa:
i = rand_q['question']
i2 = check_answer(i)
   
return render_template('app.html') + i, i2 

@app.route("/check_answer/", methods = ['POST'])
def check_answer(ans):
user1 = []
if request.method == 'POST':
answers = request.form.get('answers')
if 'yes' in answers:
print(ans)
user1.append('yes')
i3 = ans.get(answers, '')
return i3
--
Here's my form from the html file:


Enter your answer: 
 


Also, where do I see my print statement in this case? Mind you the codes worked 
fine before I attempted to use flask.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: python: server is not receiving input from client flask

2021-06-29 Thread Chris Angelico
On Wed, Jun 30, 2021 at 3:38 AM Jerry Thefilmmaker
 wrote:
> Thanks for taking the time to explained, Chris. Believe me, it helps. It had 
> me thinking for a while. So, All the stuff about HTTP makes sense. I've been 
> studying  and trying to wrap my head around the rest of your explanation and 
> see how I can apply it to my codes.
>

Glad to hear it :)

> So, if I separate my GET method which would be to get the web page from my 
> POST method which would be assigned to returning value from my form, wouldn't 
> I have to dedicate 2 functions for any given requests in that sense?
>

The web page and form response are two completely separate requests.
You can't think of them as a single request; in fact, it's entirely
possible for someone to send the POST request without first getting
the page at all.

> The only reason I have parameters in my functions is so I can pass value from 
> 1 function to another which is just stuff that happens in the background. Is 
> it necessary to have them in my decorators as well, or is it that these 
> values won't get passed around if they're not integrated in the decorators?
>

They won't get passed around. The only way to share that information
is via the page itself (or something along those lines, like a session
variable - which is some magic built on top of cookies). Think about
the two requests completely independently, and make sure that (a) the
GET request sends back the correct page, and (b) the POST request does
whatever it needs to, and sends back a new page.

Hopefully that should set you in the right direction!

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


Re: python: server is not receiving input from client flask

2021-06-29 Thread Jerry Thefilmmaker
On Monday, June 28, 2021 at 3:59:54 PM UTC-4, Chris Angelico wrote:
> On Tue, Jun 29, 2021 at 5:43 AM Jerry Thefilmmaker 
>  wrote: 
> > 
> > Do you mind elaborating a bit more on making one function for any given 
> > request? 
> > 
> > As far as defining a bunch of functions that get called when particular 
> > requests come in I thought that's what I had going on in my codes. No? 
> > 
> > Also thank you, on making use of the print statement. Thought once I 
> > crossed over to the web side there was no more need for it. But what you 
> > said makes sense in terms of debugging, because sometimes I couldn't tell 
> > whether the client's variable was getting pass to my function which caused 
> > it not to be triggered. 
> > 
> > Thank you! 
> >
> Sure. I'll take a step back and look quickly at the way HTTP works and 
> how Flask figures out what function to call; you probably know all 
> this but it'll make the explanation easier. 
> 
> Every HTTP request has a method (GET, POST, PUT, DELETE, etc) and a 
> request URI. Some of the URI just figures out whether it goes to your 
> server or not, and the rest is which page within your server. So if 
> you're running on, say, port 5000 on the same computer the web browser 
> is on, then you can go to http://localhost:5000/any/path/here and 
> it'll be handled by your web app. Since the "http://localhost:5000"; 
> part is the way to find the whole server, Flask just looks at the rest 
> of it - "/any/path/here" - to do its routing. So we have two parts - a 
> path and a method - that define which function is called. 
> 
> When you point your browser at "http://localhost:5000/";, that's a GET 
> request (normal web page fetches are GET requests) with a path of "/". 
> 
> When you submit the form, that's a POST request (because the form's 
> method) with a path of "/" (because that's the form's action). I'm 
> assuming here that nothing is getting in the way of that, but that's 
> what printing stuff out can help with. 
> 
> So far, so good. I'm pretty sure none of what I just said is news to 
> you, but let's focus on those two requests: "GET /" and "POST /". 
> 
> The app.route decorator lets you associate a function with some 
> path/method combination. What you have in the code you shared is this:
> > @app.route("/", methods = ['POST', 'GET']) 
> > def play(): 
> > 
> > @app.route("/", methods = ['POST', 'GET']) 
> > def check_answer(ans, user):
> That tells Flask that the play function should be associated with 
> "POST /" and "GET /". And then it tells Flask that the check_answer 
> function should be associated with... the same two routes. 
> 
> I suspect that what you actually intend is for one of those functions 
> to just handle GET, and the other to just handle POST. But another way 
> you could fix this would be to change the URL used as the form's 
> action. It's up to you and what your plans are for the rest of this 
> app. 
> 
> (My recommendation is to start out with each function handling just 
> one route - say, "GET /" for play() and "POST /" for check_answer - 
> and only combine them (with multiple keywords in methods=[...]) once 
> you find that the two functions are duplicating a lot of code.) 
> 
> Once that's sorted out, you'll want to figure out exactly what 
> parameters your functions take. As a general rule, the function's 
> parameters will match the placeholders in the route, so if you're not 
> using placeholders, you'll probably just want them all to take no 
> parameters. Here are some examples from a project of mine: 
> 
> @app.route("/login") 
> def login(): 
> 
> @app.route("/force/") 
> def force_timer(id): 
> 
> @app.route("/") 
> @app.route("/editor/") 
> def mainpage(channelid=None): 
> 
> In the case of mainpage, it handles both "GET /" and "GET 
> /editor/12345", so the function might get a parameter and might not - 
> hence it takes a parameter with a default. For what you're doing here, 
> there are no placeholders in your routes, so all your routed functions 
> will take no args (like login in my example - it only ever handles 
> "GET /login", so it doesn't need anything else). 
> 
> Hope that helps! 
> 
> ChrisA

Thanks for taking the time to explained, Chris. Believe me, it helps. It had me 
thinking for a while. So, All the stuff about HTTP makes sense. I've been 
studying  and trying to wrap my head around the rest of your explanation and 
see how I can apply it to my codes.

So, if I separate my GET method which would be to get the web page from my POST 
method which would be assigned to returning value from my form, wouldn't I have 
to dedicate 2 functions for any given requests in that sense?

The only reason I have parameters in my functions is so I can pass value from 1 
function to another which is just stuff that happens in the background. Is it 
necessary to have them in my decorators as well, or is it that these values 
won't get passed around if they're not integrated in the decorators?
-- 
https://mail

Re: python: server is not receiving input from client flask

2021-06-28 Thread Chris Angelico
On Tue, Jun 29, 2021 at 5:43 AM Jerry Thefilmmaker
 wrote:
>
> Do you mind elaborating a bit more on making one function for any given 
> request?
>
> As far as defining a bunch of functions that get called when particular 
> requests come in I thought that's what I had going on in my codes. No?
>
> Also thank you, on making use of the print statement. Thought once I crossed 
> over to the web side there was no more need for it. But what you said makes 
> sense in terms of debugging, because sometimes I couldn't tell whether the 
> client's variable was getting pass to my function which caused it not to be 
> triggered.
>
> Thank you!
>

Sure. I'll take a step back and look quickly at the way HTTP works and
how Flask figures out what function to call; you probably know all
this but it'll make the explanation easier.

Every HTTP request has a method (GET, POST, PUT, DELETE, etc) and a
request URI. Some of the URI just figures out whether it goes to your
server or not, and the rest is which page within your server. So if
you're running on, say, port 5000 on the same computer the web browser
is on, then you can go to http://localhost:5000/any/path/here and
it'll be handled by your web app. Since the "http://localhost:5000";
part is the way to find the whole server, Flask just looks at the rest
of it - "/any/path/here" - to do its routing. So we have two parts - a
path and a method - that define which function is called.

When you point your browser at "http://localhost:5000/";, that's a GET
request (normal web page fetches are GET requests) with a path of "/".

When you submit the form, that's a POST request (because the form's
method) with a path of "/" (because that's the form's action). I'm
assuming here that nothing is getting in the way of that, but that's
what printing stuff out can help with.

So far, so good. I'm pretty sure none of what I just said is news to
you, but let's focus on those two requests: "GET /" and "POST /".

The app.route decorator lets you associate a function with some
path/method combination. What you have in the code you shared is this:

> @app.route("/", methods = ['POST', 'GET'])
> def play():
>
> @app.route("/", methods = ['POST', 'GET'])
> def check_answer(ans, user):

That tells Flask that the play function should be associated with
"POST /" and "GET /". And then it tells Flask that the check_answer
function should be associated with... the same two routes.

I suspect that what you actually intend is for one of those functions
to just handle GET, and the other to just handle POST. But another way
you could fix this would be to change the URL used as the form's
action. It's up to you and what your plans are for the rest of this
app.

(My recommendation is to start out with each function handling just
one route - say, "GET /" for play() and "POST /" for check_answer -
and only combine them (with multiple keywords in methods=[...]) once
you find that the two functions are duplicating a lot of code.)

Once that's sorted out, you'll want to figure out exactly what
parameters your functions take. As a general rule, the function's
parameters will match the placeholders in the route, so if you're not
using placeholders, you'll probably just want them all to take no
parameters. Here are some examples from a project of mine:

@app.route("/login")
def login():

@app.route("/force/")
def force_timer(id):

@app.route("/")
@app.route("/editor/")
def mainpage(channelid=None):

In the case of mainpage, it handles both "GET /" and "GET
/editor/12345", so the function might get a parameter and might not -
hence it takes a parameter with a default. For what you're doing here,
there are no placeholders in your routes, so all your routed functions
will take no args (like login in my example - it only ever handles
"GET /login", so it doesn't need anything else).

Hope that helps!

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


Re: python: server is not receiving input from client flask

2021-06-28 Thread Jerry Thefilmmaker
On Monday, June 28, 2021 at 2:41:23 PM UTC-4, Chris Angelico wrote:
> On Tue, Jun 29, 2021 at 4:36 AM Jerry Thefilmmaker 
>  wrote: 
> > @app.route("/", methods = ['POST', 'GET']) 
> > def play(): 
> >
> > @app.route("/", methods = ['POST', 'GET']) 
> > def check_answer(ans, user):
> When you're building a Flask app, you're defining a bunch of functions 
> that get called when particular requests come in. There needs to be 
> exactly *one* function for any given request. I would actually 
> recommend making the GET and POST endpoints completely separate here, 
> and designing them in independent functions. 
> 
> One extremely helpful technique here: "If In Doubt, Print It Out". 
> Event-driven code can be hard to debug, so don't be afraid to make 
> extensive use of print() calls to examine various aspects of the 
> incoming request. Even just a simple thing like print("check_answer 
> called") can tell you all kinds of things. 
> 
> HTTP is stateless by nature. You will have to think about each request 
> independently, and figure out how to carry the information you need. 
> Play around with it, have fun, and see what you can learn! 
> 
> ChrisA

Do you mind elaborating a bit more on making one function for any given request?

As far as defining a bunch of functions that get called when particular 
requests come in I thought that's what I had going on in my codes. No? 

Also thank you, on making use of the print statement. Thought once I crossed 
over to the web side there was no more need for it. But what you said makes 
sense in terms of debugging, because sometimes I couldn't tell whether the 
client's variable was getting pass to my function which caused it not to be 
triggered.

Thank you!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: python: server is not receiving input from client flask

2021-06-28 Thread Chris Angelico
On Tue, Jun 29, 2021 at 4:36 AM Jerry Thefilmmaker
 wrote:
> @app.route("/", methods = ['POST', 'GET'])
> def play():
>
> @app.route("/", methods = ['POST', 'GET'])
> def check_answer(ans, user):

When you're building a Flask app, you're defining a bunch of functions
that get called when particular requests come in. There needs to be
exactly *one* function for any given request. I would actually
recommend making the GET and POST endpoints completely separate here,
and designing them in independent functions.

One extremely helpful technique here: "If In Doubt, Print It Out".
Event-driven code can be hard to debug, so don't be afraid to make
extensive use of print() calls to examine various aspects of the
incoming request. Even just a simple thing like print("check_answer
called") can tell you all kinds of things.

HTTP is stateless by nature. You will have to think about each request
independently, and figure out how to carry the information you need.
Play around with it, have fun, and see what you can learn!

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


python: server is not receiving input from client flask

2021-06-28 Thread Jerry Thefilmmaker
I am new at python but newer at flask, and I'm trying to deploy a web app where 
I:
1. Send the user the question
2. Get the answer from the user
3. Send additional information based on the answer

I am able to send the question but stuck at getting the answer from the user. 
Base on the answer from the user the server returns a specific answer from a 
list of dict.

Here's my html:




THE QUIZ



QUIZ GAME


Welcome


Would you like to play


Enter your answer: 
 





Here's my python code:
@app.route("/", methods = ['POST', 'GET']) 
def play():

qa = questions.qa #list of dict with questions
user1, user2 = [], [] #containers for each player's answers

if request.method == 'POST':
answers = request.form.get('answers')
random.shuffle(questions.qa)
response = quiz(qa, user1)

return response 

def quiz(qa, user):
for rand_q in qa:

i = rand_q['question']
i2 = check_answer(i, user)

#print(rand_q["question"])
return i2

@app.route("/", methods = ['POST', 'GET'])
def check_answer(ans, user):
if request.method == 'POST':
answers = request.form.get('answers')
if 'yes' in answers:
user.append('yes')
i3 = ans.get(answers, '')#if the client answers "yes" to the 
question this part iterates over the part corresponds to yes in the list of dict

return i3 #this should send 2nd part of question/rand_q

Can anyone help me see what I'm doing wrong, and how do I pass the 2nd answer 
from my list of dict to the client. Thanks!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: setting user input equal to target language in Google Translator

2021-04-16 Thread Peter Otten

On 16/04/2021 19:11, Quentin Bock wrote:

is it possible to set the target language of a translation to be the input
from a user?
I have tried inputting specific abbreviations that would normally be
accepted as the target language but it remains in Icelandic and I would
like to change the target language based on the user's input without
creating hundred of scenarios for each inputted language or country.
Thanks


Hi, Quentin!

When you ask a question it is best to give the code you have. For
beginner problems you may even get a hint from people who haven't used
the library in question. That said, I have just installed googletrans,
and changing the destination language appears to be as easy as

>>> import googletrans as gt
>>> t = gt.Translator()
>>> for language in ["de", "fr", "es"]:
... print(t.translate("Hello, world!", dest=language).text)
...
Hallo Welt!
Bonjour le monde!
¡Hola Mundo!

Does that help?
--
https://mail.python.org/mailman/listinfo/python-list


setting user input equal to target language in Google Translator

2021-04-16 Thread Quentin Bock
is it possible to set the target language of a translation to be the input
from a user?
I have tried inputting specific abbreviations that would normally be
accepted as the target language but it remains in Icelandic and I would
like to change the target language based on the user's input without
creating hundred of scenarios for each inputted language or country.
Thanks
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: A beginning beginner's question about input, output and . . .

2021-01-16 Thread Terry Reedy

On 1/16/2021 9:17 PM, 2qdxy4rzwzuui...@potatochowder.com wrote:


A bare minimum skeleton might look something like this:

 with open(filename) as f:
 for line in f.readlines():
 handle_one_line(f)


f.readlines() reads the entire file into a list of lines (strings).  If 
you do not need that,

for line in f:
is sufficient for iterating thru the file line by line.

--
Terry Jan Reedy

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


Re: A beginning beginner's question about input, output and . . .

2021-01-16 Thread 2QdxY4RzWzUUiLuE
On 2021-01-16 at 17:46:13 -0500,
DonK  wrote:

> On Sat, 16 Jan 2021 14:56:37 -0600, 2qdxy4rzwzuui...@potatochowder.com
> wrote:
> 
> >On 2021-01-16 at 15:42:44 -0500,
> >DonK  wrote:

> >> For example, I've found a need to parse text documents quite a number
> >> of times over the years. Basic/VB is great at doing that. How's
> >> Python?
> 
> >
> >Python can do that.  Can you expand on "parse" and "text documents"?
> 
> There's nothing that I have any particular need for at the moment but
> it is something that I've done a number of times over the years. I
> think it's a common need?? 

Indeed.  :-)  In my experience, "parse" and "text documents" often mean
different things to different people.

> I've used Pascal and BASIC\VB for string parsing and BASIC\VB is much
> better. VB has all the string handling functions that you need built
> in but, for example, Pascal has some but you have to create others to
> be useful. Since I'm just beginning with Python I have no knowledge or
> criticism of how Python does this but I'm sure that it can.
> 
> Since I've retired I've written parsers for my bank records, medical
> records and other personally useful things. I would categorize them as
> trivial but useful.  i.e utility means useful
> 
> When I was working, in the 1999-2001 range, I wrote a parser in VB
> that unscrambled corrupted "batch files" for credit card processing so
> that vendors didn't have to spend hours rebuilding them by hand. Some
> of those files had over 700 credit card transactions in them. That's
> one example.

Sounds like you're parsing files composed of lines of plain text where
each line represents some kind of record (as opposed to parsing a
document containing programming code as a precursor to generating an
executable, or looking through a word processing document for something
important).

A bare minimum skeleton might look something like this:

with open(filename) as f:
for line in f.readlines():
    handle_one_line(f)

Python has a capable string type for handling text; see
<https://docs.python.org/3/library/string.html>.

Or look into the fileinput module for a convenient way to run through a
collection of files and/or standard input.

> I'm looking forward to learning some Python, mostly for fun, but I'm
> sure that it will also be useful.

Absolutely!  :-)

Happy Hacking!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: A beginning beginner's question about input, output and . . .

2021-01-16 Thread DonK
On Sat, 16 Jan 2021 14:56:37 -0600, 2qdxy4rzwzuui...@potatochowder.com
wrote:

>On 2021-01-16 at 15:42:44 -0500,
>DonK  wrote:
>
>> Yes, Windows. Iterating open windows with the Window's API is easy the
>> hard (very hard) part is sending keystrokes to those windows to Save
>> them. It's very tricky because the timing is critical. 
>> 
>> You have to use one of those "spy" utilities to get the name and
>> classid for the controls that you want to send a command to, then use
>> the Window's API functions SendMessage or PostMessage to send the
>> message directly to the control or just put it in the message que.
>>  
>> Like sending an "s" to the File menu to (S)ave. It's more complicated
>> than you would think and it doesn't work very well. It's like pushing
>> on a string. 
>
>Then don't do that?  ;-)
>
>I'm no Windows expert (nor even a user), but do those applications have
>a scripting interface?  (DDE?  OLE?  COM?  Do those letters ring a bell?
>The right bell?  Are those technologies current?)  What you're trying to
>do sounds like working *against* those applications rather than with
>them.

No! I've used the interfaces that you mentioned (OLE and COM in
particular) but that was for apps that I, or my colleagues, wrote (for
an employer) "to expose their guts" many years ago. I've found few
general use Windows apps that support any form of scripting. MS Office
apps, famously, support OLE. Or they used to. My copy of Office is
2007 so I don't know about the newer versions. I think most of those
technologies might have died a long time ago but I could be entirely
wrong. Does Python use those methods to control Excel, etc??

There was a Windows Usenet app, that I was interested in, around 10,
maybe 20 years ago that exposed a Pascal language like interface but
there was no documentation and no support. I believe it only lasted a
short time. I'm pretty sure that it's name started with a "D". It
doesn't matter.

I tried the method that I described above with the Forte Agent
newsreader back in the dial-up days because people in one of the
programming newsgroups wanted to be able to upload/dowanload
(unattended) in the middle of the night. It might have been possible
to get it to work reliably but I gave up on it.

>
>> For example, I've found a need to parse text documents quite a number
>> of times over the years. Basic/VB is great at doing that. How's
>> Python?

>
>Python can do that.  Can you expand on "parse" and "text documents"?

There's nothing that I have any particular need for at the moment but
it is something that I've done a number of times over the years. I
think it's a common need?? 

I've used Pascal and BASIC\VB for string parsing and BASIC\VB is much
better. VB has all the string handling functions that you need built
in but, for example, Pascal has some but you have to create others to
be useful. Since I'm just beginning with Python I have no knowledge or
criticism of how Python does this but I'm sure that it can.

Since I've retired I've written parsers for my bank records, medical
records and other personally useful things. I would categorize them as
trivial but useful.  i.e utility means useful

When I was working, in the 1999-2001 range, I wrote a parser in VB
that unscrambled corrupted "batch files" for credit card processing so
that vendors didn't have to spend hours rebuilding them by hand. Some
of those files had over 700 credit card transactions in them. That's
one example.

I'm looking forward to learning some Python, mostly for fun, but I'm
sure that it will also be useful.


Thank you

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


Re: A beginning beginner's question about input, output and . . .

2021-01-16 Thread DonK
On Tue, 12 Jan 2021 10:16:47 +0400, Abdur-Rahmaan Janhangeer
 wrote:

>Greetings,
>
>Web with Python is really easy to get started with, here
>is a simple endpoint with a framework called Flask
>
>from flask import Flask
>app = Flask(__name__)
>
>@app.route('/')
>def hello_world():
>   return 'Hello World’
>
>if __name__ == '__main__':
>   app.run()
>
>As for Tkinter, it's really annoying.
>PyQt5 and others are a lot better.
>PyQt5 follows the Cpp function namings
>
>Kind Regards,
>
>Abdur-Rahmaan Janhangeer

Someone else also suggested a web interface for i/o. If I get that far
it seems like it will be something I'll need to take a look at.

A lot of my early programming was command line BASIC apps running on
MSDOS. Even some pretty BIG stuff. So, going back to that after 40+
years seems a little weird. :-)

I looked at some Youtube videos about creating mobile apps with Java
but that just didn't do it for me. As far as I've seen there isn't
really a way to do the small "ad hoc" type of utilities on a
smartphone that you can do on a desktop machine.

Don't get me wrong, I love my smartphone.  

Thanks, 

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


Re: A beginning beginner's question about input, output and . . .

2021-01-16 Thread 2QdxY4RzWzUUiLuE
On 2021-01-16 at 15:42:44 -0500,
DonK  wrote:

> Yes, Windows. Iterating open windows with the Window's API is easy the
> hard (very hard) part is sending keystrokes to those windows to Save
> them. It's very tricky because the timing is critical. 
> 
> You have to use one of those "spy" utilities to get the name and
> classid for the controls that you want to send a command to, then use
> the Window's API functions SendMessage or PostMessage to send the
> message directly to the control or just put it in the message que.
>  
> Like sending an "s" to the File menu to (S)ave. It's more complicated
> than you would think and it doesn't work very well. It's like pushing
> on a string. 

Then don't do that?  ;-)

I'm no Windows expert (nor even a user), but do those applications have
a scripting interface?  (DDE?  OLE?  COM?  Do those letters ring a bell?
The right bell?  Are those technologies current?)  What you're trying to
do sounds like working *against* those applications rather than with
them.

> For example, I've found a need to parse text documents quite a number
> of times over the years. Basic/VB is great at doing that. How's
> Python?

Python can do that.  Can you expand on "parse" and "text documents"?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: A beginning beginner's question about input, output and . . .

2021-01-16 Thread DonK
On Mon, 11 Jan 2021 21:56:48 -0800, Paul Rubin
 wrote:

>DonK  writes:
>> My problem is that I don't understand how Python programs are
>> used. (i.e user input and output) Is Python mainly used for backends?
>> I've seen some Python gui frameworks like Tkinter, PyQt, etc
>
>I would say at least for me, the i/o to my python programs tends to be
>be either files or network sockets.  I've written some fairly complex
>tkinter apps in the past, but these days, desktop GUI's almost seem like
>a 1990s thing.  If you want an interactive program, either it's a mobile
>app (Python is not so great at that, though see kivy.org) or a web app
>(so the user interacts with it through a browser).
>
>> So, what do you folks use Python for?
>
>Pretty much everything unless a) it's someone else's application written
>in another language so I have to use the other language; b) I need raw
>performance (C, C++) or some other specialized feature; or c) I want to
>get more practice with some other language (quite a few).
>
>> if the titlebar contains certain strings
>
>Yeah this sounds like a Windows thing.  I don't have any idea what it
>takes to make those Windows calls in Python since I'm mostly a Un*x
>programmer.

Yes, Windows. Iterating open windows with the Window's API is easy the
hard (very hard) part is sending keystrokes to those windows to Save
them. It's very tricky because the timing is critical. 

You have to use one of those "spy" utilities to get the name and
classid for the controls that you want to send a command to, then use
the Window's API functions SendMessage or PostMessage to send the
message directly to the control or just put it in the message que.
 
Like sending an "s" to the File menu to (S)ave. It's more complicated
than you would think and it doesn't work very well. It's like pushing
on a string. 


>
>> I know that Python is a very popular language so I'm sorry if it
>> sounds like I'm being critical. I really don't know enough about it to
>> be critical.
>
>If you're familiar with Javascript or Visual Basic, my impression is
>that Python is at about the same level, but with a (for me) subjectively
>cleaner style.  It doesn't have a static type system or a lot of
>boilerplate, so it's easy to bang out small scripts; but the compiler
>doesn't supply much long range error checking, so you have to be pretty
>devoted to test automation if you're doing anything sizeable.  There is
>now a syntax for optional type annotations in Python, and a tool called
>mypy for checking types based on the annotations.  The Python compiler
>itself ignores the annotations.  I've been using them and like them.


Hi Paul,

I doubt that I'll be doing anything sizeable, mostly just a little
learning and entertainment with an occasional small utility once in a
while. But, who knows?

For example, I've found a need to parse text documents quite a number
of times over the years. Basic/VB is great at doing that. How's
Python?


Thanks,

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


Re: A beginning beginner's question about input, output and . . .

2021-01-16 Thread DonK
On Tue, 12 Jan 2021 09:26:18 +1100, Chris Angelico 
wrote:

>On Tue, Jan 12, 2021 at 7:41 AM DonK  wrote:
>> Hi, I'm thinking about learning Python but I'm 74 years old and will
>> very likely not ever have a programming job again. I used to program
>> in Visual Basic, C\C++, Delphi, etc. and some obscure "mainframe"
>> languages.
>
>BTW, from my experience, there's very very few languages so obscure
>that not one person on this list has heard of them :)
>
>For example, I've used REXX, which is an IBM language found on some of
>the mainframes and also on OS/2, and I'm not the only person here who
>has.
>
>ChrisA

Hi Chris,

The mainframe language that I mentioned was/is? called KwikBasic. I
don't remember if it was all one word or not. It's not to be confused
with Microsoft's QuickBasic.

KwikBasic ran on the Unix OS and was, hands down, the worst
programming experience I've ever had. It was a Y2k fix for the
reservation system of a large Fortune 500 real estate "timeshare"
company. I probably shouldn't say that their name was Trendswest.

The update had to be completed by the end of October 1998 because they
would start taking reservations for 2000 in Nov, 1998. They hired me
to manage the "reservation" part of their Y2k update in the Summer.
(YES! It was late.)

It turned out that KwikBasic was VERY much like the other versions of
basic that I had used. Including MSDOS's QuickBasic and PDS. The two
nutty things about it were that it had only 2 data types, if I
remember corectly they were called number and string.

The worst thing was that there was just one directory that contained
2,702 source files (I'll never forget that number) with names like
217h9436. There was no index to tell you what 217h9436 was, what it
did, what part of the business it pertained to . . . nothing. There
was also no notation in the files. You just had to open each one of
them, read their code to find out what they did.

Also, we had Windows computers on our desks with MS Office installed
but the nearest computer that could run Kwikbasic was their UNIX
mainframe in the main buildings about .25 to .50 miles away. We were
supposed to write code at our desk with Windows Notepad and then, on
Fridays,  the IT manager would take our code over to compile it and
would let us know of any error codes. They said they were going to buy
some expensive workstation for our office, that would run RedHat,
which they were told would then run Kwikbasic. IDunno!

It would have been impossible to do the job as the IT mgr (Mike W.)
envisioned it but I was able to write some simple MS Office code that
searched all the source code files, in just a minute or 2, for any
reference to "Date" functions. As I recall, there weren't that many.

Anyway, Mike W. was a fool that spent all day, every day, screaming
about, mostly, politics. I wound up quitting iafter less than 2 weeks.

Thanks for replying and sorry for the long message.

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


Re: conceptual problem (was: A beginning beginner's question about input, output and . . .

2021-01-14 Thread Greg Ewing

On 14/01/21 11:49 am, Cameron Simpson wrote:

The "pure" OOP approach, where method calls are used as messages to set
or fetch aspects of the object, is usually does with getter and setter
methods like:

 x = o.getX()
 o.setX(9)


People use get and set methods, not because it's somehow morally
wrong to expose attributes directly, but as a workaround for the
lack of a language feature.

In C++ and Java, different calling syntax is required for direct
access and access mediated by methods, so if you start out exposing
something directly and then change your mind, all the code using it
has to be changed. For this reason, people got into the habit of
wrapping everything in get and set methods from the beginning,
"just in case".

Python doesn't have this problem -- you can turn an attribute
into a property at any time, and nothing else needs to change.
So get and set methods are unnecessary and actively discouraged
in Python.

(C#, if I understand correctly, gets this sort of half-right.
You can turn an attribute into a property, and the calling *source*
doesn't change, but it all has to be recompiled -- which kind of
defeats the purpose.)

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


Re: A beginning beginner's question about input, output and . . .

2021-01-14 Thread Peter Pearson
On Wed, 13 Jan 2021 21:46:08 - (UTC), Grant Edwards wrote:
> On 2021-01-13, Peter Pearson  wrote:
[snip]
>> Browsergui is not widely popular (I don't think anybody but me has
>> mentioned it on this newsgroup), but it was written to be simple and
>> Pythonic, and has served me well.  Browsergui just uses your browser as
>> its user interface.  Grab it from
>>
>> https://github.com/speezepearson/browsergui
>
> I've been browsing through to documentation and examples, and I don't
> see any way to do any sort of modern flexible layout (e.g. nesting
> horizontal and vertical flexboxes) where you can control which
> elements grow/shrink when the window size changes.
>
> Is there a way to span columns/rows in a grid or control which columns
> grow/shrink?
>
> Have I missed something?

I doubt you've missed anything important, though I'm not sure because
I haven't done any of the things you mention.  Browsergui is minimalist.
If you've done the "python -m browsergui.examples" and don't see 
something like what you want, it's probably not there.

I like Browsergui for simple tools that require a little more
interaction than straight command-line utilities: exploring the effect
of various value-settings on some curve on a graph, or exploring the
ranges of values in a CSV file, or (most recently) rearranging the
order of image files in a list.

-- 
To email me, substitute nowhere->runbox, invalid->com.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: A beginning beginner's question about input, output and . . .

2021-01-13 Thread Greg Ewing

On 14/01/21 11:09 am, Grant Edwards wrote:

Perhaps I need to recalibrate my adjectives, but with
256KB+ of flash and 32KB+ of RAM, I wouldn't call them "small"


It's small by today's standards, when you consider that
multiple GB of RAM is commonplace now in most "real" computers.

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


Re: A beginning beginner's question about input, output and . . .

2021-01-13 Thread Greg Ewing

On 13/01/21 7:57 pm, Christian Gollwitzer wrote:

  What do you mean, "until" ?

https://medium.com/@yon.goldschmidt/running-python-in-the-linux-kernel-7cbcbd44503c 


He's using Micropython. That's cheating! :-)

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


Re: FridayFinking - Was: A beginning beginner's question about input, output and . . .

2021-01-13 Thread Rich Shepard

On Thu, 14 Jan 2021, dn via Python-list wrote:


Concerning the definition of "old"
- when I'm having a 'good day', it's anyone several years my senior (and
above)
- when I'm creaking and groaning, it's anyone remotely my age, and older.


About 45 years ago a 25-year-older friend of mine offered a great philosophy
of life. "We can do nothing about growing older," she told me, "but we can
do everything about growing old."

How true.

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


Re: A beginning beginner's question about input, output and . . .

2021-01-13 Thread Grant Edwards
On 2021-01-13, Peter Pearson  wrote:
> On Mon, 11 Jan 2021 15:37:58 -0500, DonK  
> wrote:
> [snip]
>>
>> I've seen some Python gui frameworks like Tkinter, PyQt, etc. but they
>> look kinda like adding a family room onto a 1986 double wide mobile
>> home, 
>
> Agreed.
>
> Browsergui is not widely popular (I don't think anybody but me has
> mentioned it on this newsgroup), but it was written to be simple and
> Pythonic, and has served me well.  Browsergui just uses your browser as
> its user interface.  Grab it from
>
> https://github.com/speezepearson/browsergui

I've been browsing through to documentation and examples, and I don't
see any way to do any sort of modern flexible layout (e.g. nesting
horizontal and vertical flexboxes) where you can control which
elements grow/shrink when the window size changes.

Is there a way to span columns/rows in a grid or control which columns
grow/shrink?

Have I missed something?

--
Grant


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


Re: A beginning beginner's question about input, output and . . .

2021-01-13 Thread Grant Edwards
On 2021-01-13, Dennis Lee Bieber  wrote:
> On Tue, 12 Jan 2021 15:18:05 - (UTC), Grant Edwards
> declaimed the following:
>>On 2021-01-12, songbird  wrote:
>>
>>> it can be used for pretty much anything except perhaps high
>>> pressure real time things, but i bet someone else will know that
>>> is being done too, i've just not heard of it.  :)
>>
>>AFAIK, Python can't be used to write device drivers for any popular OS
>>(Linux, Unix, Windows, OSX). It also can't be used on small embedded
>>systems (real-time or not).
>
>   MicroPython/Circuit Python. Native language for AdaFruit's Metro
> boards.

Those are very cool, and I've come this -><- close to ordering one in
the past.  Perhaps I need to recalibrate my adjectives, but with
256KB+ of flash and 32KB+ of RAM, I wouldn't call them "small" -- even
though the Trinket M0 is physically tiny. But that may just be my age
showing. I remember not _that_ long ago working on processors where
the RAM was measured in hundreds of bytes. And I still maintain code
for ARM parts with way less than 1/10 the memory of the Trinket M0.

--
Grant



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


FridayFinking - Was: A beginning beginner's question about input, output and . . .

2021-01-13 Thread dn via Python-list
On 14/01/2021 04.54, Grimble wrote:
> On 11/01/2021 20:37, DonK wrote:
>>
>> Hi, I'm thinking about learning Python but I'm 74 years old and will
>> very likely not ever have a programming job again. 

> At 83, I have no intention of having a programming job again! I last
> coded something professionally 45 years ago, but it hasn't lost its
> attraction.

Hey, some 'silver surfers' who have a few years on me!

Concerning the definition of "old"
- when I'm having a 'good day', it's anyone several years my senior (and
above)
- when I'm creaking and groaning, it's anyone remotely my age, and older.


Of course, many of my colleagues have fairly similar understandings -
for them anyone with the digit "3" (or greater) at the front of their
age, is not so much old (saying that would be rude!), but "ancient"!


That said, such young-bucks wrestling with cloud-concepts today, were
totally nonplussed when I told them how (mainframe) computer bureaux
used to work. The 'mechanics' may be different, but the management is
little-changed!


...

> I find this a fascinating news group - shame there's been no updates to
> Friday Finking recently!


With all due apologies!

I work(ed) with a particular team in a mentoring rôle, handling reviews,
walk-throughs, some design meetings, Python version-upgrades coaching,
etc. One of these was a 'morning tea' meeting, when we would
discuss/debate/argue 'Python best practice' topics, either raised by
members or that arose from other meetings but were best not discussed
there-and-then.

If there was an interesting topic, or one that 'we' hadn't really
settled satisfactorily within the group, I would try to re-frame the
discussion, and consult 'the oracles' here. So, that's the raison d'être
and motivation of the "Friday Finking" series..


Then along came COVID-19, and although this country's response was
amongst the best in the world, the team (and its routines) all-but
fell-apart. Firstly, we had to adjust to working remotely. The effort
that went into 'Friday Finking' was quickly absorbed into figuring-out
remote-techniques and maintaining the social component of the team's
success. Then a bunch of us were 'released to other duties' and
landed-in high-pressure projects to do with modelling pandemic
response-options. Various other interventions, life moved-on, etc, etc -
stories familiar to most, I'm sure.


So, thank you for the gentle reminder. Even though that team is still
not meeting as it once did, there's plenty of other 'inspiration', eg a
parallel discussion 'here' about the virtues of a programmer positioning
dialog(ue)s/windows or leaving it to the window manager...


I'll give it some thought - as long as Fridays keep coming!
-- 
Regards =dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: conceptual problem (was: A beginning beginner's question about input, output and . . .

2021-01-13 Thread Cameron Simpson
On 13Jan2021 10:37, songbird  wrote:
>  my momentary conceptual problem is that to me OOP means
>being able to encapsulate data structures and code from
>other parts of the program, but to me it doesn't look like
>that is how python is designed.  this is probably a complete
>aside to this whole thread and perhaps even this newsgroup
>so i'll subthread this.

Python allows you to avoid mucking with the object internals from 
outside. But it doesn't prevent it.

So you can (and often should) adopt an OOP approach - it reduces the 
dependencies between your classes, with the benefits that brings.

The "pure" OOP approach, where method calls are used as messages to set 
or fetch aspects of the object, is usually does with getter and setter 
methods like:

x = o.getX()
o.setX(9)

In Python this is less common. Simple things like that which do not 
intrude much on the conceptual model (i.e. if all such things will have 
an "X") are usually exposed as a public attribute which you can get or 
set directly:

x = o.x
o.x = 9

"Public" attributes in Python are just a convention: we name "private" 
attributes with a leading underscore and "public" attributes with 
leading letters and expect people using our classes to behave well.

Sometime we _don't_ have a plain old attribute "x", but we do have a 
property of the object looking like it. Then you can implement something 
which looks like an attribute from outside:

@property
def x(self):
# "x" if a derived value
return self._a + self._b

@x.setter
def x(self, new_x):
# setting "x" gets split between _a and _b
x2 = x / 3
self._a = x2# put some in _a
self._b = x - x2# put the rest in _b

# you can still do this, but it calls methods now
x = o.x
o.x = 9

So Python supports OOP practices but doesn't enforce them. Adopt the 
degree of discipline you think best.

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


Re: A beginning beginner's question about input, output and . . .

2021-01-13 Thread Peter Pearson
On Mon, 11 Jan 2021 15:37:58 -0500, DonK  wrote:
[snip]
>
> I've seen some Python gui frameworks like Tkinter, PyQt, etc. but they
> look kinda like adding a family room onto a 1986 double wide mobile
> home, 

Agreed.

Browsergui is not widely popular (I don't think anybody but me has
mentioned it on this newsgroup), but it was written to be simple and
Pythonic, and has served me well.  Browsergui just uses your browser as
its user interface.  Grab it from

https://github.com/speezepearson/browsergui

then run "python -m browsergui.examples".

(Disclaimer/boast: I'm related to Browsergui's author.)

-- 
To email me, substitute nowhere->runbox, invalid->com.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: A beginning beginner's question about input, output and . . .

2021-01-13 Thread songbird
Christian Gollwitzer wrote:
> Am 13.01.21 um 06:24 schrieb Greg Ewing:
>> On 13/01/21 4:18 am, Grant Edwards wrote:
>> 
>>> AFAIK, Python can't be used to write device drivers for any popular OS
>> 
>> At least not until some crazy person embeds Python in the
>> Linux kernel...
>
>
>   What do you mean, "until" ?
>
> https://medium.com/@yon.goldschmidt/running-python-in-the-linux-kernel-7cbcbd44503c
>
> http://www.kplugs.org/

  yes!  haha!  :)  love it!  wish i had time to play now.


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


Re: A beginning beginner's question about input, output and . . .

2021-01-13 Thread Grimble

On 11/01/2021 20:37, DonK wrote:


Hi, I'm thinking about learning Python but I'm 74 years old and will
very likely not ever have a programming job again. 
At 83, I have no intention of having a programming job again! I last 
coded something professionally 45 years ago, but it hasn't lost its 
attraction.

So, what do you folks use Python for?

I have several scripts to help with activities for the charity that 
keeps me occupied. I've written a shopping list script with 
auto-completion and a couple of web-scraping applications that support a 
weather reporting application interfacing with various 1Wire sensors 
transcribed from an initial Ruby application. My largest GUI application 
is a database of personal contacts with input and output of data via 
vCards and .csv files (with a lot of mentoring from an American Gtk user!)
I find this a fascinating news group - shame there's been no updates to 
Friday Finking recently!


--
Grimble
Registered Linux User #450547
Machine 'Bach' running Plasma 5.15.4 on 5.7.19-desktop-3.mga7 kernel.
Mageia release 7 (Official) for x86_64


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


conceptual problem (was: A beginning beginner's question about input, output and . . .

2021-01-13 Thread songbird
Chris Angelico wrote:
...projects that fade...
> That's not really something Python can ever control, but I can say
> with some confidence that the big libraries like Qt and GTK are going
> to adapt, one way or another. And perhaps more importantly: Neither
> input()/print() nor web applications is going *anywhere*. You are
> ALWAYS going to have those two as options.

  :)  i hope so. :)

  at the moment i've only done things with GTK and pyglet.
since i am way too new at python i can't say the code is
pretty, but it does work.

  my momentary conceptual problem is that to me OOP means
being able to encapsulate data structures and code from
other parts of the program, but to me it doesn't look like
that is how python is designed.  this is probably a complete
aside to this whole thread and perhaps even this newsgroup
so i'll subthread this.


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


Re: A beginning beginner's question about input, output and . . .

2021-01-13 Thread Grimble

On 11/01/2021 20:37, DonK wrote:




So, what do you folks use Python for?


I've written a shopping list script with auto-completion and a couple of 
web-scraping applications that support a weather reporting application 
interfacing with various 1Wire sensors transcribed from an initial Ruby 
application. My largest GUI application is a database of personal 
contacts with input and output of data via vCards and .csv files (with a 
lot of mentoring from an American Gtk user!)
I find this a fascinating news group - shame there's been no updates to 
Friday Finking recently


--
Grimble
Registered Linux User #450547
Machine 'Bach' running Plasma 5.15.4 on 5.7.19-desktop-3.mga7 kernel.
Mageia release 7 (Official) for x86_64
--
https://mail.python.org/mailman/listinfo/python-list


Re: A beginning beginner's question about input, output and . . .

2021-01-12 Thread Christian Gollwitzer

Am 13.01.21 um 06:24 schrieb Greg Ewing:

On 13/01/21 4:18 am, Grant Edwards wrote:


AFAIK, Python can't be used to write device drivers for any popular OS


At least not until some crazy person embeds Python in the
Linux kernel...



 What do you mean, "until" ?

https://medium.com/@yon.goldschmidt/running-python-in-the-linux-kernel-7cbcbd44503c

http://www.kplugs.org/

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


Re: A beginning beginner's question about input, output and . . .

2021-01-12 Thread Greg Ewing

On 13/01/21 4:18 am, Grant Edwards wrote:


AFAIK, Python can't be used to write device drivers for any popular OS


At least not until some crazy person embeds Python in the
Linux kernel...

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


Re: A beginning beginner's question about input, output and . . .

2021-01-12 Thread Grant Edwards
On 2021-01-12, Chris Angelico  wrote:

> * Command-line calculator - pressing Ctrl-Alt-P will open up a
>   terminal with Python, and that's the normal way that I do quick
>   calculations

I do that a lot too.

--
Grant





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


Re: A beginning beginner's question about input, output and . . .

2021-01-12 Thread Cameron Simpson
On 12Jan2021 10:40, Michael F. Stemper  wrote:
>On 11/01/2021 14.37, DonK wrote:
>>I've installed Python 3.7, the PyCharm IDE and watched some Youtube
>>tutorials
>
>I would suggest that instead of watching tutorials, you open up your IDE
>and start writing stuff.

I would second that. Maybe this is a congnitive shortcoming on my part, 
but I find videos not useful for learning new programming. What they are 
great for is seeing explicit examples of something you are doing, 
particular if you hit some block and need to see someone _do_ what 
you're failing to do.

They're great for physical repair though, which again is an explicit 
example of a particular fixed task. Repaired our stand mixer with 
reference to a good video. Would not want to use a video to learn the 
theory of stand mixer design.

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


Re: A beginning beginner's question about input, output and . . .

2021-01-12 Thread Cameron Simpson
On 12Jan2021 15:18, Grant Edwards  wrote:
>On 2021-01-12, songbird  wrote:
>>   it can be used for pretty much anything except perhaps
>> high pressure real time things, but i bet someone else will
>> know that is being done too, i've just not heard of it.  :)
>
>AFAIK, Python can't be used to write device drivers for any popular OS
>(Linux, Unix, Windows, OSX). It also can't be used on small embedded
>systems (real-time or not).

Well, yes and no. Not a pure device driver. But there are systems like 
FUSE for hooking kernel level filesystem stuff to an external system 
programme.  I've used the Python llfuse library to implement a 
filesystem in Python.

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


Re: A beginning beginner's question about input, output and . . .

2021-01-12 Thread Chris Angelico
On Tue, Jan 12, 2021 at 7:41 AM DonK  wrote:
> So, what do you folks use Python for?
>

Since everyone else is, I'll add my list.

* API lookups of various sorts (usually via HTTP requests)
* Audio analysis. Calculate the maximum and average volume of each of
many songs.
* Code generation. The audio analysis output is in the form of a Lua
script (a VLC extension); also I have Python scripts that generate
SourcePawn code for CS:GO integration, and various other things.
* Decoding and analyzing myriad formats of files, including
Borderlands save files (now which character had that level 62
legendary weapon I wanted...)
* Mathematical analysis and testing. Python has excellent arithmetical
and higher mathematical tools.
* Automated tidying up of files to eliminate spurious diffs (eg with
OBS Studio's config files)
* Web apps involving PostgreSQL databases, various API calls, etc, etc
* Financial calculations - parse the downloaded transactions files
from my bank, correlate with my client list, automatically mark
invoices as paid
* Command-line calculator - pressing Ctrl-Alt-P will open up a
terminal with Python, and that's the normal way that I do quick
calculations
* And a ton of quick one-off scripts for a wide variety of jobs.

Python's one of my favourite languages, and I use it a lot :)

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


Re: A beginning beginner's question about input, output and . . .

2021-01-12 Thread Grant Edwards
On 2021-01-12, Chris Angelico  wrote:
> On Wed, Jan 13, 2021 at 3:18 AM Grant Edwards  
> wrote:
>>
>> On 2021-01-12, songbird  wrote:
>>
>> >   it can be used for pretty much anything except perhaps
>> > high pressure real time things, but i bet someone else will
>> > know that is being done too, i've just not heard of it.  :)
>>
>> AFAIK, Python can't be used to write device drivers for any popular OS
>> (Linux, Unix, Windows, OSX). It also can't be used on small embedded
>> systems (real-time or not).
>
> Depends how small.

Of course.

> An RPi has a full Linux system and can easily run Python scripts;
> and the pyboard runs a dedicated Python interpreter called
> MicroPython, broadly compatible with CPython 3.5, I think (some 3.x
> version, anyhow), albeit with a cut-down standard library. The
> pyboard is pretty tiny; according to the micropython.org blurb, it
> has 192KB RAM.

Yes, that's tiny compared to the desktop machine I'm posting from, but
I work with ARM parts (that are in active production production and
not EOL) with 2KB of RAM and 8KB of flash.

--
Grant



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


Re: A beginning beginner's question about input, output and . . .

2021-01-12 Thread Michael F. Stemper

On 12/01/2021 10.40, Michael F. Stemper wrote:


Modeling of electric power systems:
- load behavior in response to conservation load reduction


Sorry, that should have been "conservation voltage reduction".


--
Michael F. Stemper
Psalm 82:1-4
--
https://mail.python.org/mailman/listinfo/python-list


Re: A beginning beginner's question about input, output and . . .

2021-01-12 Thread MRAB

On 2021-01-11 20:37, DonK wrote:



[snip]


So, what do you folks use Python for?


Since we're sharing:

- Personal information manager in the form of a tree of pages. Each page 
can have code associated with it which defines functions to call when 
shortcut keys are pressed, giving page-specific shortcuts for 
page-specific functionality.


- Simple money manager.

Both use tkinter.
--
https://mail.python.org/mailman/listinfo/python-list


Re: A beginning beginner's question about input, output and . . .

2021-01-12 Thread Michael F. Stemper

On 11/01/2021 14.37, DonK wrote:


I've installed Python 3.7, the PyCharm IDE and watched some Youtube
tutorials


I would suggest that instead of watching tutorials, you open up your IDE
and start writing stuff. Get an introductory python book (I used the
O'Reilly _Introducing Python_), start at the beginning, and type in each
example. Then, tweak it to see what happens.


I've seen some Python gui frameworks like Tkinter, PyQt, etc. but they
look kinda like adding a family room onto a 1986 double wide mobile
home, and they look even more complicated than creating a GUI from
scratch in C++ with a message loop, raising events . . .


I haven't really got my head around GUI programming myself. I tried to
write one with tkinter based on on-line examples, but didn't have any
conceptual framekwork, so it didn't work too well. I saw in a post here
that there are actually books on it, so I might pick one up and try
again.


So, what do you folks use Python for?


Since you asked:

Various command-line utilities, including:
- comparing the contents of two directories
- ad-hoc linear regression
- validation of DTDs
- sanity check of nesting symbols in TeX files
- ad-hoc plotting

Maintaining and querying of data bases:
- five-minute values of local temperatures
- Action items for an organization of which I'm secretary
- my own to-do list
- non-isomorphic groups that have isomorphic character tables

Modeling of electric power systems:
- load behavior in response to conservation load reduction
- generator and governor response to system load
- economic dispatch of generators, including those with non-monotonic 
incremental cost curves

(last two are very much works in progress)

Mathematics:
- experiments with number theory and combinatorics
- composition of permutations of a set
- properties of minimal paths through a C_m x C_n lattice
- generating tikz commands for geometric diagrams in TeX documents
- unstructured and uneducated exploration of Conway's Game of Life

--
Michael F. Stemper
2 Chronicles 19:7
--
https://mail.python.org/mailman/listinfo/python-list


Re: A beginning beginner's question about input, output and . . .

2021-01-12 Thread Chris Angelico
On Wed, Jan 13, 2021 at 3:18 AM Grant Edwards  wrote:
>
> On 2021-01-12, songbird  wrote:
>
> >   it can be used for pretty much anything except perhaps
> > high pressure real time things, but i bet someone else will
> > know that is being done too, i've just not heard of it.  :)
>
> AFAIK, Python can't be used to write device drivers for any popular OS
> (Linux, Unix, Windows, OSX). It also can't be used on small embedded
> systems (real-time or not).
>

Depends how small. An RPi has a full Linux system and can easily run
Python scripts; and the pyboard runs a dedicated Python interpreter
called MicroPython, broadly compatible with CPython 3.5, I think (some
3.x version, anyhow), albeit with a cut-down standard library. The
pyboard is pretty tiny; according to the micropython.org blurb, it has
192KB RAM.

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


Re: A beginning beginner's question about input, output and . . .

2021-01-12 Thread Grant Edwards
On 2021-01-12, songbird  wrote:

>   it can be used for pretty much anything except perhaps
> high pressure real time things, but i bet someone else will
> know that is being done too, i've just not heard of it.  :)

AFAIK, Python can't be used to write device drivers for any popular OS
(Linux, Unix, Windows, OSX). It also can't be used on small embedded
systems (real-time or not).

--
Grant



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


Re: A beginning beginner's question about input, output and . . .

2021-01-12 Thread Grant Edwards
On 2021-01-11, DonK  wrote:

> So, what do you folks use Python for?

I mainly use it for writing command-line utilities. Many of them work
on either Windows or Linux, but are mostly used on Linux:

 * Two-pass symbolic assembler and dissassembler for a proprietary
   communications controller.

 * Utilties to encrypt/decrypt files in proprietary formats.

 * Protocol dissector that prints the contents of network traffic for
   a couple different proprietary protocols.  It will parse a file
   saved with Wireshark/tcpdump or it will display live traffic using
   libpcap.

 * A utility to discover and manage a couple different families of
   industrial products (discovery, configiration) using a proprietary
   UDP protocol.

 * Utilities to program firmware into various products and
   microprocessors.

 * Utilities to perform various operations (e.g. run-length encoding)
   on things like FPGA bitstream files.

 * Utilities that implement various serial protocols for testing
   devices that use those protocols.

 * Scraping my favorite comic strips from various web sites and
   compiling them into a local web page.

 * Utilties for working with industrial control devices using
   DeviceNet on CAN bus.

 * An email gateway daemon that accepted SMTP mail and relayed it to MS
   Exchange using WebDAV.

 * An email gateway daemon that fetched email from MS Exchnage using
   Outlook/DCOM and relayed to an SMTP server.

 * Custom SMTP servers used to test SMTP clients.
 

I also wire the occasional GUI application:

 * A GTK "terminal" application that connects to a serial port.

 * A GTK IMAP mailbox notification app that monitors any number of
   IMAP mailboxes and notifies the user when there is new mail.

 * WxWindows and Tk applications to do various device management tasks
   for industrial equipment (update firmware, change configurations,
   etc.) via TCP and UDP network protocols.

 * WxWindows utilities for working with industrial control devices
   using DeviceNet on CAN bus.

I've also written web "backend" code that gathers and archives data
from my solar panels every 10 minutes and then produces graphs and
charts on demand for AJAX web applications.

Where I work we also use Python to run our production stations --
testing and programming circuit boards and assembled products.

There are also a couple commercial applicatoins I use daily (but
didn't write) that are written in Python:

 Hiri (email client)
 Plex (DVR and home theater application)


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


Re: A beginning beginner's question about input, output and . . .

2021-01-11 Thread Chris Angelico
On Tue, Jan 12, 2021 at 5:26 PM songbird  wrote:
>   for python i just spend too much time fumbling around
> and i don't really know what is current and if i'm using
> something that will be kept up for the future or if the
> project is going away or in a direction that i won't like
> (both KDE and Gnome desktops messed me up with what they
> did after i spent a lot of time finding them, getting
> them set up and then they changed and i switched only to
> have the other do the same to me so i switched again to
> Mate and that at least has been more stable to my style of
> doing things).

That's not really something Python can ever control, but I can say
with some confidence that the big libraries like Qt and GTK are going
to adapt, one way or another. And perhaps more importantly: Neither
input()/print() nor web applications is going *anywhere*. You are
ALWAYS going to have those two as options.

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


Re: A beginning beginner's question about input, output and . . .

2021-01-11 Thread songbird
DonK wrote:
>
> Hi, I'm thinking about learning Python but I'm 74 years old and will
> very likely not ever have a programming job again. I used to program
> in Visual Basic, C\C++, Delphi, etc. and some obscure "mainframe"
> languages. It's been about 18-19 years since my last programming job.
> I do understand programming concepts but I'm really not up on any of
> the more modern programming languages.

  hi Don,

  you sound like you have a similar perspective to my own
except i'm a bit younger.  :)


> I've installed Python 3.7, the PyCharm IDE and watched some Youtube
> tutorials but it's been stretched out over about 1.5 years so I'll
> probably need to go back to the beginning. My problem is that I don't
> understand how Python programs are used. (i.e user input and output)
> Is Python mainly used for backends?

  it can be used for pretty much anything except perhaps
high pressure real time things, but i bet someone else will
know that is being done too, i've just not heard of it.  :)


> I've seen some Python gui frameworks like Tkinter, PyQt, etc. but they
> look kinda like adding a family room onto a 1986 double wide mobile
> home, and they look even more complicated than creating a GUI from
> scratch in C++ with a message loop, raising events . . .

  i tried pyglet just because it was the first one that i
could figure out without it being too complicated.


> So, what do you folks use Python for?

  for me i used it to learn python and wrote a simple game
which adapted an already existing game written in C to python.
since i don't really understand python and have issues with
some concepts it hasn't gone much further lately and i'm
ok with that.


> Nowdays I mainly just use programming for rather small utilities for
> my personal use. Currently I'd like to write something to iterate
> through open windows and save them to different folders depending on
> if the titlebar contains certain strings. In the past I would probably
> have used Excel's VBA to do this but I no longer have Excel installed
> on my main computer. I'd like a bit of a challenge but I don't want to
> spin my wheels trying to learn something that will be a dead end for
> me.

  i am so familiar with Bash shell script language and C 
that either of those would normally be my first choice
because i already have tools done for enough things and
i know what i'm doing.

  for python i just spend too much time fumbling around
and i don't really know what is current and if i'm using
something that will be kept up for the future or if the
project is going away or in a direction that i won't like
(both KDE and Gnome desktops messed me up with what they
did after i spent a lot of time finding them, getting
them set up and then they changed and i switched only to
have the other do the same to me so i switched again to
Mate and that at least has been more stable to my style of
doing things).

  uh, so, i think i do understand your aims and perspective
and hope you can get further in your goals.  :)


> I know that this probably seems like a stupid post but your input will
> be useful.
>
> Thank you.
>
>Don
>
> I know that Python is a very popular language so I'm sorry if it
> sounds like I'm being critical. I really don't know enough about it to
> be critical.

  heh, well, if you go back and read some of my previous posts
here you'd see a lot of dumb things i've said too.  don't worry.
i'm sure i'll make other dumb posts too, but at the moment i'm
mostly in a holding pattern for a while.  i have a few other
big projects i need to finish before i get back to python again.


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


Re: A beginning beginner's question about input, output and . . .

2021-01-11 Thread Abdur-Rahmaan Janhangeer
Greetings,

Web with Python is really easy to get started with, here
is a simple endpoint with a framework called Flask

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
   return 'Hello World’

if __name__ == '__main__':
   app.run()

As for Tkinter, it's really annoying.
PyQt5 and others are a lot better.
PyQt5 follows the Cpp function namings

Kind Regards,

Abdur-Rahmaan Janhangeer
about <https://compileralchemy.github.io/> | blog
<https://www.pythonkitchen.com>
github <https://github.com/Abdur-RahmaanJ>
Mauritius


On Tue, Jan 12, 2021 at 12:43 AM DonK  wrote:

>
> Hi, I'm thinking about learning Python but I'm 74 years old and will
> very likely not ever have a programming job again. I used to program
> in Visual Basic, C\C++, Delphi, etc. and some obscure "mainframe"
> languages. It's been about 18-19 years since my last programming job.
> I do understand programming concepts but I'm really not up on any of
> the more modern programming languages.
>
> I've installed Python 3.7, the PyCharm IDE and watched some Youtube
> tutorials but it's been stretched out over about 1.5 years so I'll
> probably need to go back to the beginning. My problem is that I don't
> understand how Python programs are used. (i.e user input and output)
> Is Python mainly used for backends?
>
> I've seen some Python gui frameworks like Tkinter, PyQt, etc. but they
> look kinda like adding a family room onto a 1986 double wide mobile
> home, and they look even more complicated than creating a GUI from
> scratch in C++ with a message loop, raising events . . .
>
> So, what do you folks use Python for?
>
> Nowdays I mainly just use programming for rather small utilities for
> my personal use. Currently I'd like to write something to iterate
> through open windows and save them to different folders depending on
> if the titlebar contains certain strings. In the past I would probably
> have used Excel's VBA to do this but I no longer have Excel installed
> on my main computer. I'd like a bit of a challenge but I don't want to
> spin my wheels trying to learn something that will be a dead end for
> me.
>
> I know that this probably seems like a stupid post but your input will
> be useful.
>
> Thank you.
>
>Don
>
> I know that Python is a very popular language so I'm sorry if it
> sounds like I'm being critical. I really don't know enough about it to
> be critical.
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: A beginning beginner's question about input, output and . . .

2021-01-11 Thread Chris Angelico
On Tue, Jan 12, 2021 at 3:16 PM Greg Ewing  wrote:
> > Currently I'd like to write something to iterate
> > through open windows and save them to different folders depending on
> > if the titlebar contains certain strings.
>
> That sounds like it should be doable if you can get access to the
> right Windows API functions. Check out the pywin32 package. If that
> doesn't provide what you need, there's always ctypes (part of the
> standard python distribution, gives low-level access to C library
> functions).
>

Sounds like an awful lot of work. On Linux, I'd just subprocess out to
wmctrl and parse its output - way easier.

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


Re: A beginning beginner's question about input, output and . . .

2021-01-11 Thread Greg Ewing

On 12/01/21 9:37 am, DonK wrote:


I've seen some Python gui frameworks like Tkinter, PyQt, etc. but they
look kinda like adding a family room onto a 1986 double wide mobile
home, and they look even more complicated than creating a GUI from
scratch in C++ with a message loop, raising events . . .


I'm surprised you find any of those toolkits more complicated
to use than the raw Windows API, which last time I dabbled in it
seemed fairly horrendous.

Unfortunately there doesn't seem to be a really good way to
easily make GUIs in Python. I tried to fill that gap a few years
back with PyGUI:

https://www.cosc.canterbury.ac.nz/greg.ewing/python_gui/

You might like to check that out, but be warned that a few bits
of it are broken at the moment. It's badly in need of an overhaul,
and I don't have time to devote to it right now.


So, what do you folks use Python for?


Personal uses I can think of in recent times:

* Command line tools for various small tasks, often parts of
build systems for other projects.

* Games, using pygame, pyopengl, numpy and various other libraries.


Currently I'd like to write something to iterate
through open windows and save them to different folders depending on
if the titlebar contains certain strings.


That sounds like it should be doable if you can get access to the
right Windows API functions. Check out the pywin32 package. If that
doesn't provide what you need, there's always ctypes (part of the
standard python distribution, gives low-level access to C library
functions).

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


Re: A beginning beginner's question about input, output and . . .

2021-01-11 Thread Cameron Simpson
On 11Jan2021 15:52, Dan Stromberg  wrote:
>On Mon, Jan 11, 2021 at 2:22 PM Cameron Simpson  wrote:
>> >I've seen some Python gui frameworks like Tkinter, PyQt, etc. but 
>> >they
>> >look kinda like adding a family room onto a 1986 double wide mobile
>> >home, and they look even more complicated than creating a GUI from
>> >scratch in C++ with a message loop, raising events . . .
>>
>> They aren't really. I've not use Tkinter, but I have used PyQt.
>
>Maybe compared to Java or C# they are, which come with almost the only GUI
>toolkit that gets used.  But there's also a version of Qt for Java.  Not
>sure about C#.

Hmm, in the distant past I did write a small GUI app using Java. It was 
a little simpler than (current) Qt to my (fuzzy) recollection, but that 
might be partly because the toolkit itself was smaller. Unsure now.

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


Re: A beginning beginner's question about input, output and . . .

2021-01-11 Thread Dan Stromberg
On Mon, Jan 11, 2021 at 2:22 PM Cameron Simpson  wrote:

> >I've seen some Python gui frameworks like Tkinter, PyQt, etc. but they
> >look kinda like adding a family room onto a 1986 double wide mobile
> >home, and they look even more complicated than creating a GUI from
> >scratch in C++ with a message loop, raising events . . .
>
> They aren't really. I've not use Tkinter, but I have used PyQt.
>

Maybe compared to Java or C# they are, which come with almost the only GUI
toolkit that gets used.  But there's also a version of Qt for Java.  Not
sure about C#.

I've mostly used GTK for GUI's and a little Tkinter for turtle graphics,
both in Python.  Both felt natural.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: A beginning beginner's question about input, output and . . .

2021-01-11 Thread Chris Angelico
On Tue, Jan 12, 2021 at 7:41 AM DonK  wrote:
> Hi, I'm thinking about learning Python but I'm 74 years old and will
> very likely not ever have a programming job again. I used to program
> in Visual Basic, C\C++, Delphi, etc. and some obscure "mainframe"
> languages.

BTW, from my experience, there's very very few languages so obscure
that not one person on this list has heard of them :)

For example, I've used REXX, which is an IBM language found on some of
the mainframes and also on OS/2, and I'm not the only person here who
has.

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


Re: A beginning beginner's question about input, output and . . .

2021-01-11 Thread Cameron Simpson
On 11Jan2021 15:37, DonK  wrote:
>Hi, I'm thinking about learning Python but I'm 74 years old and will
>very likely not ever have a programming job again. I used to program
>in Visual Basic, C\C++, Delphi, etc. and some obscure "mainframe"
>languages.

Therefore you're happy with classes, and are presumably with a Windows 
background. (And, of course, the mainframe world.)

>I've installed Python 3.7, the PyCharm IDE and watched some Youtube
>tutorials but it's been stretched out over about 1.5 years so I'll
>probably need to go back to the beginning. My problem is that I don't
>understand how Python programs are used. (i.e user input and output)
>Is Python mainly used for backends?

My personal Python use is almost all backend, and on a personal basis I 
spend most of my time at a command prompt in a terminal window.

However, you can write fully fledged GUI applications in Python.

Without a GUI Python programmes tend to work off their input and write 
to their output (or other files) like any other command line programme.

Chris mentioned input() for reading input and print() for writing 
output. input() is an interactive function (it accepts a prompt string 
and reads a single line of text). If you're writing something batchy, 
which might be in a pipeline or reading from a text file, then the 
standard input is sys.stdin and can be read in various ways - when that 
is text the typical way is just to iterate over it in a for-loop, which 
gets your lines of text.

Trite example:

import sys


lineno = 0
for line in sys.stdin:
lineno += 1
print("line number", lineno, "text =", line)

>I've seen some Python gui frameworks like Tkinter, PyQt, etc. but they
>look kinda like adding a family room onto a 1986 double wide mobile
>home, and they look even more complicated than creating a GUI from
>scratch in C++ with a message loop, raising events . . .

They aren't really. I've not use Tkinter, but I have used PyQt. You 
still have the usual framework:

- contruct widgets (windows and other GUI elements) with the associated 
  code which runs when you interact with them

- an event loop (usually simply entered after constructing the main GUI 
  component(s)) - it will run until told to stop

- raising events - in PyQt these are called "signals" - you issue a 
  signel/event with whatever information it uses and the event loop runs 
  its handler in due course

Part of the difficulty with PyQt (for me) is that it is a Python shim 
onto a quite large C++ widget library. Most of the actual doco seems to 
be the C++ side, and you need to infer some stuff to use it from Python.  
The shim is very one-to-one, so that works pretty well.

I gather that Tkinter is easier to get off the ground with.

>So, what do you folks use Python for?

Personally, almost entirely command line stuff, and making 
libraries/modules/packages which implement what I need.

>Nowdays I mainly just use programming for rather small utilities for
>my personal use.

Me too.

>Currently I'd like to write something to iterate
>through open windows and save them to different folders depending on
>if the titlebar contains certain strings. In the past I would probably
>have used Excel's VBA to do this but I no longer have Excel installed
>on my main computer. I'd like a bit of a challenge but I don't want to
>spin my wheels trying to learn something that will be a dead end for
>me.

This requires Windows specific knowledge, which I lack. Saving to 
folders etc is standard stuff, but the "iterate through open windows" 
and consulting their titlebar strings is platform, and maybe app, 
specific. I'm not a Windows person, alas.

>I know that this probably seems like a stupid post but your input will
>be useful.

No, it's entirely reasonable. Getting off the ground with a 
useful-to-you task is always the first hurdle with a new language.

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


Re: A beginning beginner's question about input, output and . . .

2021-01-11 Thread dn via Python-list
On 12/01/2021 09.37, DonK wrote:
> 
> Hi, I'm thinking about learning Python but I'm 74 years old and will
> very likely not ever have a programming job again. I used to program
> in Visual Basic, C\C++, Delphi, etc. and some obscure "mainframe"
> languages. It's been about 18-19 years since my last programming job.
> I do understand programming concepts but I'm really not up on any of
> the more modern programming languages.
> 
> I've installed Python 3.7, the PyCharm IDE and watched some Youtube
> tutorials but it's been stretched out over about 1.5 years so I'll
> probably need to go back to the beginning. My problem is that I don't
> understand how Python programs are used. (i.e user input and output)
> Is Python mainly used for backends?
> 
> I've seen some Python gui frameworks like Tkinter, PyQt, etc. but they
> look kinda like adding a family room onto a 1986 double wide mobile
> home, and they look even more complicated than creating a GUI from
> scratch in C++ with a message loop, raising events . . .
> 
> So, what do you folks use Python for?
> 
> Nowdays I mainly just use programming for rather small utilities for
> my personal use. Currently I'd like to write something to iterate
> through open windows and save them to different folders depending on
> if the titlebar contains certain strings. In the past I would probably
> have used Excel's VBA to do this but I no longer have Excel installed
> on my main computer. I'd like a bit of a challenge but I don't want to
> spin my wheels trying to learn something that will be a dead end for
> me.


Your question is very broad. Python is used for an incredibly wide
variety of purposes.

Frankly, why worry about my uses for Python, the only important stuff is
what you want to do with it!

There are plenty of articles 'out there' which discuss using Excel
[data] with Python, why one should prefer Python to Excel, etc. Try:
https://info.cambridgespark.com/latest/python-vs-excel (BTW with Python
and appropriate libraries, the Excel package itself is not required)

One way to learn is to ask the question: how do I do xyz in Python? You
have some background, so will be able to ask reasonably 'educated' and
valid questions. This will feel faster, but is by definition a
piece-meal approach.

Us 'silver surfers' often prefer a more structured (and complete)
approach, and preferably one which looks at the semantics of the
language (in Python we talk of idioms and the "Zen of Python") not
merely the syntax. Thus, I recommend (free or $) MOOCs on the edX or
Coursera platforms (amongst others).

As you say, the profession has 'moved on' and there are fresh approaches
and new angles to get one's head around... So, it's not just "Python" then!

PS you will likely find the Python-Tutor mailing list solid assistance.
-- 
Regards =dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: A beginning beginner's question about input, output and . . .

2021-01-11 Thread Chris Angelico
On Tue, Jan 12, 2021 at 7:41 AM DonK  wrote:
>
>
> Hi, I'm thinking about learning Python but I'm 74 years old and will
> very likely not ever have a programming job again. I used to program
> in Visual Basic, C\C++, Delphi, etc. and some obscure "mainframe"
> languages. It's been about 18-19 years since my last programming job.
> I do understand programming concepts but I'm really not up on any of
> the more modern programming languages.
>
> I've installed Python 3.7, the PyCharm IDE and watched some Youtube
> tutorials but it's been stretched out over about 1.5 years so I'll
> probably need to go back to the beginning. My problem is that I don't
> understand how Python programs are used. (i.e user input and output)
> Is Python mainly used for backends?
>

Python is used in many different ways. I'd recommend focusing first on
the simple console input and output, which are available as the
input() and print() built-in functions; those are sufficient for a
vast majority of situations. Beyond that, you run into what's best
described as "inherent complexity"; building a good user interface is,
by its nature, not simple.

If it's easier, you can look into using a web browser as your user
interface. Python is superb at building web servers and web
applications, so you can easily design your app so the user interacts
with it using a very simple browser-based front end - either with
JavaScript or as a really easy form fill-out.

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


A beginning beginner's question about input, output and . . .

2021-01-11 Thread DonK


Hi, I'm thinking about learning Python but I'm 74 years old and will
very likely not ever have a programming job again. I used to program
in Visual Basic, C\C++, Delphi, etc. and some obscure "mainframe"
languages. It's been about 18-19 years since my last programming job.
I do understand programming concepts but I'm really not up on any of
the more modern programming languages.

I've installed Python 3.7, the PyCharm IDE and watched some Youtube
tutorials but it's been stretched out over about 1.5 years so I'll
probably need to go back to the beginning. My problem is that I don't
understand how Python programs are used. (i.e user input and output)
Is Python mainly used for backends?

I've seen some Python gui frameworks like Tkinter, PyQt, etc. but they
look kinda like adding a family room onto a 1986 double wide mobile
home, and they look even more complicated than creating a GUI from
scratch in C++ with a message loop, raising events . . .

So, what do you folks use Python for?

Nowdays I mainly just use programming for rather small utilities for
my personal use. Currently I'd like to write something to iterate
through open windows and save them to different folders depending on
if the titlebar contains certain strings. In the past I would probably
have used Excel's VBA to do this but I no longer have Excel installed
on my main computer. I'd like a bit of a challenge but I don't want to
spin my wheels trying to learn something that will be a dead end for
me.

I know that this probably seems like a stupid post but your input will
be useful.

Thank you.

   Don

I know that Python is a very popular language so I'm sorry if it
sounds like I'm being critical. I really don't know enough about it to
be critical.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: tkinter and input()

2020-09-29 Thread Terry Reedy

On 9/29/2020 9:48 AM, Pierre Bonville wrote:

I have a small problem with the method .quit() of tkinter.


What problem?  It works for me (3.9 on Win 10).

>>> import tkinter as tk
>>> r = tk.Tk()
>>> b = tk.Button(r, text= r.quit)
>>> b = tk.Button(r, text='quit', command=r.quit)
>>> b.pack()
>>> r.mainloop()  # This blocks until press button.
>>> # Root window with button is still displayed.

Your program has a lot more stuff extraneous to your question and 
requires matplotlib and numpy.


Posted code should be a minimal reproducible example such as above.

Try adding a few lines at a time until it breaks or does what you want.

--
Terry Jan Reedy

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


tkinter and input()

2020-09-29 Thread Pierre Bonville
 Hello everybody,
I have a small problem with the method .quit() of tkinter. Below is a
sketch of a much larger program, which shows the problem. I would like to
run the main program but keeping the tk window on the screen until the end.
Presently, execution stops after the first "plot" instruction. I don't
understand why. The program runs fine if one replaces "quit" by "destroy",
but then the tk window disappears. Is there a solution?
Thanks in advance for any answer,
Regards,
P.Bonville

# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
from tkinter import *
def init():
global vit
def print_par():
global vitt
vitt = vit.get()
print("velocity= ",vitt," cm/s")
fen.quit()

vit = ""
fen = Tk()
vit0 = StringVar()
Label(fen, text = "velocity (cm/s): ").grid(row=0)
vit = Entry(fen,text = vit0)
vit0.set(7.)
vit.grid(row=0, column=1)
button = Button(fen, text='OK', command=print_par).grid(row=5,column=0)
fen.mainloop()

vit = float(vitt)

init()
print(vit)

x = np.arange(0,4*np.pi,0.1)
y = np.sin(x)

for i in range(0,10):
plt.plot(x,y)
plt.show()
re = input("Hit RETURN to continue:")
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [Beginner] Spliting input

2020-06-25 Thread Andrew Jaffe

Hi,

On 25/06/2020 12:50, Bischoop wrote:

I try to split input numbers, for example: 12 so I cant add them, I
tried separated split(' ') but it's not working.
Any ideas how to do this?

*
numb1,numb2=input("enter 1st and 2nd no ").split()
Avg=(int(numb1) + int(numb2)) / 2
print(Avg)



So, this is an opportunity to do (and learn) some debugging!

One problem is that the first line does two things at once -- it reads 
the input and tries to split it into numb1 and numb2. Similarly for the 
"average" line.


You could instead try:

input_string = input("enter 1st and 2nd no ")
print(input_string)
numb1_as_string, numb2_as_string = input_string.split()
print(numb1_as_string, numb2_as_string)
numb1 = int(numb1)
numb2 = int(numb2)
print(numb1, numb2)
avg = (numb1 + numb2) / 2
print(avg)

Now, when if fails on input_string.split() (which I think is what 
happens) you can then be sure that you know what the input is. Let's say 
it's "17,3". Since you know that, you can experiment:


"17, 3".split() -> "17,", "3"  (note extra space)
"17 3".split() -> "17" "3" (aha, getting somewhere)
... and same results for both of these with split(' '), which should 
indicate that it's splitting on the space, and you didn't supply a space.


So now maybe try "17,3".split(',') -> "17", "3" (bingo!)

Bonus question: what happens with "17, 3".split(',')?






*

--
Thanks




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


Re: [Beginner] Spliting input

2020-06-25 Thread Peter Otten
Bischoop wrote:

> I try to split input numbers, for example: 12 so I cant add them, I
> tried separated split(' ') but it's not working.
> Any ideas how to do this?
> 
> *
> numb1,numb2=input("enter 1st and 2nd no ").split()
> Avg=(int(numb1) + int(numb2)) / 2
> print(Avg)
> *
> 
> --
> Thanks

To split the string "12" into its characters (i. e. the digits "1" and "2") 
you don't need the split() method which only works with separators.
Instead you can unpack the digits directly:

>>> a, b = input("enter two digits> ")
enter two digits> 12
>>> a
'1'
>>> b
'2'
>>> (int(a) + int(b)) / 2
1.5


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


Re: [Beginner] Spliting input

2020-06-25 Thread Frank Millman

On 2020-06-25 2:13 PM, Bischoop wrote:

On 2020-06-25, Andrew Bell  wrote:

Without knowing the problem you're having, it's hard to answer.
This seems generally correct.



Error track:
Traceback (most recent call last):
   File "splitting.py", line 1, in 
   numb1,numb2=input("enter 1st and 2nd no ").split()
   ValueError: not enough values to unpack (expected 2, got 1)



Without arguments, split() splits on whitespace.

If you entered 2 numbers separated by a comma, but no spaces, there is 
no split.


Maybe you meant split(',') which will split on a comma.

Frank Millman


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


Re: [Beginner] Spliting input

2020-06-25 Thread Bischoop
On 2020-06-25, Andrew Bell  wrote:
> Without knowing the problem you're having, it's hard to answer.
> This seems generally correct.
>
>
Error track:
Traceback (most recent call last):
  File "splitting.py", line 1, in 
  numb1,numb2=input("enter 1st and 2nd no ").split()
  ValueError: not enough values to unpack (expected 2, got 1)

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


Re: [Beginner] Spliting input

2020-06-25 Thread Andrew Bell
Without knowing the problem you're having, it's hard to answer.
This seems generally correct.

On Thu, Jun 25, 2020 at 7:57 AM Bischoop  wrote:

> I try to split input numbers, for example: 12 so I cant add them, I
> tried separated split(' ') but it's not working.
> Any ideas how to do this?
>
> *
> numb1,numb2=input("enter 1st and 2nd no ").split()
> Avg=(int(numb1) + int(numb2)) / 2
> print(Avg)
>

-- 
Andrew Bell
andrew.bell...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


[Beginner] Spliting input

2020-06-25 Thread Bischoop
I try to split input numbers, for example: 12 so I cant add them, I
tried separated split(' ') but it's not working.
Any ideas how to do this?

*
numb1,numb2=input("enter 1st and 2nd no ").split()
Avg=(int(numb1) + int(numb2)) / 2
print(Avg)
*

--
Thanks

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


Python - Suppress input while writing to window

2020-04-08 Thread Paraskevas Petsanas
Hi,
I am developing an app that monitors and corrects the user input based on some 
rules.
I am reading the events from keyboard with the keyboard python module.
I faced some problem when the user types very fast, as regards some overlays of 
text. By this I mean that when my app writes the correct input, the user 
continues writing and may writes before the corrector types the whole word.
I found, that I can start a keyboard hook with suppressed output to screen and 
tried to implements a solution.
In the above code I tried recreating the problem and tried giving the general 
idea. 

```
import keyboard
from collections import deque

string : str = ""
counter : int = 0
is_suppressed: bool = False # this indicates if letters are shown in the window 
or not
suppressed_string: str = ""
q = deque() # this is used as a buffer, and stores the words that are entered 
when the
# program is correcting


def keyboard_module_write_to_screen(is_suppressed, string):
for i in range(len(string) + 1):
print("--Pressing backspace--")
keyboard.press_and_release('backspace')
for i, char in enumerate (string): # simulating a calculation 
final_char_to_be_written = char.upper()
print("---WRITING THE CHAR -> {} 
---".format(final_char_to_be_written))
keyboard.write(final_char_to_be_written)
for i in range(30):
keyboard.write('*')
keyboard.write(' ')

def monitoring(event):
global counter, string, is_suppressed, suppressed_string

if (event.event_type == keyboard.KEY_DOWN): # and event.name != 
'backspace'):
print("-String entered : {}".format(event.name))

if (event.name == 'space'):
# if space is button a new word is entered
if (is_suppressed is True):
# if program occupied writing to the screen save the word 
to the buffer
q.appendleft(suppressed_string)
suppressed_string = ""

elif (is_suppressed is False):
# check and write first from the deque,
    # write the word(s) that were stored in the buffer 
before writing current
# input string
# haven't find a way to do the above alongside the 
others
keyboard.unhook_all()
keyboard.hook(monitoring, suppress = True)

is_suppressed = True

keyboard_module_write_to_screen(is_suppressed, string)

keyboard.unhook_all()
keyboard.hook(monitoring, suppress = False)
is_suppressed = False
counter = 0
string = ""

elif (event.name in "abcdefghijklmnopqrstuvwxyz") :
if (is_suppressed is True):
suppressed_string = ''.join([suppressed_string, event.name])
print("## SUPPRESSED_STRING = {} 
#".format(suppressed_string))

counter = counter + 1
print("-- COUNTER is : {}".format(counter))
string = ''.join([string, event.name])
elif (event.name == "]"):
print(q)
elif (event.name == 'backspace'):
pass

keyboard.hook(monitoring, suppress = False)
```
The main thing I want to achieve is
1)while correcting - writing to the window, read events and save them to a 
buffer
2)when correcting - writing is done check the buffer, write it's content, but 
keep reading events
3)if buffer empty and currently not writing something, read events etc.
I didn't manage to make it work and produce the desired result.
Any advice on how to make it work, would be useful.
Thanks in advance for any help.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to compare in python an input value with an hashed value in mysql table?

2020-01-16 Thread centredeformationfrance
Thank you so much Pieter! Danku well

Where can I write you a review 5/5! Linkedin? Google business? Facebook page? 

Thank you!Thank you!Thank you!Thank you!Thank you! X 1! 

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


Re: How to compare in python an input value with an hashed value in mysql table?

2020-01-16 Thread Pieter van Oostrum
Growth Hacking Formation  writes:

> Thanks for helping. That is what I thought.
> Lets say it is the case and I get the key. We know it uses sha256 and it 
> apply to the ascii code.
> What should be the python code in this scenario?
> I am novice and the hash python module is a bit too complex for me. I read 
> the doc.
>
> Thanks.

Some of the details are still vague, but I think it must be something like this:
Here is some code that works in both Python 2 and Python 3.

import hashlib
import hmac

secretfile = '.../lmfwc-files/secret.txt' ## Fill in proper file name

with open(secretfile, 'rb') as fd:
secret = fd.read()

key = 'goldQ3T8-1QRD-5QBI-9F22'

bkey = key.encode('ascii')

h = hmac.new(secret, bkey, hashlib.sha256)

print('hd (hex): ', h.hexdigest())

-- 
Pieter van Oostrum
www: http://pieter.vanoostrum.org/
PGP key: [8DAE142BE17999C4]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to compare in python an input value with an hashed value in mysql table?

2020-01-14 Thread Chris Angelico
On Wed, Jan 15, 2020 at 5:41 PM Growth Hacking Formation
 wrote:
>
> Thanks for helping. That is what I thought.
> Lets say it is the case and I get the key. We know it uses sha256 and it 
> apply to the ascii code.
> What should be the python code in this scenario?
> I am novice and the hash python module is a bit too complex for me. I read 
> the doc.
>
> Thanks.

Look at the source code for the PHP module. Find the parts you need.
My guess is that every hash-related function they call will have a
direct equivalent in Python.

Welcome to the wonderful world of porting code that you don't truly
comprehend :)

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


Re: How to compare in python an input value with an hashed value in mysql table?

2020-01-14 Thread Growth Hacking Formation
Thanks for helping. That is what I thought.
Lets say it is the case and I get the key. We know it uses sha256 and it apply 
to the ascii code.
What should be the python code in this scenario?
I am novice and the hash python module is a bit too complex for me. I read the 
doc.

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


Re: How to compare in python an input value with an hashed value in mysql table?

2020-01-14 Thread Chris Angelico
On Wed, Jan 15, 2020 at 10:54 AM Dennis Lee Bieber
 wrote:
>
> On Tue, 14 Jan 2020 10:02:08 -0800 (PST), Growth Hacking Formation
>  declaimed the following:
>
>
> >
> >Hello @formationgrowthhacking,
> >thank you for your message and for using my plugin.
> >For license key hashing, I implemented the PHP native method hash_hmac(), 
> >using the sha256 algorithm.
> >You can check out the class which is responsible for encryption, decryption, 
> >and hashing here:
> >https://plugins.trac.wordpress.org/browser/license-manager-for-woocommerce/trunk/includes/Crypto.php
> >Let me know if this helped!
> >###
> >
>
> https://www.php.net/manual/en/function.hash-hmac.php
> """
>  key
>
> Shared secret key used for generating the HMAC variant of the message
> digest.
> """
> ... Which implies that one needs to know another key to generate the hash
> of the input data. I suspect the author of your database system will not
> reveal that key (check the source code referenced by the author and see if
> you can find a key for use in the hash function).
>

I had a squiz at the linked-to source code, and it looks like the
corresponding key is stored in a file. Whether that actually
constitutes an improvement in security, I can't say. But to be
compatible, you would have to read the same file.

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


Re: How to compare in python an input value with an hashed value in mysql table?

2020-01-14 Thread Growth Hacking Formation

Thanks for your help.

Litle details,

the license key is goldQ3T8-1QRD-5QBI-9F22

and it is stored in database already encrypted.
License key is not saved in database with clear text. It is already encrypted. 
I am not sure what is this hash column for?

License key =>
def50200962018b6bbed50fc53abca6bb076eb2947fc379e69bd38dcea9f8fbe29eedd43f1148e721d5f6657d8d0152356f5a7ba566dde545a9a354c7b42af88fe4ea7775a4e2ee1a26d8b8f7e3272cf5a8bbe38197fdf19e1726d5e2d769bae408cd511706388abad5a75

hash =>
25138e045e9f50022331340a26d0eecbd0d7ca6bfefee0275749025c4f56c3a8
see screenshot:
http://prntscr.com/qnhz8h

I thought the "hash" column was the key to encrypt or decrypt the license 
stored in column "license_key".


So I run your code for testing with appropriate licese key:
Python Code: 
1
2
3
4
5
6   from hashlib import md5, sha256, sha512
 
key = 'goldQ3T8-1QRD-5QBI-9F22'
 
for hash_func in (md5, sha256, sha512):
print(hash_func(key.encode()).hexdigest())
and it give this outpu:
Output:
ecc58b55c33fe6dfe3b49d6d63aad65b
f67e701240fbd964aa9a0eb81e2f549b8e3dd97e1aa3b1f5796fd12cd9b14005
8288f635fbab6d6511fc5aa63caf153fa434b3d351612cdf48dcf6abea4275cde5f0d6fffda2e7c6fd42350483603cf6959dd62c946eea2b75eca9f60a5cf5b7

Process finished with exit code 0
As you can see, here the code doesn't give same result than database.

===

Regarding wordpress login, I didn't find any python library which can can 
handle this authentification process.

I contacted the developper, and he replied me this message:



Hello @formationgrowthhacking,
thank you for your message and for using my plugin.
For license key hashing, I implemented the PHP native method hash_hmac(), using 
the sha256 algorithm.
You can check out the class which is responsible for encryption, decryption, 
and hashing here:
https://plugins.trac.wordpress.org/browser/license-manager-for-woocommerce/trunk/includes/Crypto.php
Let me know if this helped!
###

But he may not know python. I need help of python expert.

Does this update help for better understanding my issue?

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


Re: How to compare in python an input value with an hashed value in mysql table?

2020-01-14 Thread dieter
ad...@formationgrowthhacking.com writes:
> I have a wordpress 5.3 websites which sell a software with license key.
>
> The license key is encrypted and stored in Mysql table. there are 2 columns 
> "license" and "hash":
>
> license_key   
> def50200352f5dc4bd8181a9daebbf4f9177fe725111a5a479d64636d01c2a10074e0c645abe898dea18210af563a5334288420551ab61c18ca4506cd03aa5d2bdd40933ddf7ca4d4b61b1c0f58a3830cbe0891cf4ff526311d5d637a55a574eca2c3a1b487b56
>
> hash
> 9498cbf8bf00d6c55e31f98ba6d8294afa3127a84f31aa622c4158ac7377c6dd
>
>
> My python program get an input for user (the license key in string without 
> any encrypton) and need to compare it with the official license key stored in 
> Mysql database of our Wordpress website.
>
> I read a lot of hashlib python, functions and methods. But I didn't find 
> anywhere how could I "hash" the string input typed by user with some hash 
> values from the table, in order to compare both values (the input license and 
> the license stored in mysql table).

Contact the person responsible for the data in your database.
Ask him which hashing algorithm should be used to verify the
license info provided by a user against the database info.

Note: there are many different hashing functions (e.g. "md5", "sha1",
"sha256", ...) and often their use involves an additionl secret
(besides the hashed data). Best get those details from a
knowledgable person than from us.

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


Re: How to compare in python an input value with an hashed value in mysql table?

2020-01-14 Thread Pieter van Oostrum
ad...@formationgrowthhacking.com writes:

> I have a wordpress 5.3 websites which sell a software with license key.
>
> The license key is encrypted and stored in Mysql table. there are 2 columns 
> "license" and "hash":
>
> license_key   
> def50200352f5dc4bd8181a9daebbf4f9177fe725111a5a479d64636d01c2a10074e0c645abe898dea18210af563a5334288420551ab61c18ca4506cd03aa5d2bdd40933ddf7ca4d4b61b1c0f58a3830cbe0891cf4ff526311d5d637a55a574eca2c3a1b487b56
>
> hash
> 9498cbf8bf00d6c55e31f98ba6d8294afa3127a84f31aa622c4158ac7377c6dd
>
Slightly off-topic:

Why would you store *both* an encrypted key and a hash?
If you have the encrypted key in the database and the encryption key on your 
site (presumably in the Python code) and your site is hacked, all the license 
keys are potentially in the open.
And if your key is on the site you can as well encrypt the entered license key 
and compare it to the stored encrypted key.

end off-topic

> My python program get an input for user (the license key in string
> without any encrypton) and need to compare it with the official license
> key stored in Mysql database of our Wordpress website.
>
> I read a lot of hashlib python, functions and methods. But I didn't find
> anywhere how could I "hash" the string input typed by user with some
> hash values from the table, in order to compare both values (the input
> license and the license stored in mysql table).

This supposes Python 3:

Let's assume the entered key is in ASCII and stored in the variable 'key'.

from hashlib import sha256
key = bytes(key, 'ascii')
hash = sha256(key).hexdigest()

Now you can compare hash with the stored hash in the database. Of course this 
only works if that stored hash has been calculated in the same way from the 
same key.

On Python 2 (which you shouldn't use) you can leave out the "key = bytes(key, 
'ascii')" part.

You can of course make it more sophisticated, for example by using a salt. 
Unless your keys are extremely valuable, I wouldn't bother with that.
-- 
Pieter van Oostrum
www: http://pieter.vanoostrum.org/
PGP key: [8DAE142BE17999C4]
-- 
https://mail.python.org/mailman/listinfo/python-list


How to compare in python an input value with an hashed value in mysql table?

2020-01-13 Thread admin
I have a wordpress 5.3 websites which sell a software with license key.

The license key is encrypted and stored in Mysql table. there are 2 columns 
"license" and "hash":

license_key   
def50200352f5dc4bd8181a9daebbf4f9177fe725111a5a479d64636d01c2a10074e0c645abe898dea18210af563a5334288420551ab61c18ca4506cd03aa5d2bdd40933ddf7ca4d4b61b1c0f58a3830cbe0891cf4ff526311d5d637a55a574eca2c3a1b487b56

hash
9498cbf8bf00d6c55e31f98ba6d8294afa3127a84f31aa622c4158ac7377c6dd


My python program get an input for user (the license key in string without any 
encrypton) and need to compare it with the official license key stored in Mysql 
database of our Wordpress website.

I read a lot of hashlib python, functions and methods. But I didn't find 
anywhere how could I "hash" the string input typed by user with some hash 
values from the table, in order to compare both values (the input license and 
the license stored in mysql table).


This topic 
https://stackoverflow.com/questions/1183161/to-sha512-hash-a-password-in-mysql-database-by-python
  gave me a lot of information but didn't fix my issue.

Anyone has any idea how to proceed?

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


Re: How to load cookies from a json input in python-requests?

2019-08-12 Thread Alexandre Brault

On 2019-08-12 11:38 p.m., Peng Yu wrote:

```
import requests
s = requests.Session()
import json
s.cookies.set_cookie(requests.utils.cookiejar_from_dict(json.load(sys.stdin)))
```

I used the above command to load cookies from a json file. But I got
the following error. Does anybody know how to fix the error? Thanks.

```
Traceback (most recent call last):
   File "/xxx/xxx.py", line 15, in 
 
s.cookies.set_cookie(requests.utils.cookiejar_from_dict(json.load(sys.stdin)))
   File 
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/cookies.py",
line 345, in set_cookie
 if hasattr(cookie.value, 'startswith') and
cookie.value.startswith('"') and cookie.value.endswith('"'):
AttributeError: 'RequestsCookieJar' object has no attribute 'value'
```
set_cookie is used to add an individual cookie in an existing cookiejar. 
You might want to have a look at 
requests.utils.add_dict_to_cookiejar(s.cookies, json.load(...)) or 
passing the result of requests.utils.cookiejar_from_dict ti the cookies 
argument of requests.Session

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


How to load cookies from a json input in python-requests?

2019-08-12 Thread Peng Yu
```
import requests
s = requests.Session()
import json
s.cookies.set_cookie(requests.utils.cookiejar_from_dict(json.load(sys.stdin)))
```

I used the above command to load cookies from a json file. But I got
the following error. Does anybody know how to fix the error? Thanks.

```
Traceback (most recent call last):
  File "/xxx/xxx.py", line 15, in 

s.cookies.set_cookie(requests.utils.cookiejar_from_dict(json.load(sys.stdin)))
  File 
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/cookies.py",
line 345, in set_cookie
if hasattr(cookie.value, 'startswith') and
cookie.value.startswith('"') and cookie.value.endswith('"'):
AttributeError: 'RequestsCookieJar' object has no attribute 'value'
```

-- 
Regards,
Peng
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Handle foreign character web input

2019-07-04 Thread Peter J. Holzer
On 2019-07-03 18:13:20 -0500, Igor Korot wrote:
> But as I said, imaging the following situation:
> 
> You are somewhere in Germany and you have a German version of OS
> (any OS)
> .
> You also have a German keyboard (hardware) with German keys.
> 
> Now you are assigned to go to some international events where people
> all over the world will be coming to your presentation and they will be
> registering on you machine
> 
> Also imagine that the company policy prohibits you from  modifying the
> system settings.
> 
> My solution:
> I would probably grab a lot of registering paper and ask people to enter
> English transliteration of the names on the machine so when you come
> back to the office you can properly enter their names using all those
> different keyboards (maybe virtual ones) to associate them with
> their English counterparts.
> 
> Just curious - what would you do?

I would set up a web registration form, so people can use their own
device (phone, laptop, whatever) to enter their name. Presumably they
know how to enter their name on their device. I definitely don't know
how to enter a hand-written (or even printed) Chinese name on any
keyboard (I managed to do that recently, but that was a lot of work and
way into "a fun challenge to do once, not something I want to repeat"
territory).

hp

-- 
   _  | Peter J. Holzer| we build much bigger, better disasters now
|_|_) || because we have much more sophisticated
| |   | h...@hjp.at | management tools.
__/   | http://www.hjp.at/ | -- Ross Anderson 


signature.asc
Description: PGP signature
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Handle foreign character web input

2019-07-03 Thread Chris Angelico
On Thu, Jul 4, 2019 at 8:12 AM Igor Korot  wrote:
>
> Hi, Chris,
>
> On Wed, Jul 3, 2019 at 4:41 PM Chris Angelico  wrote:
> >
> > On Thu, Jul 4, 2019 at 7:08 AM Igor Korot  wrote:
> > >
> > > Hi, Thomas,
> > >
> > > On Sat, Jun 29, 2019 at 11:06 AM Thomas Jollans  wrote:
> > > >
> > > > On 28/06/2019 22:25, Tobiah wrote:
> > > > > A guy comes in and enters his last name as RÖnngren.
> > > > With a capital Ö in the middle? That's unusual.
> > > > >
> > > > > So what did the browser really give me; is it encoded
> > > > > in some way, like latin-1?  Does it depend on whether
> > > > > the name was cut and pasted from a Word doc. etc?
> > > > > Should I handle these internally as unicode?  Right
> > > > > now my database tables are latin-1 and things seem
> > > > > to usually work, but not always.
> > > >
> > > >
> > > > If your database is using latin-1, German and French names will work,
> > > > but Croatian and Polish names often won't. Not to mention people using
> > > > other writing systems.
> > > >
> > > > So Günther and François are ok, but Bolesław turns into Boles?aw and
> > > > don't even think about anybody called Владимир or محمد.
> > >
> > > As others pointed out - it is very easy to do transliteration especially 
> > > if
> > > its' not a user registration that will be done.
> > >
> > > But I would simply not do that at all - create your forms in English and
> > > accept English spellings only.
> > > Most people that do computers this days can enter phonetic spelling
> > > of their first/last names (even in Chinese/Japanese/Hebrew).
> > >
> > > And all European names can be transliterated to English.
> > >
> > > Besides as the OP said - if someone comes to him and will
> > > try to enter the non-English name. The OP might not even have the 
> > > appropriate
> > > keyboard layout to input such a name. And if this is an (time consuming) 
> > > event
> > > all (s)he can do is ask for phonetic spelling.
> > >
> > > Thank you.
> > >
> > What you basically just said was "I wish all those ugly foreign names
> > would just go away". Honestly, that's not really an acceptable
> > solution; you assume that you can transliterate any name into
> > "English" in some perfect way, which is acceptable to everyone in the
> > world. And you also assume that this transformation will be completely
> > consistent, so you can ask someone his/her name and always get back
> > the same thing.
> >
> > If you want to do a Latinization and accent strip for the sake of a
> > search, that's fine; but make sure you retain the name as people want
> > it to be retained. Don't be bigoted.
> >
> > https://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/
>
> I'm not opposing this, in fact I'm all for keeping the native name somewhere 
> in
> the DB.
>
> But as I said, imaging the following situation:
>
> You are somewhere in Germany and you have a German version of OS
> (any OS)
> .
> You also have a German keyboard (hardware) with German keys.
>
> Now you are assigned to go to some international events where people
> all over the world will be coming to your presentation and they will be
> registering on you machine
>
> Also imagine that the company policy prohibits you from  modifying the
> system settings.
>
> My solution:
> I would probably grab a lot of registering paper and ask people to enter
> English transliteration of the names on the machine so when you come
> back to the office you can properly enter their names using all those
> different keyboards (maybe virtual ones) to associate them with
> their English counterparts.
>
> Just curious - what would you do?
>

I would use a Compose key (if available) or a software input method
(always available, as long as you have an internet connection and
browser, and often available locally too). With your method, how would
you enter it back at the office, if all you have is an English
transliteration? How do you transform it back into the original
characters?

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


Re: Handle foreign character web input

2019-07-03 Thread Igor Korot
Hi, Chris,

On Wed, Jul 3, 2019 at 4:41 PM Chris Angelico  wrote:
>
> On Thu, Jul 4, 2019 at 7:08 AM Igor Korot  wrote:
> >
> > Hi, Thomas,
> >
> > On Sat, Jun 29, 2019 at 11:06 AM Thomas Jollans  wrote:
> > >
> > > On 28/06/2019 22:25, Tobiah wrote:
> > > > A guy comes in and enters his last name as RÖnngren.
> > > With a capital Ö in the middle? That's unusual.
> > > >
> > > > So what did the browser really give me; is it encoded
> > > > in some way, like latin-1?  Does it depend on whether
> > > > the name was cut and pasted from a Word doc. etc?
> > > > Should I handle these internally as unicode?  Right
> > > > now my database tables are latin-1 and things seem
> > > > to usually work, but not always.
> > >
> > >
> > > If your database is using latin-1, German and French names will work,
> > > but Croatian and Polish names often won't. Not to mention people using
> > > other writing systems.
> > >
> > > So Günther and François are ok, but Bolesław turns into Boles?aw and
> > > don't even think about anybody called Владимир or محمد.
> >
> > As others pointed out - it is very easy to do transliteration especially if
> > its' not a user registration that will be done.
> >
> > But I would simply not do that at all - create your forms in English and
> > accept English spellings only.
> > Most people that do computers this days can enter phonetic spelling
> > of their first/last names (even in Chinese/Japanese/Hebrew).
> >
> > And all European names can be transliterated to English.
> >
> > Besides as the OP said - if someone comes to him and will
> > try to enter the non-English name. The OP might not even have the 
> > appropriate
> > keyboard layout to input such a name. And if this is an (time consuming) 
> > event
> > all (s)he can do is ask for phonetic spelling.
> >
> > Thank you.
> >
> What you basically just said was "I wish all those ugly foreign names
> would just go away". Honestly, that's not really an acceptable
> solution; you assume that you can transliterate any name into
> "English" in some perfect way, which is acceptable to everyone in the
> world. And you also assume that this transformation will be completely
> consistent, so you can ask someone his/her name and always get back
> the same thing.
>
> If you want to do a Latinization and accent strip for the sake of a
> search, that's fine; but make sure you retain the name as people want
> it to be retained. Don't be bigoted.
>
> https://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/

I'm not opposing this, in fact I'm all for keeping the native name somewhere in
the DB.

But as I said, imaging the following situation:

You are somewhere in Germany and you have a German version of OS
(any OS)
.
You also have a German keyboard (hardware) with German keys.

Now you are assigned to go to some international events where people
all over the world will be coming to your presentation and they will be
registering on you machine

Also imagine that the company policy prohibits you from  modifying the
system settings.

My solution:
I would probably grab a lot of registering paper and ask people to enter
English transliteration of the names on the machine so when you come
back to the office you can properly enter their names using all those
different keyboards (maybe virtual ones) to associate them with
their English counterparts.

Just curious - what would you do?

Thank you.

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


Re: Handle foreign character web input

2019-07-03 Thread Chris Angelico
On Thu, Jul 4, 2019 at 7:08 AM Igor Korot  wrote:
>
> Hi, Thomas,
>
> On Sat, Jun 29, 2019 at 11:06 AM Thomas Jollans  wrote:
> >
> > On 28/06/2019 22:25, Tobiah wrote:
> > > A guy comes in and enters his last name as RÖnngren.
> > With a capital Ö in the middle? That's unusual.
> > >
> > > So what did the browser really give me; is it encoded
> > > in some way, like latin-1?  Does it depend on whether
> > > the name was cut and pasted from a Word doc. etc?
> > > Should I handle these internally as unicode?  Right
> > > now my database tables are latin-1 and things seem
> > > to usually work, but not always.
> >
> >
> > If your database is using latin-1, German and French names will work,
> > but Croatian and Polish names often won't. Not to mention people using
> > other writing systems.
> >
> > So Günther and François are ok, but Bolesław turns into Boles?aw and
> > don't even think about anybody called Владимир or محمد.
>
> As others pointed out - it is very easy to do transliteration especially if
> its' not a user registration that will be done.
>
> But I would simply not do that at all - create your forms in English and
> accept English spellings only.
> Most people that do computers this days can enter phonetic spelling
> of their first/last names (even in Chinese/Japanese/Hebrew).
>
> And all European names can be transliterated to English.
>
> Besides as the OP said - if someone comes to him and will
> try to enter the non-English name. The OP might not even have the appropriate
> keyboard layout to input such a name. And if this is an (time consuming) event
> all (s)he can do is ask for phonetic spelling.
>
> Thank you.
>
What you basically just said was "I wish all those ugly foreign names
would just go away". Honestly, that's not really an acceptable
solution; you assume that you can transliterate any name into
"English" in some perfect way, which is acceptable to everyone in the
world. And you also assume that this transformation will be completely
consistent, so you can ask someone his/her name and always get back
the same thing.

If you want to do a Latinization and accent strip for the sake of a
search, that's fine; but make sure you retain the name as people want
it to be retained. Don't be bigoted.

https://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/

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


  1   2   3   4   5   6   7   8   9   10   >