• 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

  • 相关阅读:
    【转】忘记密码功能的安全实现(邮件方式)
    windows7下安装gem包---bcrypt-ruby
    Ruby中的%表示法
    ruby中特殊的全局变量
    rails中一个窗体多个模型——fields_for
    【转】深刻理解render 和 redirect_to
    UML核心元素--分析类
    UML核心元素--包
    UML核心元素--边界
    UML核心元素--用例
  • 原文地址:https://www.cnblogs.com/shengulong/p/9643166.html
Copyright © 2020-2023  润新知