Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit138eb37

Browse files
committed
Merge pull request#16 from 'skrashevich/230722-return'
2 parents02276f7 +edd9032 commit138eb37

File tree

3 files changed

+82
-7
lines changed

3 files changed

+82
-7
lines changed

‎README.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ hass.services.call('persistent_notification', 'create', {
7373

7474
```
7575

76-
###Run script from inline source
76+
###Run script from inline source and return data
7777

7878
Show your IP address in Notification. Using`requests` library. It is installed by default with Home Assistant.
7979

@@ -93,6 +93,7 @@ script:
9393
'title': data['title'],
9494
'message': f"My IP: { resp['ip'] }"
9595
})
96+
return_response = resp # return data
9697
```
9798
9899
### Example remote SSH-command run

‎custom_components/python_script/__init__.py‎

Lines changed: 78 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,15 @@
99
fromhomeassistant.helpersimportconfig_validationascv
1010
fromhomeassistant.helpers.typingimportServiceCallType
1111
fromhomeassistant.requirementsimportasync_process_requirements
12+
fromhomeassistant.config_entriesimportConfigEntry
13+
fromhomeassistant.coreimport (
14+
HomeAssistant,
15+
ServiceCall,
16+
ServiceResponse,
17+
SupportsResponse,
18+
)
19+
fromhomeassistant.helpersimportconfig_validationascv,entity_platform,service
20+
fromhomeassistant.util.jsonimportJsonObjectType
1221

1322
_LOGGER=logging.getLogger(__name__)
1423

@@ -25,9 +34,25 @@
2534
},
2635
extra=vol.ALLOW_EXTRA,
2736
)
37+
PYTHON_SCRIPTS_PRO_SERVICE_SCHEMA=vol.Schema(
38+
{
39+
vol.Optional("file"):str,
40+
vol.Optional("source"):str,
41+
vol.Optional("cache"):bool,
42+
}
43+
)
44+
2845

46+
defmd5(data:str)->str:
47+
"""
48+
Calculate the MD5 hash of the input string.
2949
30-
defmd5(data:str):
50+
Args:
51+
data (str): The input string to calculate the MD5 hash for.
52+
53+
Returns:
54+
str: The MD5 hash of the input string.
55+
"""
3156
returnhashlib.md5(data.encode()).hexdigest()
3257

3358

@@ -40,7 +65,30 @@ async def async_setup(hass: HomeAssistant, hass_config: dict):
4065

4166
cache_code= {}
4267

43-
defhandler(call:ServiceCallType):
68+
defhandler(call:ServiceCall)->ServiceResponse:
69+
"""
70+
Handler function for processing a service call.
71+
72+
Args:
73+
call (ServiceCall): The service call object containing the data for the call.
74+
75+
Returns:
76+
ServiceResponse: The response returned by the function.
77+
78+
Raises:
79+
None
80+
81+
Description:
82+
This function is responsible for handling a service call. It receives a ServiceCall object as the input parameter, which contains the data for the call. The function first checks if the 'file' or 'source' parameter is present in the call data. If neither of them is present, an error message is logged and the function returns without any response.
83+
84+
If either 'file' or 'source' is present, the function proceeds to retrieve the code from the cache or load it from the file or inline source. If the 'cache' parameter is set to False or the code is not found in the cache, the function loads the code from the specified file or inline source and compiles it.
85+
86+
If the 'cache' parameter is set to True and the code is loaded from a file, the compiled code is stored in the cache for future use. Similarly, if the code is loaded from an inline source, it is stored in the cache with the source ID as the key.
87+
88+
If the 'return_response' attribute of the service call is True, the function calls the 'execute_script' function with the necessary parameters and returns the response returned by it. Otherwise, the function returns None.
89+
90+
Note: This function assumes that the necessary variables, such as '_LOGGER', 'hass', and 'cache_code', are already defined.
91+
"""
4492
# Run with SyncWorker
4593
file=call.data.get("file")
4694
srcid=md5(call.data["source"])if"source"incall.dataelseNone
@@ -74,16 +122,41 @@ def handler(call: ServiceCallType):
74122
else:
75123
_LOGGER.debug("Load code from cache")
76124

77-
execute_script(hass,call.data,_LOGGER,code)
125+
ifcall.return_response:
126+
returnexecute_script(hass,call.data,_LOGGER,code)or {}
127+
returnNone
78128

79-
hass.services.async_register(DOMAIN,"exec",handler)
129+
hass.services.async_register(
130+
DOMAIN,
131+
"exec",
132+
handler,
133+
PYTHON_SCRIPTS_PRO_SERVICE_SCHEMA,
134+
SupportsResponse.OPTIONAL,
135+
)
80136

81137
returnTrue
82138

83139

84140
defexecute_script(hass:HomeAssistant,data:dict,logger,code):
85141
try:
86142
_LOGGER.debug("Run python script")
87-
exec(code)
143+
loc_vars= {}
144+
exec(code, {},loc_vars)
145+
146+
ifloc_vars.get("return_response")isnotNone:
147+
service_response:JsonObjectType= {
148+
"stdout":loc_vars["return_response"],
149+
"stderr":"",
150+
"returncode":0,
151+
}
152+
returnservice_response
153+
else:
154+
return {}
88155
exceptExceptionase:
89156
_LOGGER.error(f"Error executing script",exc_info=e)
157+
service_response:JsonObjectType= {
158+
"stderr":f"Error executing script:{e}",
159+
"stdout":"",
160+
"returncode":13,
161+
}
162+
returnservice_responseifeelse {}

‎hacs.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
{
22
"name":"Python Scripts Pro",
3-
"render_readme":true
3+
"render_readme":true,
4+
"homeassistant":"2023.7.0"
45
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp