【问题标题】:how to call multiple bash functions using | in python如何使用 | 调用多个 bash 函数在蟒蛇
【发布时间】:2012-03-25 10:43:40
【问题描述】:

我正在使用仅在 bash 中工作的科学软件(称为 vasp),并使用 Python 创建一个脚本,该脚本将为我进行多次运行。当我使用 subprocess.check_call 正常调用该函数时,它工作正常,但是当我添加 '| tee tee_output' 它不起作用。

subprocess.check_call('vasp') #this works
subprocess.check_call('vasp | tee tee_output') #this doesn't

我完全不喜欢 python 和编程。

【问题讨论】:

    标签: python bash call subprocess


    【解决方案1】:

    您可以在文档中找到更多信息: http://docs.python.org/library/pipes.html

    只需将更多字符串附加到t 对象

    【讨论】:

      【解决方案2】:

      不要使用 shell=True,它有很多安全漏洞。而是做这样的事情

      cmd1 = ['vasp']
      cmd2 = ['tee', 'tee_output']
      
      runcmd = subprocess.Popen(cmd1, stdout=subprocess.PIPE)
      runcmd2 = subprocess.Popen(cmd2, stdin=runcmd.stdout, stdout=subprocess.PIPE)
      
      runcmd2.communicate()
      

      我知道它更长,但它更安全。

      【讨论】:

        【解决方案3】:

        你可以这样做:

        vasp = subprocess.Popen('vasp', stdout=subprocess.PIPE)
        subprocess.check_call(('tee', 'tee_output'), stdin=vasp.stdout)
        

        这通常比使用shell=True 更安全,尤其是在您无法信任输入的情况下。

        注意check_call 将检查tee 的返回码,而不是vasp,以查看它是否应该引发CalledProcessError。 (shell=True 方法也会这样做,因为这与 shell 管道的行为相匹配。)如果需要,您可以通过调用 vasp.poll() 自己检查 vasp 的返回码。 (另一种方法不允许您这样做。)

        【讨论】:

          【解决方案4】:

          试试这个。它通过 shell 执行命令(作为字符串传递),而不是直接执行命令。 (相当于使用-c 标志调用shell 本身,即Popen(['/bin/sh', '-c', args[0], args[1], ...])):

          subprocess.check_call('vasp | tee tee_output', shell=True)
          

          但请注意docs 中有关此方法的警告。

          【讨论】:

          • @user1255726:它executes the command using a shell
          • @user1255726,我相信你的话,你的软件“只能在 bash 中运行”。如果这实际上不是真的,那么出于安全原因,其他答案之一会更可取。如果是这样,请告诉我。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-02-14
          • 2022-06-17
          • 1970-01-01
          • 2017-05-03
          • 2019-05-28
          • 1970-01-01
          • 2018-01-26
          相关资源
          最近更新 更多