子流程调用中的变量替换

时间:2018-06-22 19:15:18

标签: python python-2.7

我需要使用子进程通过一些替换来运行此bash命令。 server.txt包含服务器名称列表,此脚本必须在多个服务器上运行,并且输出应重定向到bash命令中的文件。请帮助。

BASH命令:

ssh server1 "cat /home/pxh07/python/list| tail -n +2"
#!/usr/bin/env python
import subprocess
import commands
import sys
import os
from subprocess import Popen, PIPE, STDOUT
cmd = "cat /home/user1/python/list| tail -n +2 >  data.out"
SSH = "ssh "
fh = open('server.txt')
for server_name in fh:
  subprocess.call(SSH + server_name + cmd,shell=True)
fh.close()

1 个答案:

答案 0 :(得分:0)

如果要由子进程运行命令输出,则仅在命令成功运行而没有任何错误时执行此操作

command = subprocess.Popen ('command', shell=True, stdout=subprocess.PIPE,stderr=subprocess.STDOUT)

ans,err = command.communicate()
subprocess.Popen('kill '+str(command.pid),shell=True)

如果您想通过完整执行来获取命令输出而没有错误或者超时时间到期,请执行此操作

command = subprocess.Popen ("command", shell=True, stdout=subprocess.PIPE,stderr=subprocess.STDOUT, stdin=subprocess.PIPE)
command.stdin.write ("input for your command") // optional 
command.stdin.close ()
timeout = 4 // some timeout
ans,time_out = getO(command,timeout)



def getO(command,timeout):  
    poll_obj = select.poll()
    poll_obj.register(command.stdout, select.POLLIN)
    buflimit = 512000 // set as Ideal buffer limit
    idealbuffer = 1
    buf = 0
    ans =''
    start = time.time()

    while buf <= buflimit and start + timeout > time.time() : 
        poll_result = poll_obj.poll(0)
        if poll_result:
            ans+= command.stdout.read(idealbuffer)
            buf+=idealbuffer

    return ans