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