2013-09-01 170 views
0

我正致力于将我写入并行进程的一些代码翻译成在我的家乡大学的计算机集群上进行分发。为了准备写我的剧本集群,我开始通过阅读由集群提供的Python代码样本片段之一:寻找帮助了解os.system()中的sed命令()Python行

#! /usr/bin/python 

# This script replicates a given test with varied parameters 
# creating unique submit scripts and executing the submission to the CRC SGE queue 

# Imports 
import os 
import shutil 
import string 

basedir=os.getcwd() 
origTestFol='wwd' 
templFol='template' 
origTestDir= basedir + '/' + origTestFol 
templFolDir= basedir + '/' + templFol 

steps=[0,1,2,3,4,5,6,7,8,9] 
primes=[2,3,5,7,11,13,17,19,23,29,31] 
trials=[6,7,8,9,10] 

for step in steps: 
    newTestDir= origTestDir + '_nm_' + str(step) 
    if not os.path.exists(newTestDir): 
     os.mkdir(newTestDir) 
    os.chdir(newTestDir) 
    for trial in trials: 
     newTestSubDir= newTestDir + '/' + str(trial) 
     if not os.path.exists(newTestSubDir): 
      shutil.copytree(templFolDir,newTestSubDir) 
      os.chdir(newTestSubDir) 
      os.system('sed -i \'s/seedvalue/' + str(primes[trial]) + '/g\' wwd.nm.conf') 
      os.system('sed -i \'s/stepval/' + str(step) + '/g\' qsubScript.sh') 
      os.system('qsub qsubScript.sh') 
      os.chdir(basedir) 

我可以遵循的代码,直至最后四行[例如直到“os.system('sed -i ...)”],但之后的代码很难。其他人能否帮助我理解最后四行的内容。有没有办法来描述伪代码中的谎言?据我所知,第一条sed行尝试用primes [trial]的值替换“seedvalue”,但我不确定seedvalue是什么。我也不确定如何理解后续行中的“stepval”。任何其他人可以解决这些问题的亮点将是最受赞赏的。

回答

1

你可以做一个小的搜索上的sed:http://en.wikipedia.org/wiki/Sed#In-place_editing

简而言之:sed -i 's/old/new/g' file取代的oldfilenew一切的发生。 -i标志告诉它在线修改文件本身。

在您的代码中,seedvaluestepval只不过是文本文件wwd.nm.confqsubScript.sh中的两个单词。这些命令正如您在文本编辑器或文字处理器中所做的那样替换这些单词。

+0

感谢您对s/command和-i标志@emnoor的简洁定义。这个简单的解释帮助我掌握了最后四行代码的功能。 – duhaime

1

seedvalue是一个字符串,所以它的值本身与stepval相同。

第一sed线将取代wwd.nm.conf所有seedvalue字符串(所有线路上,这就是/g做,它的全称是“全球”)值为str(primes[trial])。想想是这样的:

无论文本stepvalue在文件wwd.nm.conf中找到,请将值str(primes[trial])(无论那些评估为Python)。

第二个sed呼叫将做类似的事情,但stepvalstep的结果,它将取代文件qsubScript.sh中的文本。

+0

非常感谢@Phillip!我确信seedvalue和stepval是字符串,但是因为代码没有定义这些字符串而感到困惑。我现在才明白,代码将这些代码保留为未定义的变量,以便用户可以用他们希望在其“wwd.nm.conf”脚本中更改的某行代码替换“seedvalue”。如果我理解正确,上面脚本的要点是略微修改单个脚本及其关联的.job文件,然后提交新的作业文件(使用qsub)以运行修改后的脚本。感谢您帮助我理解这一点。 – duhaime