在涉及子流程时,使用Python复制两个特定字符串之间的行

时间:2018-03-21 23:18:20

标签: python subprocess

我想将特定的代码行(两行中的代码)从file1.v附加到file2.sv

我试图在子进程模块的帮助下从python运行外部perl脚本。这个外部perl脚本创建" file2.sv"为了我。 file1.v已经存在。

我的问题是file2.sv是由perl脚本成功创建的,但代码我试图从file1.v向file2.sv附加行无法正常工作

以下是代码:

pipe = subprocess.Popen(
    ["Verilog.pl", "file1.v", "file2.sv", "0", "SystemVerilog", "SV","0"], stdin=subprocess.PIPE)

with open("file1.v","r") as rf_VamsModel, open("file2.sv", "a") as wf_sytemVerilogFile:
    copy = False
    for line in rf_VamsModel:
        if line.strip() == "//Start of functional specification here":
            copy = True
        elif line.strip() == "//End of functional specification here":
            copy = False
        elif copy:
            print("line test2={}".format(line))
            wf_sytemVerilogFile.write(line)

是否因为subprocess.Popen和文件追加进程并行执行?

1 个答案:

答案 0 :(得分:1)

Popen构造函数启动一个进程,但它不会在返回之前等待它完成。在perl脚本完成写入之前,您可能会尝试读取和写入这两个文件。

您可以通过调用wait()

等待perl脚本完成
process = subprocess.Popen(...)
process.wait()