예제 #1
0
def run():
    print('os.name', os.name)
    print('os.device_encoding(0)', os.device_encoding(0))
    print('os.device_encoding(1)', os.device_encoding(1))
    print('os.device_encoding(2)', os.device_encoding(2))
    print('os.getcwd()', os.getcwd())
    #~ print('os.getlogin()', os.getlogin())
    print('os.getpid()', os.getpid())
    print('os.getppid()', os.getppid())
    print('os.get_exec_path()', os.get_exec_path())
    print('os.supports_bytes_environ', os.supports_bytes_environ)
    print('os.times()', os.times())
    width = max(len(x) for x in os.environ)
    for key in os.environ:
        print('{key:<{width}}= {}'.format(os.environ[key], **locals()))
예제 #2
0
    def output(self, timeout=None):
        if self.dry_run:
            return 0, None, None
        if self.proc is None:
            if self.verbose:
                print('  invalid process')
            return 1, None, None
        if self.pipe[1] != Proc.PIPE and self.pipe[2] != Proc.PIPE:
            if self.verbose:
                print('  output is not redirected')
            return 0, None, None
        #
        try:
            out, err = self.proc.communicate(timeout=timeout)
            status = self.proc.returncode
        except subprocess.TimeoutExpired:
            self.proc.kill()
            out, err = self.proc.communicate()
            status = Proc.ETIME
        encoding = os.device_encoding(1)
        if encoding is None:
            encoding = 'UTF-8' if Util.is_unix() else 'cp932'
        out = out.decode(encoding) if out else None
        err = err.decode(encoding) if err else None

        # cleanup
        self.__close(self.fd[0], self.pipe[0])
        self.__close(self.fd[1], self.pipe[1])
        self.__close(self.fd[2], self.pipe[2])
        self.__revive_envirnment(self.org_env)

        # only lower 16 bits are meaningful
        self.status = self.__s16(status)
        return self.status, out, err
예제 #3
0
 def __init__(
     self,
     filename: str,
     mode: str = "w",
     encoding: Optional[str] = None,
     **kwargs: Dict[str, Any],
 ) -> None:
     super().__init__(filename)
     if not isinstance(mode, str):
         raise TypeError(f"Invalid mode: {mode}")
     if not set(mode) <= set("xrwabt+"):
         raise ValueError(f"Invalid mode: {mode}")
     if "x" in mode or "w" in mode or "a" in mode:
         self._writable = True
         self._readable = False
     elif "r" in mode:
         self._check_readable()
     elif "+" in mode:
         self._readable = True
         self._writable = True
     self.maxbytes = kwargs.get("maxbytes", -1)
     self.maxlines = kwargs.get("maxlines", -1)
     self.ignore_linebreak = kwargs.get("ignore_linebreak", True)
     if self.ignore_linebreak:
         self.maxlines -= 1  # type: ignore
     if self.maxbytes > 0 or self.maxlines > 0:  # type: ignore
         mode = "a"
     self.mode = mode
     if encoding is None:
         encoding = os.device_encoding(0)
     self.encoding = encoding
     self._closed = False
     self.idx = self.index
     self.open()
예제 #4
0
def test_device_encoding():
    encoding = os.device_encoding(sys.stderr.fileno())
    if not encoding:
        skip("Requires a result from "
             "os.device_encoding(sys.stderr.fileno())")
    
    f = _io.TextIOWrapper(sys.stderr.buffer)
    assert f.encoding == encoding
예제 #5
0
파일: test_textio.py 프로젝트: Qointum/pypy
 def test_device_encoding(self):
     import os
     import sys
     encoding = os.device_encoding(sys.stderr.fileno())
     if not encoding:
         skip("Requires a result from "
              "os.device_encoding(sys.stderr.fileno())")
     import _io
     f = _io.TextIOWrapper(sys.stderr.buffer)
     assert f.encoding == encoding
예제 #6
0
def run_command(command, path):
    global result
    global path_to_file

    path_to_file = path
    encoding = os.device_encoding(1) or ctypes.windll.kernel32.GetOEMCP()
    result = subprocess.check_output(command, encoding=encoding)

    # создание файла
    Path(path).expanduser().write_text(result)
예제 #7
0
 def __init__(self,
              buffer,
              encoding=None,
              errors=None,
              newline=None,
              line_buffering=False,
              write_through=False):
     if newline is not None and not isinstance(newline, str):
         raise TypeError('illegal newline type: %r' % (type(newline), ))
     if newline not in (None, '', '\n', '\r', '\r\n'):
         raise ValueError('illegal newline value: %r' % (newline, ))
     if encoding is None:
         try:
             encoding = os.device_encoding(buffer.fileno())
         except (AttributeError, UnsupportedOperation):
             pass
         if encoding is None:
             try:
                 import locale
             except ImportError:
                 encoding = 'ascii'
             encoding = locale.getpreferredencoding(False)
     if not isinstance(encoding, str):
         raise ValueError('invalid encoding: %r' % encoding)
     if not codecs.lookup(encoding)._is_text_encoding:
         msg = '%r is not a text encoding; use codecs.open() to handle arbitrary codecs'
         raise LookupError(msg % encoding)
     if errors is None:
         errors = 'strict'
     elif not isinstance(errors, str):
         raise ValueError('invalid errors: %r' % errors)
     self._buffer = buffer
     self._line_buffering = line_buffering
     self._encoding = encoding
     self._errors = errors
     self._readuniversal = not newline
     self._readtranslate = newline is None
     self._readnl = newline
     self._writetranslate = newline != ''
     self._writenl = newline or os.linesep
     self._encoder = None
     self._decoder = None
     self._decoded_chars = ''
     self._decoded_chars_used = 0
     self._snapshot = None
     self._seekable = self._telling = self.buffer.seekable()
     self._has_read1 = hasattr(self.buffer, 'read1')
     self._b2cratio = 0.0
     if self._seekable and self.writable():
         position = self.buffer.tell()
         if position != 0:
             try:
                 self._get_encoder().setstate(0)
             except LookupError:
                 pass
예제 #8
0
    def _determine_encoding(self, encoding: Optional[str]) -> None:

        self.encoding = encoding

        if self.encoding is None and self.text is not None:
            self.encoding = self.text.encoding

        if self.encoding is None and self.fd is not None:
            self.encoding = os.device_encoding(self.fd)

        if self.encoding is None:
            self.encoding = 'utf-8'
예제 #9
0
def run_ex():
    while True:
        in_action = input('ex/com/action/ ')
        if in_action == 'lg':
            print(os.getlogin())
        elif in_action == 'pd':
            print(os.getpid())
        elif in_action == 'de':
            print(os.device_encoding(10))
        elif in_action == 'back':
            break
        else:
            print('command doesnt exist')
    return
예제 #10
0
 def __init__(self, buffer, encoding=None, errors=None, newline=None, line_buffering=False, write_through=False):
     if newline is not None and not isinstance(newline, str):
         raise TypeError('illegal newline type: %r' % (type(newline),))
     if newline not in (None, '', '\n', '\r', '\r\n'):
         raise ValueError('illegal newline value: %r' % (newline,))
     if encoding is None:
         try:
             encoding = os.device_encoding(buffer.fileno())
         except (AttributeError, UnsupportedOperation):
             pass
         if encoding is None:
             try:
                 import locale
             except ImportError:
                 encoding = 'ascii'
             encoding = locale.getpreferredencoding(False)
     if not isinstance(encoding, str):
         raise ValueError('invalid encoding: %r' % encoding)
     if not codecs.lookup(encoding)._is_text_encoding:
         msg = '%r is not a text encoding; use codecs.open() to handle arbitrary codecs'
         raise LookupError(msg % encoding)
     if errors is None:
         errors = 'strict'
     elif not isinstance(errors, str):
         raise ValueError('invalid errors: %r' % errors)
     self._buffer = buffer
     self._line_buffering = line_buffering
     self._encoding = encoding
     self._errors = errors
     self._readuniversal = not newline
     self._readtranslate = newline is None
     self._readnl = newline
     self._writetranslate = newline != ''
     self._writenl = newline or os.linesep
     self._encoder = None
     self._decoder = None
     self._decoded_chars = ''
     self._decoded_chars_used = 0
     self._snapshot = None
     self._seekable = self._telling = self.buffer.seekable()
     self._has_read1 = hasattr(self.buffer, 'read1')
     self._b2cratio = 0.0
     if self._seekable and self.writable():
         position = self.buffer.tell()
         if position != 0:
             try:
                 self._get_encoder().setstate(0)
             except LookupError:
                 pass
예제 #11
0
def command(cmnd, timeout=None):
    proc = subprocess.Popen(cmnd, stdout=PIPE, shell=True)
    try:
        out, err = proc.communicate(timeout=timeout)
        status = proc.returncode
    except subprocess.TimeoutExpired:
        proc.kill()
        out, err = proc.communicate()
        status = 1
    encoding = os.device_encoding(1)
    if encoding is None:
        encoding = 'cp932'
    out = out.decode(encoding) if out else None
    err = err.decode(encoding) if err else None
    return status, out, err
예제 #12
0
	def __system_encoding(self):
		if self.major >= 3:
			encoding = os.device_encoding(1)
		else:
			encoding = sys.stdout.encoding
		#print('os.device_encoding(1) returns [%s]' % encoding)
		if encoding is None:
			stdout_info = str(sys.stdout)
			#print('sys.stdout returns [%s]' % stdout_info)
			m = re.search("encoding='(.+)'", stdout_info)
			if m:
				encoding = m.group(1)
			else:
				encoding = 'utf-8'
				#print('assume %s as default encoding' % encoding)
		#print('encoding: %s' % encoding)
		return encoding
예제 #13
0
 def output(self):
     if self.dry_run:
         return None, None
     if self.proc is None:
         if self.verbose:
             print('  invalid process')
         return None, None
     if self.pipe[1] != Proc.PIPE and self.pipe[2] != Proc.PIPE:
         if self.verbose:
             print('  output is no redirected')
         return None, None
     #
     out, err = self.proc.communicate()
     encoding = os.device_encoding(1)
     if encoding is None:
         encoding = 'UTF-8' if Util.is_unix() else 'cp932'
     out = out.decode(encoding) if out else None
     err = err.decode(encoding) if err else None
     return out, err
예제 #14
0
        async def do_run():
            cmd = ' '.join([self.executable, *self.args, *args])
            self._logger.debug(f'cwd: {Path.cwd()}')
            self._logger.debug(f'cmd: {cmd}')
            if recorder:
                recorder(cmd)
            if not dry_run:
                proc = await asyncio.create_subprocess_exec(
                    self.executable,
                    *self.args, *args,
                    stderr=asyncio.subprocess.PIPE,
                    stdout=stdout)
                out, err = await proc.communicate()

                rc = proc.returncode
                if not always_return and rc:
                    raise ProcessError(err.decode(os.device_encoding(sys.stderr.fileno()) or 'utf-8'))
                return rc, out, err
            else:
                return 0, None, None
예제 #15
0
def output(proc_info):
    proc, pipe = proc_info
    out, err = proc.communicate()
    status = s16(proc.returncode)
    close_pipe(pipe)
    #
    encoding = os.device_encoding(1)
    if encoding is None:
        encoding = 'UTF-8' if is_unix() else 'cp932'
    out = out.decode(encoding) if out else None
    err = err.decode(encoding) if err else None
    #
    if status == 0:
        out = out.split('\n')
        out = list(map(lambda x: x.strip('\r'), out))
    if verbose > 1:
        print('  output: status %d' % status)
        for line in out:
            print('    [%s]' % line)
    return status, out, err
예제 #16
0
def system_exec(cmd: str, who: str = "", what: str = ""):
    """
    execute a system command
    :param cmd: the command to run
    :param who: who is trying to use the command
    :param what: message that replace the full command in log in case of error
    :return: (return code, output lines as list of string)
    """
    import subprocess
    if cmd == "":
        return -1, []
    temp_who = who
    if temp_who == "":
        temp_who = "robot"
    try:
        p = subprocess.run(cmd,
                           stdout=subprocess.PIPE,
                           stderr=subprocess.STDOUT,
                           shell=True)
    except (ValueError, OSError) as err:
        if what == "":
            msg = "ERROR executing " + cmd + ": " + str(err)
        else:
            msg = "ERROR executing " + what + ": " + str(err)
        logger.log_error(temp_who, msg)
        return -2, []
    try:
        enc = device_encoding(1)
        if not enc:
            enc = "ascii"
        lines = p.stdout.decode(enc, errors='ignore').splitlines()
    except Exception as err:
        if what == "":
            msg = "ERROR while decoding return of " + cmd + ": " + str(err)
        else:
            msg = "ERROR while decoding return of " + what + ": " + str(err)
        logger.log_error(temp_who, msg)
        return -3, []
    return p.returncode, lines
예제 #17
0
    def get_host_fingerprint(self, host):
        ping_cmd = self._build_ping_command(host.ip_addr)
        logger.debug(f"Running ping command: {' '.join(ping_cmd)}")

        # If stdout is not connected to a terminal (i.e. redirected to a pipe or file), the result
        # of os.device_encoding(1) will be None. Setting errors="backslashreplace" prevents a crash
        # in this case. See #1175 and #1403 for more information.
        encoding = os.device_encoding(1)
        sub_proc = subprocess.Popen(
            ping_cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            encoding=encoding,
            errors="backslashreplace",
        )

        logger.debug(
            f"Retrieving ping command output using {encoding} encoding")
        output = " ".join(sub_proc.communicate())
        regex_result = self._ttl_regex.search(output)
        if regex_result:
            try:
                ttl = int(regex_result.group(0))
                if ttl <= LINUX_TTL:
                    host.os["type"] = "linux"
                else:  # as far we we know, could also be OSX/BSD but lets handle that when it
                    # comes up.
                    host.os["type"] = "windows"

                host.icmp = True

                return True
            except Exception as exc:
                logger.debug("Error parsing ping fingerprint: %s", exc)

        return False
예제 #18
0
fd = os.open(r"C:\c.obj", os.O_RDWR | os.O_CREAT)
readfd, writefd = os.pipe()  # 打开管道,返回读取,写入 (windows失败)
# fdopen(fd, *args, **kwargs) // 打开  (windews写入失败,读取""字符)
f = os.fdopen(readfd)

os.read(fd, 150)  # 读取
os.write(fd, "String".encode("utf-8"))  # 写入
os.fsync(fd)  # 强行写入
os.ftruncate(fd, 100)  # 裁剪文件
bytes = os.lseek(fd, 10, os.SEEK_SET)  # 设置指针  SEEK_SET(0开始) SEEK_CUR(1当前位置) SEEK_END(2末尾)

fd_temp = os.dup(fd)  # 副本
boolean = os.isatty(fd)  # 是否是tty设备

stat = os.fstat(fd)  # 状态信息
strs = os.device_encoding(fd)  # 返回终端字符编码,非终端None

os.close(fd)  # 关闭
os.closerange(fd, fd)  # 关闭并忽略错误


# === DirEntry ===
for dir in os.scandir():
    strs = dir.name  # 文件名
    strs = dir.path  # 完整路径名
    num = dir.inode()  # inode编号
    boolean = dir.is_dir()  # 是否是文件夹
    boolean = dir.is_file()  # 是否是文件
    boolean = dir.is_symlink()  # 是否是链接
    tups = dir.stat()  # 状态信息的stat_result对象
예제 #19
0
#通过文件描述符改变当前工作目录
#print('改变当前工作目录', os.fchdir(os.open("foo.txt", os.O_RDWR|os.O_CREAT)))

#改变一个文件的访问权限,该文件由参数fd指定,参数mode是Unix下的文件访问权限。
#print(os.fchmod(os.open("foo.txt", os.O_RDWR|os.O_CREAT), stat.S_IREAD))

#修改一个文件的所有权,这个函数修改一个文件的用户ID和用户组ID,该文件由文件描述符fd指定。
#os.fchown(fd, uid, gid)

print('cpu 数量:', os.cpu_count())
print('当前路径:', os.curdir)
print('定义路径:', os.defpath)

# 返回描述终端文件描述符编码的字符串。文件描述符必须附加到终端。 如果设备不是终端,则返回无。
print('文件描述符编码: ',
      os.device_encoding(os.open("foo.txt", os.O_RDWR | os.O_CREAT)))

print('系统变量:', os.environ)

# 打开文件
fd = os.open("f:/foo.txt", os.O_RDWR | os.O_CREAT)
#通过文件描述符 fd 创建一个文件对象,并返回这个文件对象
'''
参数

fd -- 打开的文件的描述符,在Unix下,描述符是一个小整数。
mode -- 可选,和buffersize参数和Python内建的open函数一样,mode参数可以指定『r,w,a,r+,w+,a+,b』等,表示文件的是只读的还是可以读写的,以及打开文件是以二进制还是文本形式打开。这些参数和C语言中的<stdio.h>中fopen函数中指定的mode参数类似。
bufsize -- 可选,指定返回的文件对象是否带缓冲:buffersize=0,表示没有带缓冲;bufsize=1,表示该文件对象是行缓冲的;bufsize=正数,表示使用一个指定大小的缓冲冲,单位为byte,但是这个大小不是精确的;bufsize=负数,表示使用一个系统默认大小的缓冲,对于tty字元设备一般是行缓冲,而对于其他文件则一般是全缓冲。如果这个参数没有制定,则使用系统默认的缓冲设定。
'''
file = os.fdopen(fd, "r", 512)
print(file)
예제 #20
0
def os_func():
    '''
    操作系统模块
        该模块下的方法,对各个版本的兼容不明确,须谨慎使用.
        测试版本: Python:3.6.1   Windows:Windows10,64bit
    '''

    # === 系统 ===
    strs = os.name  # 当前系统: Linux'posix' / Windows'nt' / 'ce' / 'java'
    strs = os.sep  # 分隔符 \\ (windows:\\ linux:/)
    strs = os.pathsep  # path变量分隔符 ; (windows:; linux::)
    strs = os.linesep  # 换行分隔符 \r\n (windows:/r/n linux:\n)
    dics = os.environ  # 查看系统环境变量(字典)
    strs = os.getenv("Path", default=-1)  # 读取环境变量, 没有返回None
    os.putenv("Path", "C:\\python")  # 添加环境变量  (windows无效)
    os.unsetenv("Path")  # 删除环境变量  (windows不可用)
    strs = os.getlogin()  # 当前登录的用户名
    num = os.getpid()  # 当前进程PID
    num = os.system("cmd")  # 执行操作系统命令, 返回0/1(0执行正确;1执行错误)
    strs = os.popen("dir").read()  # 执行系统命令,并去读结果
    tups = os.times()  # 当前进程时间(user用户 / system系统 / children_user子用户(windews=0) / children_system子系统(windews=0) / elapsed过去时间)
    bytes = os.urandom(10)  # n字节用以加密的随机字符
    num = os.cpu_count()  # CUP数量



    # === 进程 ===
    os.abort()  # 结束进程
    # execl(file, *args) / execle / execlp / execlpe / execv / execve / execvp / execvpe // 运行新程序替换当前进程
    os.execl(r"C:\python", 'python', 'hello.py', 'i')  # (windows执行失败)
    os._exit(0)  # 退出
    os.kill(8480, signal.SIGTERM) # (系统) 终止进程(需要导入:signal) SIGINT (终止进程) / SIGTERM (终止进程) / SIGKILL (终止进程) / SIGALRM (闹钟信号)



    # === 文件 / 文件夹 ===
    strs = os.getcwd()  # 当前路径
    bytes = os.getcwdb()  # 当前路径
    os.chdir(r"C:\Windows")  # 切换路径
    strs = os.curdir  # 当前目录 .
    strs = os.pardir  # 上级目录 ..
    strs = os.sep  # 路径分隔符 ('/' or '\\')
    bytes = os.fsencode(r"C:\c.obj")  # (编码) 文件路径字符串转为bytes类型 => b'C:\\c.obj'
    strs = os.fsdecode(b"C:\c.obj")  # (解码) 文件路径转为strs类型 => 'C:\\c.obj'
    # chmod(path, mode, *, dir_fd=None, follow_symlinks=True)
    os.chmod(r"C:\python\hello.py", 777)  # 修改模式
    os.link("file.txt", "file.txt.link")  # 创建硬链接
    os.symlink("file.txt", "file.txt.link")  # 创建软链接 (windows执行失败)
    lists = os.listdir()  # 所有文件和文件夹(列表) ".""..""D:"
    # lstat(path, *, dir_fd=None)
    tups = os.lstat(r"C:\c.obj")  # 状态信息列表
    boolean = os.access(r"C:\c.obj", os.F_OK)   # (文件/文件夹) 权限测试 (mode: F_OK存在? / R_OK可读? / W_OK可写? / X_OK可执行?)
    # scandir(path='.')  // DirEntry迭代器, 文件目录
    lists = os.scandir()
    # st_atime (访问时间) / st_ctime (修改时间) / st_mtime (模式修改时间) / st_size (大小(字节bytes))
    # st_uid (用户ID) / st_gid (用户组ID)
    # st_ino (inode) / st_mode (模式) / st_dev (设备) / st_nlink (硬链接)
    # count = cpu_count() # (系统) CPU线程数(非核数)
    tups = os.stat(".")  # 获取状态信息, 返回stat_result对象
    # utime(path, times=None, *, ns=None, dir_fd=None, follow_symlinks=True) // 更新文件的访问和修改时间
    num = os.utime(r"C:\c.obj")
    # walk(top, topdown=True, onerror=None, followlinks=False) // 根目录(top)遍历目录树,返回迭代器 (dirpath, dirnames[], filenames[]).
    root, dirnames, filenames = os.walk(r"C:\python")

    os.removedirs(r"c:\python")  # 删除多个文件夹 (windews删除多个文件夹失败,单个成功)
    # mkdir(path, mode=0o777, *, dir_fd=None) // 创建单个目录, 文件夹已存在,抛 FileExistsError 异常
    os.mkdir("test")
    # makedirs(name, mode=0o777, exist_ok=False)  // 创建(多个)文件夹
    os.makedirs(r"./t1/t2/t3")
    os.rmdir("test")  # 删除单个目录

    # mknod(path, mode=0o600, device=0, *, dir_fd=None) // 创建空文件 (windows不可用)
    os.mknod("test.txt")
    # remove(path, *, dir_fd=None)
    os.remove("test.txt")  # 删除文件
    # rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None)
    os.rename("text.txt", "file.txt")  # 重命名
    os.renames("text.txt", "file.txt")
    # replace(src, dst, *, src_dir_fd=None, dst_dir_fd=None) // 重命名, 存在则替换
    os.replace("text.txt", "file.txt")
    tups = os.stat(r"text.txt")  # 文件属性



    # === 文件读写 ===
    # open(path, flags, mode=0o777, *, dir_fd=None) // 打开文件 fd:文件描述符
    fd = os.open(r"C:\c.obj", os.O_RDWR | os.O_CREAT)
    readfd, writefd = os.pipe()  # 打开管道,返回读取,写入 (windows失败)
    # fdopen(fd, *args, **kwargs) // 打开  (windews写入失败,读取""字符)
    f = os.fdopen(readfd)

    os.read(fd, 150)  # 读取
    os.write(fd, "String".encode("utf-8"))  # 写入
    os.fsync(fd)  # 强行写入
    os.ftruncate(fd, 100)  # 裁剪文件
    bytes = os.lseek(fd, 10, os.SEEK_SET)  # 设置指针  SEEK_SET(0开始) SEEK_CUR(1当前位置) SEEK_END(2末尾)

    fd_temp = os.dup(fd)  # 副本
    boolean = os.isatty(fd)  # 是否是tty设备

    stat = os.fstat(fd)  # 状态信息
    strs = os.device_encoding(fd)  # 返回终端字符编码,非终端None

    os.close(fd)  # 关闭
    os.closerange(fd, fd)  # 关闭并忽略错误


    # === DirEntry ===
    for dir in os.scandir():
        strs = dir.name  # 文件名
        strs = dir.path  # 完整路径名
        num = dir.inode()  # inode编号
        boolean = dir.is_dir()  # 是否是文件夹
        boolean = dir.is_file()  # 是否是文件
        boolean = dir.is_symlink()  # 是否是链接
        tups = dir.stat()  # 状态信息的stat_result对象
예제 #21
0
    makepath = '/usr/bin'
else:

    def s16(value):
        return -(value & 0b1000000000000000) | (value & 0b0111111111111111)

    cmnd = 'python find_path.py nmake.exe'
    proc = subprocess.Popen(cmnd,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.DEVNULL)
    out, err = proc.communicate()
    status = s16(proc.returncode)
    if status != 0:
        Error(prog).error('can not find "%s" path.' % make)
    #
    encoding = os.device_encoding(1)
    if encoding is None:
        encoding = 'UTF-8' if unix else 'cp932'
    makepath = out.decode(encoding) if out else None
    if makepath is None:
        Error(prog).error('can not decode "%s" path.' % make)
    print('nmake path found: %s' % makepath.replace(os.sep, '/'))

swigpath = '%s/%s' % (srcdir, 'Foundation')
addpath = os.pathsep.join([bindir, swigpath, makepath])

# ----------------------------------------------------------------------
#  Main process
# ----------------------------------------------------------------------
#  オプションの定義
#
import HTML_con
from config_data import CONFIG_SECTIONS, TRACKING_AND_TELEMETRY, BUILTIN_APPS
from regkeys_data import REGKEYS_DICT, ValueEntry

_SCRIPT_PATH = pathlib.WindowsPath(__file__).resolve()
_CWD = _SCRIPT_PATH.parent
_CONFIG_PATH = _CWD.joinpath("config.cfg")
_DOWNLOAD_PATH = pathlib.WindowsPath.home().joinpath(r"Downloads\config.cfg")

_LOGRECORD_FORMAT = "%(asctime)s | %(levelname)-8s | %(message)s"
logging.basicConfig(filename=_CWD.joinpath("logfile.log"),
                    filemode="w",
                    format=_LOGRECORD_FORMAT,
                    level=logging.INFO)

_CODE_PAGE = os.device_encoding(1)


def progressbar(process_name):
    def wrapper(func):
        def wrapped_func(*args, **kwargs):
            animations = cycle("|/—\\")
            t = threading.Thread(target=func, args=args, kwargs=kwargs)
            t.start()
            print(f"{process_name}...", end="  ")
            while t.is_alive():
                t.join(.1)
                print(f"\b{next(animations)}", end="", flush=True)
            print("\bЗавершено.")
            time.sleep(.5)
예제 #23
0
def run_command(command):
    encoding = os.device_encoding(1) or ctypes.windll.kernel32.GetOEMCP()
    out = sp.Popen(command, stdout=sp.PIPE, shell=True)
    result = io.TextIOWrapper(out.stdout, encoding='cp866')

    return result.read()
예제 #24
0
def get_console_encoding() -> str:
    # Find out the console encoding
    return cast(str, os.device_encoding(1))  # '1' is the stdout on windows
#!/usr/bin/env python3
import locale
import os
import sys

envname = "PYTHONIOENCODING"
print("{}:\t{}".format(envname, os.environ.get(envname)))

for set_locale in [False]:
    print("locale({}):\t{}".format(set_locale,
                                   locale.getpreferredencoding(set_locale)))

for streamname in "stdout stderr stdin".split():
    stream = getattr(sys, streamname)
    print("device({}):\t{}".format(streamname,
                                   os.device_encoding(stream.fileno())))
    print("{}.encoding:\t{}".format(streamname, stream.encoding))

for set_locale in [False, True]:
    print("locale({}):\t{}".format(set_locale,
                                   locale.getpreferredencoding(set_locale)))
예제 #26
0
#通过文件描述符改变当前工作目录
#print('改变当前工作目录', os.fchdir(os.open("foo.txt", os.O_RDWR|os.O_CREAT)))

#改变一个文件的访问权限,该文件由参数fd指定,参数mode是Unix下的文件访问权限。
#print(os.fchmod(os.open("foo.txt", os.O_RDWR|os.O_CREAT), stat.S_IREAD))

#修改一个文件的所有权,这个函数修改一个文件的用户ID和用户组ID,该文件由文件描述符fd指定。
#os.fchown(fd, uid, gid)

print('cpu 数量:', os.cpu_count())
print('当前路径:', os.curdir)
print('定义路径:', os.defpath)

# 返回描述终端文件描述符编码的字符串。文件描述符必须附加到终端。 如果设备不是终端,则返回无。
print('文件描述符编码: ', os.device_encoding(os.open("foo.txt", os.O_RDWR|os.O_CREAT)))

print('系统变量:', os.environ)

# 打开文件
fd = os.open("f:/foo.txt", os.O_RDWR|os.O_CREAT)
#通过文件描述符 fd 创建一个文件对象,并返回这个文件对象
'''
参数

fd -- 打开的文件的描述符,在Unix下,描述符是一个小整数。
mode -- 可选,和buffersize参数和Python内建的open函数一样,mode参数可以指定『r,w,a,r+,w+,a+,b』等,表示文件的是只读的还是可以读写的,以及打开文件是以二进制还是文本形式打开。这些参数和C语言中的<stdio.h>中fopen函数中指定的mode参数类似。
bufsize -- 可选,指定返回的文件对象是否带缓冲:buffersize=0,表示没有带缓冲;bufsize=1,表示该文件对象是行缓冲的;bufsize=正数,表示使用一个指定大小的缓冲冲,单位为byte,但是这个大小不是精确的;bufsize=负数,表示使用一个系统默认大小的缓冲,对于tty字元设备一般是行缓冲,而对于其他文件则一般是全缓冲。如果这个参数没有制定,则使用系统默认的缓冲设定。
'''
file = os.fdopen(fd, "r", 512)
print(file)