简体   繁体   English

从python编辑.js文件

[英]Edit .js file from python

I'm writing a program that involves editing Firefox's proxy settings, specifically the socks and http proxy settings. 我正在编写一个涉及编辑Firefox代理设置的程序,特别是socks和http代理设置。 I want to do this through editing Firefox's prefs.js file. 我想通过编辑Firefox的prefs.js文件来做到这一点。 It opens just fine in python - but after that I just can't think of a way to do this that isn't incredibly long and roundabout. 它在python中打开很好 - 但在那之后我就想不出一种方法来做到这一点并不是非常长和迂回。 The part of prefs.js that I want to edit looks like this: 我要编辑的prefs.js部分如下所示:

user_pref("network.proxy.backup.ftp", "");
user_pref("network.proxy.backup.ftp_port", 0);
user_pref("network.proxy.backup.socks", "");
user_pref("network.proxy.backup.socks_port", 0);
user_pref("network.proxy.backup.ssl", "");
user_pref("network.proxy.backup.ssl_port", 0);
user_pref("network.proxy.ftp", "foo.bar");
user_pref("network.proxy.ftp_port", 5);
user_pref("network.proxy.gopher", "");
user_pref("network.proxy.gopher_port", 0);
user_pref("network.proxy.http", "foo.bar");
user_pref("network.proxy.http_port", 5);
user_pref("network.proxy.share_proxy_settings", true);
user_pref("network.proxy.socks", "foo.bar");
user_pref("network.proxy.socks_port", 5);
user_pref("network.proxy.ssl", "foo.bar");
user_pref("network.proxy.ssl_port", 5);
user_pref("network.proxy.type", 1);

You don't really need a JavaScript parser or anything fancy here; 你真的不需要JavaScript解析器或任何想象的东西; you could do this with very simple regular expressions. 你可以用非常简单的正则表达式做到这一点。 For example: 例如:

r = re.compile(r'user_pref\("network.proxy.socks", .*?\);')
with open('prefs.js') as f:
    contents = f.read()
contents = r.sub(r'user_pref("network.proxy.socks", "the.value.i.want");', 
                 contents)
with open('newprefs.js', 'w') as f:
    f.write(contents)

If you don't understand even simple regular expressions, this isn't too hard to do with trivial string manipulation either. 如果你甚至不理解简单的正则表达式,那么对于简单的字符串操作也不是很难。 For example: 例如:

with open('prefs.js') as fin, open('newprefs.js', 'w') as fout:
    for line in fin:
        if 'user_pref("network.proxy.socks",' in line:
            line = 'user_pref("network.proxy.socks", "the.value.i.want");\n'
        fout.write(line)

And to edit more lines, just do the same thing more times. 要编辑更多行,只需多次执行相同的操作即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM