Forcing no-user-site in embedded Python

By default a directory like %APPDATA%\Python\Python311\site-packages (Windows) or ~/.local/lib/python311/site-packages (Unix) is added to the sys.path on startup, if it exists.

This can be suppressed by passing -s on the command line or setting PYTHONNOUSERSITE in the environment.

With embedded Python, there are circumstances where a location entirely controlled by the user is particularly unwanted, so we want to go down the NOUSERSITE route. However the command line is not available, and it also may not be possible to change the environment of the running process when we come to initialize Python.

My question then is how to ensure that NOUSERSITE is respected when using something like Py_InitializeEx and similar configuration API functions. I did find Issue 35706: Make it easier to use a venv with an embedded Python interpreter - Python tracker which is clearly related, but don’t see a prescribed way to do things. Should I be aiming to use Py_SetPath with everything except the user-specific path?

Thank you.

How exactly are you starting the Python process? If there’s an environment, does that also imply there’s an operating system? If some kind of operating system call is used to start the process, that should be able to accept command-line arguments.

Thanks Karl.

To motivate a little more why I’m trying to do this entirely internally, let’s say the product is a C addin to Microsoft Excel. The addin uses (embedded) Python to do its work. In this case the user a) has started Excel in whatever way they wish, with whatever command line and environment they wish. Additionally the user may also have Python on their machine, with packages in user-site that I want to make sure are ignored by my embedded copy of Python.

(Excel is a relatively real example, but it is not the only one; there are plenty of circumstances where you can’t control the command line).

Thanks again.