Add sleep functionality to python_script

Having access to time.sleep() or a similar functionality would allow users to have a more full-fledged experience when using python_script.

Edit: on second though, having access to the time module and datetime module, or equivalent functions would be fantastic additions to the python_script module

I agree here – I need sleep in a script and it means I now need to figure out AppDaemon

Have a look in the Python_script feedback topic. In short: support for time and/or datetime might be added, but support for sleep will not.

For anyone else stumbling for information on Python Scripts and finding this thread, it’s important to mention that support for time.sleep() was in fact added . . . see this thread:

I have tried this, but can’t import it or rund time.sleep or sleep…

Are you using a recent version of HomeAssistant?

No import is possilbe in a Python script, they are all imported by the underlying plumbing/framework… so you can only access what the HomeAssistant team has exposed… time.sleep() being a function that they did expose.

Here is a snippet of code from my python scripts that use the Sleep method. An important element, is that the parameter is specified in Seconds, so for milliseconds you must specify a fractional second value… so I use .035 to represent 35 milliseconds:

delay_time_secs = .035

#Keep Looping while the Up or Down button is being pressed!
while pico_state_value == 8 or pico_state_value == 16:
	#Call the volume Up or Down REST Command via service name based on the button currently being pushed...
	volume_service_name = "denonavr_volume_up" if pico_state_value == 8 else "denonavr_volume_down"
	#NOTE: Because this is called in a tight/delayed loop we use a blocking call (vs async)
	#		by passing True as the blocking param. This allows the volume to be smoothly 
	#		adjusted via multiple calls in sequence until the button is released."rest_command", volume_service_name, None, True)

Why not just call a regular python script with a shell command?

Sure, you could do that . . . but direct use of Python Scripts is a supported feature:

In my opinion it has some advantages over Shell scripts in that they can be called by their name as services, and it’s a bit easier to pass parameters to, potentially more stable (I’ve not tested that, but found that my XBMC shells script approaches were flaky), etc.

And, I find them much easier to work with without the needless middle layer of mapping to a Shell command, etc. and are GREAT alternative to Automations with complex templates used to handle if/else logic.

But, sure, you could try Shell scripts too… becuase you still have to use them if you ever want to use advanced features such as REST calls, etc. which the Python Scripts don’t support (ugggg).

1 Like