0

在 Windows 7 中使用 Python 2.7。

执行前的文件:

build=\\server\build
apps=\\server\aps
logs=\\server\logs

执行命令:

python test1.py \\serverbuild\loc \\serverapps\loc \\serverlogs\logs

test.py 内容:

import sys
import os
import re
import shutil

buildpath = sys.argv[1]
buildpath = buildpath.replace('\\', '\\\\')
appspath = sys.argv[2]
appspath = appspath .replace('\\', '\\\\')
logspath = sys.argv[3]
logspath = logspath .replace('\\', '\\\\')

tf = open('tmp', 'a+')

with open('test1.txt') as f:
    for line in f.readlines():
        build = re.sub ('build='r'.*','build='+buildpath,line)
        tf.write(build)
        apps = re.sub ('apps='r'.*','apps='+appspath,line)
        tf.write(apps)
        logs = re.sub ('logs='r'.*','logs='+logspath,line)
        tf.write(logs)

tf.close()
f.close()
shutil.copy('tmp', 'test1.txt')
os.remove('tmp')
exit()

执行命令后的当前输出:

build=\\serverbuild\loc
build=\\server\build
build=\\server\build
apps=\\server\aps
apps=\\serverbuild\loc
apps=\\server\aps
logs=\\server\logslogs=\\server\logslogs=\\serverbuild\loc

执行命令后所需的输出:

build=\\serverbuild\loc
apps=\\serverapps\loc
logs=\\serverlogs\logs

谁能帮我得到想要的输出?我是 python 和编程的新手,我需要这方面的帮助。提前感谢一堆。

4

1 回答 1

0

我用以下代码替换了 for 循环,它起作用了:

with open('test1.txt') as f:
    line1 = f.readline()
    line2 = f.readline()
    line3 = f.readline()
    build = re.sub ('build='r'.*','build='+buildpath,line1)
    apps = re.sub ('apps='r'.*','apps='+appspath,line2)
    logs = re.sub ('logs='r'.*','logs='+logspath,line3)
    tf.write(build + apps + logs)
于 2013-06-04T00:17:04.110 回答