Programming Python - 2. System Tools

Programming Python - 2. System Tools
Chapter 2 system tools

os.getcwd  #current workding directory
os.environ # shell environment variables
sys.argv    #command-line arguments
sys.stdin stdout stderr

input(): wait for the keypress if clicked
a[:6}: show the first 6 elements of array a

sys.__doc__
help(sys)



line=aaa\nbbb\ncccc\n
line.split(\n)

line.splitlines()


String Method Basics

mystr=xxxSPAMxxx
mystr.find(SPAM)

mystr.replace(xxx, aa)

int --> string
int("42")
eval("42")

string --> int
str(42)
repr(42)

var formatting
(%d % 42)


File Operation Basics

open(file).read # return string containing all
open(file).read(N)

open(file).readlines() # read into strings list
open(file).readline() # read next line


filename=open(spam, w)
filename.write(spam*5 +\n)


Platform and Version
sys.platform
sys.maxsize
sys.version


sys.path
sys.path.append(rC:\mydir)  # only temporary settings

Administrative Tools
os.getpid()
os.getcwd()
os.chdir(rC:\Uses)
os.getcwd()


Common os.path Tools

os.path.isdir(rC:\Users)

os.path.isfile(rC:\Users)

os.path.exists(rC:\Users)

os.path.getsize(rC:\Users)


os.path.split(rC:\Users\a.dat) # (‘C:\\Users‘,‘a.dat‘)
os.path.join(rC:Users, a.dat)

os.path.dirname(rC:\Users\a.dat)
os.path.basename(rC:\Users\a.dat)


os.path.splitext(rC:\Users\a.dat) # (‘C:\\Users\a\‘,‘dat‘)

os.path.abspath(‘‘)
os.path.abspath(..)


Running Shell Commands from Scripts

os.system #just run the script
os.popen  #connects to its input or output streams

listing=os.popen(dir /B).readlines() # list
listings

text=os.popen(dir /B).read()  # string


Recently, subporcess can achive the same power of os.system & os.popen


import subprocess

subprocess.call(dir /B) # == os.system(‘dir /B‘)
subprocess.call(dir /B, shell=True) #alternative way to run bulit-in function


#like the popen() funciton code
pipe=subprocess.Popen(dir /B, stdout=suprocess.PIPE)
pipe.communicte() #output
pipe.returncode #0 or 1 to indicate whether running is sucessful


#alternative

pipe=subprocess(dir /B, stdout=subprocess.PIPE).communicate()[0]

pipe.wait() # 0 or 1 to indicate whether running is successful


#Notive: os.system & os.popen: start a brand new, independent programm running or your operating system



Shell Command Limitations
os.startfile(a.html/b.doc/c.oy) # open file with whatever program is listed in the windows registry for the file tyoe
Programming Python - 2. System Tools

Programming Python - 2. System Tools,布布扣,bubuko.com

Programming Python - 2. System Tools

上一篇:mac 下安装python pil


下一篇:python三重引号编写多行字符串块