zoukankan      html  css  js  c++  java
  • python标准库sys模块常用函数

    一、stdin:从标准输入读入数据

    script.py

    import sys
    text = sys.stdin.read()
    words = text.split()
    for i in words:
        print i

    cat source.txt | script.py | sort

    二、argv:获取程序外部向程序传递的参数

    script.py

    import sys
    print sys.argv[0]
    print sys.argv[1]

    python script.py arg1 arg2

    三、exit():退出当前进程

    scrpit.py

    import sys
    
    def exitfunc(value):
        print value
        sys.exit(0)
    
    print "hello"
    
    try:
        sys.exit(1)
    except SystemExit,value:
        exitfunc(value)
    
    print "come?"

    python script.py

    四、stdout

    这个有点复杂

    首先介绍一下stdout与print 的区别

    print 将你需要的内容打印到了控制台,然后追加了一个换行符

    print 会调用 sys.stdout 的 write 方法

    下边两行结果是一样的:

    sys.stdout.write('hello'+'
    ')
    print 'hello'

    sys.stdout指向控制台,如果将文件对象的引用赋值给sys.stdout,那么就会输出到文件。如果输出到文件之后还想在控制台输出内容,那么应该将控制台的对象引用保存下来。

    # -*- coding = UTF-8 -*-
    import sys
    f_handler = open('out.log','w')
    __console__ = sys.stdout
    sys.stdout = f_handler
    print 'hello'#这一行将会输出到文件,和调用文件的write方法相同
    sys.stdout = __console__
    print 'hello'#这一行输出到控制台

     未完待续……

  • 相关阅读:
    LeetCode5654. 盒子中小球的最大数量
    LeetCode40. 组合总和 II
    LeetCode39. 组合总和
    LeetCode17. 电话号码的字母组合
    Leetcode216. 组合总和 III
    eclipse相关使用
    matlab符号的含义
    matlab矩阵相关的笔记
    vi编辑器
    Linux 环境变量
  • 原文地址:https://www.cnblogs.com/guosq/p/6515935.html
Copyright © 2011-2022 走看看