【问题标题】:How to execute shell command get the output and pwd after the command in Python如何在Python中执行shell命令获取命令后的输出和密码
【发布时间】:2012-06-15 09:48:56
【问题描述】:

如何执行shell命令,可以像bash命令行中的普通命令一样复杂,执行后获取该命令的输出和pwd?

我用过这样的函数:

import subprocess as sub

def execv(command, path):
    p = sub.Popen(['/bin/bash', '-c', command],
                    stdout=sub.PIPE, stderr=sub.STDOUT, cwd=path)
    return p.stdout.read()[:-1]

我检查用户是否使用cd 命令,但是当用户使用符号链接到 cd 或其他奇怪的方式来更改目录时,这将不起作用。

我需要一本包含{'cwd': '<NEW PATH>', 'result': '<COMMAND OUTPUT>'}的字典

【问题讨论】:

    标签: python bash shell subprocess pwd


    【解决方案1】:

    如果你使用subprocess.Popen,你应该得到一个管道对象,你可以使用communicate() 来获取命令输出,并使用.pid() 来获取进程ID。如果您找不到通过 pid 获取进程当前工作目录的方法,我会真的感到惊讶...

    例如:http://www.cyberciti.biz/tips/linux-report-current-working-directory-of-process.html

    【讨论】:

    • 我试试,有 /proc//cwd 代码需要检查的目录,它可以使用 lsfile (并解析结果)但是当代码执行这些命令 cwd 不再可读,因为进程已结束。所以你需要在执行命令后添加 sleep 命令。最好只运行 pwd。
    【解决方案2】:

    获取带有最终 cwd 的任意 shell 命令的输出(假设 cwd 中没有换行符):

    from subprocess import check_output
    
    def command_output_and_cwd(command, path):
        lines = check_output(command + "; pwd", shell=True, cwd=path).splitlines()
        return dict(cwd=lines[-1], stdout=b"\n".join(lines[:-1]))
    

    【讨论】:

      【解决方案3】:

      我将标准输出重定向到 pwd 命令的标准错误。如果 stdout 为空且 stderr 不是路径,则 stderr 是命令错误

      import subprocess as sub
      
      def execv(command, path):
          command = 'cd %s && %s && pwd 1>&2' % (path, command)
          proc = sub.Popen(['/bin/bash', '-c', command],
                           stdout=sub.PIPE, stderr=sub.PIPE)
          stderr = proc.stderr.read()[:-1]
          stdout = proc.stdout.read()[:-1]
          if stdout == '' and not os.path.exists(stderr):
              raise Exception(stderr)
          return {
              "cwd": stderr,
              "stdout": stdout
          }
      

      更新:这里是更好的实现(使用 pwd 的最后一行,不要使用 stderr)

      def execv(command, path):
          command = 'cd %s && %s 2>&1;pwd' % (path, command)
          proc = sub.Popen(['/bin/bash', '-c', command],
                           env={'TERM':'linux'},
                           stdout=sub.PIPE)
          stdout = proc.stdout.read()
          if len(stdout) > 1 and stdout[-1] == '\n':
              stdout = stdout[:-1]
          lines = stdout.split('\n')
          cwd = lines[-1]
          stdout = '\n'.join(lines[:-1])
          return {
              "cwd": cwd,
              "stdout": man_to_ansi(stdout)
          }
      

      【讨论】:

        猜你喜欢
        • 2020-03-25
        • 2014-06-29
        • 2012-10-08
        • 1970-01-01
        • 2019-02-18
        • 2021-05-15
        • 1970-01-01
        • 2013-08-21
        • 1970-01-01
        相关资源
        最近更新 更多