Python tips 32 [common tips]

Source: Internet
Author: User

Obtain the name of the current machine:
From: 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 '

 

Obtain the current job path:
From: 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)

 

Obtain the temporary directory of the system:

OS. getenv ( ' Temp ' )

Conversion of string and INT, long, float:

Python variables seem to have no type, but they actually have a type.

Use atoi and atof In the locale module to convert a string to int or float, or directly use int (), float (), STR () to convert it. In earlier versions, atoi and atof are in the string module.

S = " 1233423423423423 "
Import Locale
Locale. atoi (s)
# 1233423423423423
Locale. atof (s)
# 1233423423423423.0
INT (s)
# 1233423423423423
Float (s)
# 1233423423423423.0
STR (0, 123434)
" 123434 "

 

Conversion of bytes and unicodestr:

From: 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)

 

Write platform independentCodeRequired:

>>> Import OS
>>> OS. pathsep
' ; '
>>> OS. SEP
' \\ '
>>> OS. linesep
' \ R \ n '

 

 

Complete!
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.