Tips on collecting Python

Source: Internet
Author: User
This article mainly introduces several tips on collecting Python, such as obtaining the name of the current machine, obtaining the current working path, and obtaining the temporary directory of the system. For more information, see Obtain the name of the current machine:

The code is as follows:


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:

The code is as follows:


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:

The code is as follows:


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.

The code is as follows:


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:

The code is as follows:


# 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)

The following code must be used to write platform-independent code:


The code is as follows:


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

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.