Check what device a script is on
What is the best way to check whether my script is currently running on a mobile device or somewhere else (like my laptop)?
sys.platform appears to be set to 'unknown', but relying on that seems shaky.
I could check for the existence of certain modules I guess? Seems like there must be a nicer way.
The question is whether you actually need to know whether you are on Pythonista or not. In almost all cases you can check if you can import the modules you need. For example, if your script requires the
uimodule, it's probably best to do the following:
try: import ui except ImportError: print("This script requires the ui module and should be run in Pythonista.") raise
Or leave the import as is, the ImportError usually speaks for itself.
If the script uses a module but could run without it, then something like this would be better:
try: import console HAVE_CONSOLE = True except ImportError: print("Could not import console module. Output text will not have colors.") HAVE_CONSOLE = False # ...somewhere in the main program... if HAVE_CONSOLE: console.set_color(1, 0, 0) print("Fancy red text") if HAVE_CONSOLE: console.set_color()
That way it can run with and without Pythonista's special modules. This solution of course only makes sense if the Pythonista-based functionality is not absolutely necessary (e. g. text colors, sound effects). If the script heavily uses modules like
uiit's better to raise an exception and inform the user if those modules couldn't be imported.