代码之家  ›  专栏  ›  技术社区  ›  michele

python popen命令。等待命令完成

  •  61
  • michele  · 技术社区  · 14 年前

    我有一个脚本,在其中我用popen启动一个shell命令。 问题是,脚本不会等到popen命令完成后立即继续执行。

    om_points = os.popen(command, "w")
    .....
    

    如何告诉我的python脚本等待shell命令完成?

    5 回复  |  直到 6 年前
        1
  •  85
  •   Amir Hossein Baghernezad    7 年前

    根据脚本的工作方式,有两个选项。如果您希望命令在执行时阻塞,而不执行任何操作,则只需使用 subprocess.call .

    #start and block until done
    subprocess.call([data["om_points"], ">", diz['d']+"/points.xml"])
    

    如果你想在执行的时候做一些事情,或者把事情反馈给 stdin ,你可以使用 communicate popen 打电话。

    #start and process things, then wait
    p = subprocess.Popen([data["om_points"], ">", diz['d']+"/points.xml"])
    print "Happens while running"
    p.communicate() #now wait plus that you can send commands to process
    

    如文件所述, wait 会死锁,所以通信是明智的。

        2
  •  14
  •   Touchstone    8 年前

    你可以使用 subprocess 为了达到这个目的。

    import subprocess
    
    #This command could have multiple commands separated by a new line \n
    some_command = "export PATH=$PATH://server.sample.mo/app/bin \n customupload abc.txt"
    
    p = subprocess.Popen(some_command, stdout=subprocess.PIPE, shell=True)
    
    (output, err) = p.communicate()  
    
    #This makes the wait possible
    p_status = p.wait()
    
    #This will give you the output of the command being executed
    print "Command output: " + output
    
        3
  •  5
  •   Olivier Verdier    14 年前

    你要找的是 wait 方法。

        4
  •  1
  •   simibac    6 年前

    wait() 对我来说很好。子流程p1、p2和p3同时执行。因此,所有进程都在3秒后完成。

    import subprocess
    
    processes = []
    
    p1 = subprocess.Popen("sleep 3", stdout=subprocess.PIPE, shell=True)
    p2 = subprocess.Popen("sleep 3", stdout=subprocess.PIPE, shell=True)
    p3 = subprocess.Popen("sleep 3", stdout=subprocess.PIPE, shell=True)
    
    processes.append(p1)
    processes.append(p2)
    processes.append(p3)
    
    for p in processes:
        if p.wait() != 0:
            print("There was an error")
    
    print("all processed finished")
    
        5
  •  0
  •   Azsgy    6 年前

    让你试图传递的命令

    os.system('x')
    

    然后你把它藏起来

    t = os.system('x')
    

    现在,python将等待命令行的输出,以便将其分配给变量 t .