獲得當前機器的名字:
代碼如下:
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)
獲取系統的臨時目錄:
代碼如下:
os.getenv('TEMP')
字符串與int,long,float的轉化:
python的變量看起來是沒有類型的,其實是有變量是有類型的。
使用locale模塊下的atoi和atof來將字符串轉化為int或float,或者也可以直接使用int(),float(),str()來轉化。以前的版本中atoi和atof是在string模塊下的。
代碼如下:
s = "1233423423423423"
import locale
locale.atoi(s)
#1233423423423423
locale.atof(s)
#1233423423423423.0
int(s)
#1233423423423423
float(s)
#1233423423423423.0
str(123434)
"123434"
bytes和unicodestr的轉化:
代碼如下:
# bytes object
b = b"example"
# str object
s = "example"
# str to bytes
bytes(s, encoding = "utf8")
# bytes to str
str(b, encoding = "utf-8")
# an alternative method
# str to bytes
新聞熱點
疑難解答