[英]Editing Python scripts with Python
I'm trying to permanently edit variables within a Python script' source. 我正在尝试永久编辑Python脚本源中的变量。
eg 例如
urlpatterns = patterns('core.views',
)
to 至
urlpatterns = patterns('core.views',
url(r'^admin/', include(admin.site.urls)),
)
eg 例如
items = [
'unicorn',
'cats',
]
to 至
items = [
'unicorn',
'cats',
'knights',
'panthers',
]
This has probably been done already, but cannot seem to find much around. 这可能已经完成,但似乎找不到多少。
Any ideas, tips or suggestions? 任何想法,提示或建议?
I'm just going to add code at the bottom of the script file 我只是要在脚本文件的底部添加代码
eg 例如
urlpatterns += patterns('core.views',
url(r'^admin/', include(admin.site.urls)),
)
works for now :) 现在适用:)
Python source code is, for this matter, a text file, so you pretty much open it and read/write data the usual way. 对于这个问题,Python源代码是一个文本文件,所以你几乎可以打开它并以通常的方式读/写数据。 I don't think this is an amazingly good idea, but if you're writing an installer of some sort... 我不认为这是一个非常好的主意,但如果你正在编写某种类型的安装程序......
If you're generating from a template, you could use plain old string formatting: 如果您是从模板生成的,则可以使用普通的旧字符串格式:
tmpl = """import foo
bar = 12345
myList = [
1,
2,
%s
]
otherStuff = %s"""
# figure out the values that need to go there
with f = open(filename, 'w+'):
f.write(tmpl % (item1, item2))
(Alternately instead of hard-coding that string, you could read it in from a file as well) (或者不是硬编码那个字符串,你也可以从文件中读取它)
Or you could use one of the many templating engines for Python . 或者您可以使用Python的许多模板引擎之一 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.