A collection of Python tips to share

  • 2020-04-02 14:24:11
  • OfStack

Get the name of the current machine:


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'

Get the current working path:


import os
 
os.getcwd() #or #os.curdir just return . for current working directory.
#need abspath() to get full path.
os.path.abspath(os.curdir)

Get the system's temporary directory:


os.getenv('TEMP')

Conversion of string with int, long, float:

Python variables seem to have no type, but there are variables that have a type.

Use the atoi and atof in the locale module to convert a string to an int or a float, or you can convert a string to an int(),float(), and STR () directly. Previous versions of atoi and atof were under the string module.


s = "1233423423423423"
import locale
locale.atoi(s)
#1233423423423423
locale.atof(s)
#1233423423423423.0
int(s)
#1233423423423423
float(s)
#1233423423423423.0
str(123434)
"123434"

Bytes and unicodestr conversion:


# 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-independent code that must be used:



>>> import os
>>> os.pathsep
';'
>>> os.sep
'\'
>>> os.linesep
'rn'


Related articles: