'avoid pytest executing python script code during collection

I have it in my project that every python file that has executable python code directly in it, i.e. code that is not encapsulated in a class, will be executed by pytest while pytest is collecting. How can this be avoided?

If I add this at the top of the source file, then the file won't be collected, but then it can also not be run outside of pytest (because the skip raises a pytest Skipped exception)

import pytest
pytest.skip(allow_module_level=True)


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source