寻找帮助了解os.system()中的sed命令Python行

时间:2013-09-01 02:49:05

标签: python sed os.system

我正在努力将我编写的一些代码翻译成并行进程,以便在我家大学的计算机集群上进行分发。为了准备为集群编写脚本,我首先阅读了集群提供的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”。任何其他人可以解决这些问题的亮点将是非常感谢。

2 个答案:

答案 0 :(得分:1)

您可以在sed上进行一些搜索:http://en.wikipedia.org/wiki/Sed#In-place_editing

简而言之:sed -i 's/old/new/g' file将所有old的{​​{1}}替换为new中的file-i标志告诉它在线执行,修改文件本身。

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

答案 1 :(得分:1)

seedvalue是一个字符串,因此其值本身与stepval相同。

第一个sed行将替换seedvalue中的所有wwd.nm.conf字符串(在所有行上,这是/g所做的,它代表“全局”)价值str(primes[trial])。想想这样:

在文件stepvalue中找到文本wwd.nm.conf的任何地方,放置值str(primes[trial])(无论评估结果如何)。

第二次sed调用会执行类似但stepvalstep的结果,它将替换文件qsubScript.sh中的文字。

相关问题