1,sys.stdin和sys.stdout用在命令行中执行脚本或在交互模式下控制输入输出(在jupyter notebook中不好使)。
2,sys.stdin输入单行:
n = sys.stdin.readline().strip()
2.1 n为接受到的标准输入的值,类型为字符串(str);
2.2 在输入为2 3的情况下,仍为字符串,可以用n = sys.stdin.readline().strip().split(’ ')将字符串转化为列表;
2.3 需要用strip()将末尾的换行符(\n)去掉(用n = raw_input()接受标准输入时,默认没有末尾的换行符)
3,sys.stdin接受多行输入:
strN = []
for line in sys.stdin:
strN.append(line.strip().split(' '))
print strN, type(strN)
程序输入为:
1 2 3
4 5 6
3 4
(分3行输入,每行输入完都敲了回车)
输出为
[[‘1’, ‘2’, ‘3’], [‘4’, ‘5’, ‘6’], [‘3’, ‘4’]] <type ‘list’>
退出此标准模式用Ctrl + d(貌似无法在程序中让其自发终止输入)
4,sys.stdout
sys.stdout.write(‘hello world’+’\n’)
print ‘hello world’
上面两行代码等价,print会调用sys.stdout.write
5,原始的 sys.stdout 指向控制台,可以一个文件句柄赋值给它,使print直接将结果写到文件中
f_handler=open('out.log', 'w')
sys.stdout=f_handler
print 'hello'
上述的代码将生成out.log文件,文件内容为hello