獲得當前機器的名字:
來自:http://tony413.iteye.com/blog/395177
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'
擷取當前工作路徑:
來自:http://www.cnblogs.com/Henrya2/archive/2009/01/16/1377284.html
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的轉化:
來自:http://blog.csdn.net/yatere/article/details/6606316
# 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
str.encode(s)
# bytes to str
bytes.decode(b)
寫平台獨立的代碼必須使用的:
>>> import os
>>> os.pathsep
';'
>>> os.sep
'\\'
>>> os.linesep
'\r\n'
完!