zoukankan      html  css  js  c++  java
  • python os模块sys模块常用方法

    官方文档看这里 https://docs.python.org/3.5/library/os.html

    http://www.cnblogs.com/wupeiqi/articles/5501365.html

    os.path.exists(file) 如果file存在于当前目录下,返回True,否则返回False

    os.path.abspath(file) 返回file的绝对路径

    os.path.dirname(file) 返回file的上级目录名

    sys.path.append(path) 添加path到环境变量

    os.system(command)

    def system(*args, **kwargs): # real signature unknown
        """ Execute the command in a subshell. """
        pass
    View Code

    Execute the command (a string) in a subshell. 系统命令如果本身就会打印结果,那么你会在屏幕上看到结果。返回值是进程的退出状态,若成功执行,则返回值为0,若有报错,返回值为错误代码。

    os.popen(command[, mode[, bufsize]])

    # Supply os.popen()
    def popen(cmd, mode="r", buffering=-1):
        if not isinstance(cmd, str):
            raise TypeError("invalid cmd type (%s, expected string)" % type(cmd))
        if mode not in ("r", "w"):
            raise ValueError("invalid mode %r" % mode)
        if buffering == 0 or buffering is None:
            raise ValueError("popen() does not support unbuffered streams")
        import subprocess, io
        if mode == "r":
            proc = subprocess.Popen(cmd,
                                    shell=True,
                                    stdout=subprocess.PIPE,
                                    bufsize=buffering)
            return _wrap_close(io.TextIOWrapper(proc.stdout), proc)
        else:
            proc = subprocess.Popen(cmd,
                                    shell=True,
                                    stdin=subprocess.PIPE,
                                    bufsize=buffering)
            return _wrap_close(io.TextIOWrapper(proc.stdin), proc)
    View Code

    执行系统命令,执行结果写到一个临时文件里面,返回值是这个打开的文件对象。mode默认值为r,即默认以只读方式打开文件;buffersize默认是系统缓冲区大小(buffer缓冲,此概念适用于磁盘写数据;cache缓存,此概念适用于磁盘读数据)。

    既然返回的是一个文件对象,那么接下来可以理解os.popen().read(),是把这个文件对象中的内容读出来,返回值就是文件中的内容。

     os.path.exists('文件名')

    判断文件是否存在,存在返回True,不存在返回False

    def mkdir(*args, **kwargs): # real signature unknown
    """
    Create a directory.

    If dir_fd is not None, it should be a file descriptor open to a directory,
    and path should be relative; path will then be relative to that directory.
    dir_fd may not be implemented on your platform.
    If it is unavailable, using it will raise a NotImplementedError.

    The mode argument is ignored on Windows.
    """
    pass
  • 相关阅读:
    MySQL5.7版本单节点大数据量迁移到PXC8.0版本集群全记录3
    19c上ADG主库sys密码修改会影响备库同步吗?
    MySQL中sql_mode的设置
    [自制工具]批量后台更新统计信息
    openssl加解密实战
    [自制工具]简便易用的ADDM报告生成工具
    MySQL5.7版本单节点大数据量迁移到PXC8.0版本集群全记录2
    MySQL5.7版本单节点大数据量迁移到PXC8.0版本集群全记录1
    Windows11如何设置经典的右键菜单
    MVC3过滤器实现多语言
  • 原文地址:https://www.cnblogs.com/huamingao/p/5812803.html
Copyright © 2011-2022 走看看