简体   繁体   中英

How to check if code is run locally or on a cluster in Python

I have a python script that will be run both, on a local machine as well as on a computing cluster. I am looking for an efficient way for the script to check, whether it is run locally or not. What would be the best solution to that? I thought about passing some hardware information along and checking if it has changed, but surely there must be a more elegant solution than that.

You can check the hostname of the machine it's running on with the os module

 import os
 os.system('hostname')

this will output the hostname to console.

If you want to capture the output use .popen like so:

 a=os.popen('hostname').read()

this will return a string, which you may have to encode into utf-8 to make it readable like so:

 print(a.encode('utf-8'))

But this last bit really only applies if your os language has special characters

For config like this you could set an environment variable on the cluster / your local machine and then have the script check for that variable to determine where it is:

import os

where_am_i = os.getenv('WHEREAMI')


if where_am_i == 'cluster':
    # Do the cluster stuff
else:
    # Do the local machine stuff

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM