zoukankan      html  css  js  c++  java
  • subprocess使用,进入到某个目录下执行shell命令

    subprocess是用来fork一个子进程的。这个子进程可以运行一个外部程序。

    函数:

    • subprocess.call()
    • subprocess.check_output()
    • subprocess.check_call()

    这三个函数都调用Popen函数:因此Popen类的初始化函数的入参,都可以通过被上面三个函数使用

    def check_output(*popenargs, **kwargs):
    r"""Run command with arguments and return its output as a byte string.

    If the exit code was non-zero it raises a CalledProcessError. The
    CalledProcessError object will have the return code in the returncode
    attribute and output in the output attribute.

    The arguments are the same as for the Popen constructor. Example:

    >>> check_output(["ls", "-l", "/dev/null"])
    'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null '

    The stdout argument is not allowed as it is used internally.
    To capture standard error in the result, use stderr=STDOUT.

    >>> check_output(["/bin/sh", "-c",
    ... "ls -l non_existent_file ; exit 0"],
    ... stderr=STDOUT)
    'ls: non_existent_file: No such file or directory '
    """
    if 'stdout' in kwargs:
    raise ValueError('stdout argument not allowed, it will be overridden.')
    process = Popen(stdout=PIPE, *popenargs, **kwargs)
    class Popen(object):
    _child_created = False # Set here since __del__ checks it

    def __init__(self, args, bufsize=0, executable=None,
    stdin=None, stdout=None, stderr=None,
    preexec_fn=None, close_fds=False, shell=False,
    cwd=None, env=None, universal_newlines=False,
    startupinfo=None, creationflags=0):

    举例:app_module_list = subprocess.check_output("grep '[INFO] cn.tong' dependency.log | awk '{print $2}' | awk -F':' '{print $2}'", shell=True, cwd=dir)

    进入到目录dir后执行shell命令:grep '[INFO] cn.tong' dependency.log | awk '{print $2}' | awk -F':' '{print $2}',标准输出stdout赋值给app_module_list

    参考:https://blog.csdn.net/bitcarmanlee/article/details/51622263

  • 相关阅读:
    python第四篇:linux命令行总结 + 自动备份Python程序
    mount挂载相关指令
    TiDB配置HAProxy负载均衡
    NewSQL 介绍
    mysql 主从搭建
    MySQL 双主问题集
    MySQL 测试工具(基准测试、压力测试)
    分布式 NewSQL 对比
    (转载)MySQL数据库的几种常见高可用方案
    MySQL 大表备份、改表
  • 原文地址:https://www.cnblogs.com/shengulong/p/9643166.html
Copyright © 2011-2022 走看看