当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - How to use sed within python?

问题描述:

I am sure there must be more intelligent way to achieve this. I need to change the app id in my javascript BEFORE minifying it with Closure.

One "quick" solution I came up with, was using the good old sed. While this works on command line, it fails when run within a python file. It doesn't fail with an error. The outfile file is the exact copy of the source. As if it hasn't found the text.

choice = raw_input("Type 1 (Staging) or 2 (Production)?")

if choice == '1':

cmd = r"sed 's%var appid = '1234';%var appid = '5678';%' {0}f11.js > {0}f11_final.js".format(PATH)

os.system(cmd)

Any idea what I am missing? Thanks

UPDATE:

I just changed the source from this:

var appid = '1';

to this:

var appid = 1;

and ran this successfully:

cmd = "sed -i 's%var appid = 1;%var appid = 2;%' {0}f11.js".format(PATH)

It has to do with escaping single quotes. Any idea what I could do? I tried \' but it fails.

Solution:

I ended up doing it in python as suggested. It is not easy though, if you haven't done it before. So I share my code:

with open("{0}f11.js".format(PATH), "r") as sources:

lines = sources.readlines()

with open("{0}f11-final.js".format(PATH), "w") as sources:

for line in lines:

sources.write(re.sub("var appid = '1';", "var appid = '2';", line))

网友答案:

You can use the library re of Python. In particular the function sub that is similar to sed.

分享给朋友:
您可能感兴趣的文章:
随机阅读: