收集的几个Python小技巧分享

672次阅读  |  发布于5年以前

获得当前机器的名字:

复制代码 代码如下:

def hostname():
sys = os.name

    if sys == 'nt':    
            hostname = os.getenv('computername')    
            return hostname    

    elif sys == 'posix':    
            host = os.popen('echo $HOSTNAME')    
            try:    
                    hostname = host.read()    
                    return hostname    
            finally:    
                    host.close()  
    else:    
            return 'Unkwon hostname'  

获取当前工作路径:

复制代码 代码如下:

import os

os.getcwd()

or

os.curdir just return . for current working directory.

need abspath() to get full path.

os.path.abspath(os.curdir)

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8