【问题标题】:Using variables inside subprocess.popen in python在 python 中使用 subprocess.popen 中的变量
【发布时间】:2017-11-27 01:19:06
【问题描述】:

大家好, 我是 python 新手。 我正在尝试在 python 中执行 shell 命令

shell命令的语法是这样的 --> programme.sh -ip -hostname --old_ip --old_host

这是我的python代码

  import socket
 import subprocess
 from subprocess import Popen, PIPE, STDOUT


   class Hosts:
   returncode = 0
   hostname = socket.gethostname()
ip = socket.gethostbyname(socket.gethostname())
# print(hostname)
def __init__(self):
    self.h = socket.gethostname()
    self.n = socket.gethostbyname(socket.gethostname())

def changeaddr(self):
     a=Hosts.hostname
     cmd='programme.sh -host a -ip Hosts.ip  -host_old <old host name> -host_ip x.x.x.x'
     cmd_new='programme.sh --continue'
     p=Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True )
     output=str(p.stdout.read())
     #print(output)
     status=output.find("error")
     if (status != -1):
       print("error encountered")
     else:
       p_new=Popen(cmd_new, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True )
       final_output=str(p_new.stdout.read())
       print(final_output)
      if __name__ == "__main__":
         h=Hosts()
         h.changeaddr()

这里的问题是在 cmd 内部,变量 a 和 Hosts.ip 没有插入到它们的值并且被视为 a 和 Hosts.ip only ,导致 shell 命令失败

请教我如何解决这个问题

【问题讨论】:

    标签: python-3.x subprocess


    【解决方案1】:

    您必须确保 cmd 字符串具有正确的值:

    cmd='programme.sh -host ' + a + ' -ip ' + Hosts.ip + ' -host_old <old host name> -host_ip x.x.x.x'
    

    【讨论】:

    猜你喜欢
    • 2014-09-02
    • 1970-01-01
    • 2016-04-24
    • 1970-01-01
    • 1970-01-01
    • 2018-06-17
    • 2012-04-06
    • 1970-01-01
    • 2011-07-07
    相关资源
    最近更新 更多