Variables to python script

Hi everyone. I´m nearly completely new in python and in Homeassistant, but i got nearly everythink working.

Now im trying to change value in MySQL Database with a python script.
I´ve found the following script in the forum and got it to work.

import MySQLdb
database = MySQLdb.connect("HOST","USER","PW","DB")
cursor = database.cursor()
query = "UPDATE `ccspardose`.`cashvalue` SET item2 = item2 + 1;"
cursor.execute(query)
database.commit()
database.close()

The Script works and i can run is from a service call.
But now the question.

How (is it possible?) I can send a variable into the script. and use it there
E.g. I dont want to add 1 in the mysql query, but a value of an entity (in my case a value from a counter helper)
so that it looks like this:

query = "UPDATE `ccspardose`.`cashvalue` SET item2 = item2 + VARIABLE_FROM_HA;"

But i dont know how to pass a entityvalue to the script and read it there.

I´m calling the script as following:

shell_command:
    runccspardosequery: "python3 /config/python_scripts/addvaluetodb.py"

I hope you understand me, sorry for my bad english :wink:

Many Thanks in advance!

you can only pass variables that way via ‘arguments’. So your python script will have to change to accept arguments. It’s no easy task if you don’t know how to code. From there, you’d need to use jinja to properly create each argument based on jinja code.

without any safety built in, this would be your python file

import sys
import MySQLdb

try:
  value = int(sys.argv[-1] if len(sys.argv) == 2 else 0)
except ValueError:
  value = 0

database = MySQLdb.connect("HOST","USER","PW","DB")
cursor = database.cursor()
query = f"UPDATE `ccspardose`.`cashvalue` SET item2 = item2 + {value};"
cursor.execute(query)
database.commit()
database.close()

and this would be your shell command, but you’d have to replace the entity_id for the sensor.

shell_command:
    runccspardosequery: "python3 /config/python_scripts/addvaluetodb.py {{ sensor('counter.xyz') }}"