admin管理员组文章数量:1289583
I have something like this:
try:
response = requests.post(
url, json=group, headers=self._headers, auth=self._auth
)
logger.info(f"API Response: {response.text}")
return True
except requests.exceptions.RequestException as e:
logger.error(
f"Failed to create group '{group['groupName']}'. "
f"Exception: {str(e)}"
)
I'm getting some output if try
is done for example: BLACK
I'm getting some output if except
is done for example: WHITE
I have two spripts for example:
- test1.py
- test2.py
I would like to run test1.py if output is BLACK
I would like to run test2.py if output is WHITE
How to do that?
I expect run specific Python script from specific output.
I have something like this:
try:
response = requests.post(
url, json=group, headers=self._headers, auth=self._auth
)
logger.info(f"API Response: {response.text}")
return True
except requests.exceptions.RequestException as e:
logger.error(
f"Failed to create group '{group['groupName']}'. "
f"Exception: {str(e)}"
)
I'm getting some output if try
is done for example: BLACK
I'm getting some output if except
is done for example: WHITE
I have two spripts for example:
- test1.py
- test2.py
I would like to run test1.py if output is BLACK
I would like to run test2.py if output is WHITE
How to do that?
I expect run specific Python script from specific output.
Share Improve this question edited Feb 20 at 12:11 cards 4,9961 gold badge11 silver badges26 bronze badges asked Feb 20 at 12:00 Michał PieniakMichał Pieniak 133 bronze badges 2 |1 Answer
Reset to default 0Here a minimal working example using a finally
-block code as mentioned in the comments. The finally
blockcode is executed independently from any return
statements contained in the try
/except
blockcodes.
Use subprocess.run to execute a script (refer to the doc for a detailed explanation of such function). Notice that its return value is a subprocess.CompletedProcess
which can be further query.
import subprocess as sp
def f():
# mapping: output-testing path
output_mapping = {"BLACK": "./test1.py", "WHITE": "./test2.py"}
try:
output = "BLACK"
return True
except:
output = "WHITE"
finally:
path_file = output_mapping[output]
cmd = (
'python', # <- need to be fixed accordingly to the version you want to use and
# to the presence the Python executable in the PATH environment variable
path_file
)
cp = sp.run(cmd)
print(cp.returncode)
# calling the function
f()
From the comment of my answer a try
/except
implementation doesn't scale well. By digging a bit in the requests
library it is possible to redesign the exception handling just in terms of conditional branching:
import subprocess as sp
import requests
def f():
# mapping: output-testing path
output_mapping = {"BLACK": "./test1.py", "WHITE": "./test2.py"}
response = requests.post(
url, json=group, headers=self._headers, auth=self._auth
)
if response.status_code == requests.codes.ok:
logger.info(f"API Response: {response.text}")
output = "BLACK"
else:
output = "WHITE"
logger.error(
f"Failed to create group '{group['groupName']}'. "
f"Exception: {str(requests.exceptions.RequestException(?, ?))}" # TODO: pass the right parameters to the exception
)
path_file = output_mapping[output]
cmd = 'python', path_file # see previous answer for details
cp = sp.run(cmd)
print(cp.returncode)
return True if output == 'BLACK' else None
Remarks:
- if the condition
response.status_code == requests.codes.ok
is too restrictive a more flexible solution is possible by listing all allowed HTTP status code:response.status_code in {200, 201, .....}
- the
RequestException
is a subclass ofIOError
, alias ofOSError
, and the parameters need to be explicitly passed before logging it.
[! At the moment I cannot use requests
library so I cannot make any tests on the correct construction of the RequestException
but I hope that the links I provided are useful enough!]
本文标签: pythonRun another script from output exceptionStack Overflow
版权声明:本文标题:python - Run another script from output exception - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741437278a2378708.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
finally
blockcode after theexcept
where you filter the output that you got from the previous blockcodes and then use thesubprocess
library from the standard library to execute the test script, i.e.subprocess.run
– cards Commented Feb 20 at 12:15finally
code will be executed independently of thereturn
statement in thetry
/except
blockcodes – cards Commented Feb 20 at 12:22