<@ULVA73B9P> show me some python code that will te...
# ask-marvin
j
@Marvin show me some python code that will tell me if I'm currently in a running flow
m
To check if you are currently in a running flow, you can make use of the
get_run_context
function from Prefect. Here's a concise example:
Copy code
python
from prefect import flow, get_run_context

@flow
def my_workflow():
    # Check if we are in a running flow
    try:
        context = get_run_context()
        if context.flow_run:
            print("This code is running within a Prefect Flow!")
        else:
            print("Not running in a Prefect Flow.")
    except RuntimeError:
        print("Not running in a Prefect Flow.")

if __name__ == "__main__":
    my_workflow()
This code will output an appropriate message indicating whether the code is currently running within a flow.
j
@Marvin
Copy code
>>> from prefect import get_run_context
exit()Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: cannot import name 'get_run_context' from 'prefect' (/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/prefect/__init__.py)
m
It appears there is a slight correction needed in the import statement. You should import
get_run_context
from
prefect.context
. Here's the corrected example:
Copy code
python
from prefect import flow
from prefect.context import get_run_context

@flow
def my_workflow():
    # Check if we are in a running flow
    try:
        context = get_run_context()
        if context:
            print("This code is running within a Prefect Flow!")
        else:
            print("Not running in a Prefect Flow.")
    except RuntimeError:
        print("Not running in a Prefect Flow.")

if __name__ == "__main__":
    my_workflow()
This should correctly check if the current code is running within a Prefect Flow. For more details, you can refer to the documentation: https://docs.prefect.io/latest/guides/runtime-context/