Search code examples
pythonpython-3.xpythonanywhere

What is a reliable way to determine if code is run locally or deployed to PythonAnywhere?


I came across several approaches but don't know which one is the most reliable or proven one for PythonAnywhere.

Some environments provide a environment variable like

os.getenv('WHEREAMI') # some cluster

os.getenv('DYNO') # Heroku

Azure seems to use something like

RoleEnvironment.IsAvailable

On PythonAnywhere I saw that the username

USERNAME=my_pythonanywhere_username

could be used. Or something like

subprocess.run(['hostname'])

which returns something, but I am not sure if that's reliable.

Are there other approaches? What would be the a good pick?


Solution

  • PythonAnywhere dev here -- that's an excellent question. Checking your username is a good solution, but of course it's not ideal if (for example) your PythonAnywhere username is the same as the one you use on your own machine.

    If you're not using SSH to connect to our servers, then a good alternative solution is to look at the PYTHONANYWHERE_SITE environment variable. That will always be set to www.pythonanywhere.com or to eu.pythonanywhere.com depending on whether you're on our US-based site or our EU-based one. However, it is not set when you log in over SSH.

    You can indeed also look at the hostname. socket.gethostname() is probably a faster way to do that than shelling out with subprocess. The hostname you get back will vary over time and depending on where your code is running, but it will follow a common pattern. For example, if you were to run that code right now in a console on PythonAnywhere on the US you would get something like blue-liveconsole3, while if you were to run it from a website's code you would get something like blue-liveweb20. After our next system update, these might change to green-liveconsole3 and green-liveweb20. In general, the pattern is either green or blue, then a -, then live (for code running on our US systems) or eu (for code running in the EU), then the type of server the code is running on, and then a number.