Programming Python - 2. System Tools -2.3 Script Execution Context

 

#whereami.py

import os, sys
print('my os.getcwd =>', os.getcwd())
print('my sys.path =>', sys.path) # show the first 6 import paths, no brace after sys.path
input() # waif for keypress if clicked

 

#test argv

import sys
print(sys.argv)


#testargv2.py
#collect command line options 

def getopts(argv):
    opts={}
    while argv:
        if argv[0][0]=='-':
            opts[argv[0]]=argv[1]
            argv=argv[2:]

        else:
            argv=argv[1:]

    return opts


if __name__ == '__main__':
    from sys import argv
    myargs=getopts(argv)
    
    if '-i' in myargs:
        print(myargs['-i'])

    print(myargs)

 

 

#fetching shell variables
import os
print('setenv...', end=' ')
print(os.environ['USER'])

os.environ['USER']='brain'

os.system('python echoenv.py')
print(os.popen('python echoe.py').read())


#Fetching shell variables

import os
os.environ.keys()

list(os.environ.keys())


import sys
for f in (sys.stdin, sys.stdout, sys.stderr): print(f)


import os
pipe=os.popen('python hello.py') #default is 'r'
pipe.read()

print(pipe.close())


pipe=os.popen('python hello.py', 'w')
pipe.write('hello world')
pipe.close()
open('hello.py').read()

 

 

#interact
def interact():
    print('hello stream world')

    while True:
        try:
            reply=input('enter a number >')
        except EOFError:
            break
        else:
            num=int(reply)
            print('%d square is %d' %(num, num**2))
    print ('bye')


if __name__=='__main__':
    interact()

 

#adder.py

import sys
sum=0
while True:
    try:
        line=input()
    except EOFError:
        break

    else:
        sum+=int(line)

print(sum)


#adder2.py
import sys 
sum=0
while True:
    line=sys.stdin.readline()
    if not line: break
    sum+=int(line)
print(sum)


#adder3.py
import sys
sum=0
for line in sys.stdin: sum+=int(line)
print(sum)

    

 

#sorter.py
import sys
lines=sys.stdin.readlines()
lines.sort()

for line in lines: print(line, end='')

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2014-03-02 13:08  yjjsdu  阅读(198)  评论(0)    收藏  举报