首页 > 编程语言 > 详细

Programming Python - 2. System Tools

时间:2014-02-27 21:11:36      阅读:579      评论:0      收藏:0      [点我收藏+]
bubuko.com,布布扣
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(r‘C:\mydir‘)  # only temporary settings

Administrative Tools
os.getpid()
os.getcwd()
os.chdir(r‘C:\Uses‘)
os.getcwd()


Common os.path Tools

os.path.isdir(r‘C:\Users‘)

os.path.isfile(r‘C:\Users‘)

os.path.exists(r‘C:\Users‘)

os.path.getsize(r‘C:\Users‘)


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

os.path.dirname(r‘C:\Users\a.dat‘)
os.path.basename(r‘C:\Users\a.dat‘)


os.path.splitext(r‘C:\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
bubuko.com,布布扣

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

Programming Python - 2. System Tools

原文:http://www.cnblogs.com/jsquare/p/3570489.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!