Python:子进程调用中的替换

时间:2011-11-22 07:01:05

标签: python subprocess

我做for in range(...):,我需要在子进程调用中替换i。我试着这样做:

myStr = "'(insert \"%g\")'" %i
    subprocess.Popen(["emacs", "--batch", "+83:28", "md.mdp", "--eval", 
                      eval("myStr"), "-f", "save-buffer", "--kill"], 
                     stdout=subprocess.PIPE).wait()

并且像这样:

subprocess.Popen(["emacs", "--batch", "+83:28", "md.mdp", "--eval", 
                  "'(insert \"%g\")'" %i, "-f", "save-buffer", "--kill"], 
                 stdout=subprocess.PIPE).wait()

也是这样的:

subprocess.Popen(["emacs", "--batch", "+83:28", "md.mdp", "--eval", 
                  ("'(insert \"%g\")'" %i), "-f", "save-buffer", "--kill"], 
                 stdout=subprocess.PIPE).wait()

但这些都不起作用。你能帮我把它弄好吗?

另外 - 这是真的 - 当system("bash command")不会wait

修改

脚本为给定参数的各种值运行计算机模拟。它为每次运行复制baseData目录,去那里,更改参数文件(插入值),然后运行模拟并返回。

这不会产生错误 - 但也不会在i中插入md.mdp的值:

myStr = "'(insert \"%g\")'" %i
subprocess.Popen(["emacs", "--batch", "+83:28", "md.mdp", "--eval", 
                  myStr, "-f", "save-buffer", "--kill"], 
                 stdout=subprocess.PIPE).wait()

这也没有帮助:

myStr = "'(insert \\\"%g\\\")'" %i

以下变体也不会插入任何内容:

subprocess.Popen(["emacs", "--batch", "+83:28", "md.mdp", "--eval", 
              "'(insert \"%g\")'" %i, "-f", "save-buffer", "--kill"], 
             stdout=subprocess.PIPE).wait()

subprocess.Popen(["emacs", "--batch", "+83:28", "md.mdp", "--eval", 
              ("'(insert \"%g\")'" %i), "-f", "save-buffer", "--kill"], 
             stdout=subprocess.PIPE).wait()

2 个答案:

答案 0 :(得分:1)

我要说问题是你不需要引用insert声明部分。原因是你在shell中使用引号来明确引号之间的字符串作为单个参数传递。

但是,在subprocess.Popen中,您使用的数组执行相同的功能,因此不需要引号。换句话说,在shell中,引号不会传递给正在启动的进程,并且在subprocess.Popen调用中,它们将被传递。

答案 1 :(得分:0)

以下作品:

subprocess.Popen(["emacs", "--batch", "+83:28", "md.mdp", "--eval", 
                 eval("'(insert \"%g\")'" %i), "-f", "save-buffer", "--kill"], 
                 stdout=subprocess.PIPE).wait()

修改1

有些时候你不需要评估:

subprocess.Popen(["grompp", "-f", "%s" %opts.myMdp, "-c", "%s" %opts.myGro,
                 "-p", "%s" %opts.myTop], stdout=subprocess.PIPE).wait()

编辑2

当我'(insert \"%g\")' %i时,它会给出

Traceback (most recent call last): File
"/home/boris/its/plts/bio/bk-simulates-work.py", line 100, in <module>

subprocess.Popen(["emacs", "--batch", "+83:28", "md.mdp", "--eval",
'(insert \"%g\")' %i, "-f", "save-buffer", "--kill"],
stdout=subprocess.PIPE).wait() 

NameError: name 'i' is not defined

实际上已经定义了,因为命令在for in in range....内。

当我做'(insert \"%g\")'时:

subprocess.Popen(["emacs", "--batch", "+83:28", "md.mdp", "--eval",
'(insert \"%g\")', "-f", "save-buffer", "--kill"],
stdout=subprocess.PIPE).wait()

它只是插入%g。

实际上我不再使用emacs这样做了(在文件的特定位置插入i):

myInput = open(opts.myMdp, 'r')
myTempFile = opts.myMdp + '~~~'
myOutput = open(myTempFile, 'w')
for line in myInput:
    myOutput.write(line.replace(opts.myToken, "%g" %myValue))
myOutput.close()
myInput.close()
os.rename(myTempFile, opts.myMdp)