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 append a finally blockcode after the except where you filter the output that you got from the previous blockcodes and then use the subprocess library from the standard library to execute the test script, i.e. subprocess.run – cards Commented Feb 20 at 12:15
  • 1 the finally code will be executed independently of the return statement in the try/except blockcodes – cards Commented Feb 20 at 12:22
Add a comment  | 

1 Answer 1

Reset to default 0

Here 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 of IOError, alias of OSError, 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