【发布时间】:2018-04-20 03:46:32
【问题描述】:
我有简单的python 函数。
def readMainTemplate(templateFile):
template = open(templateFile, 'r')
data = template.read()
index1 = data.index['['] #originally I passed it into data[]
index2 = data.index[']']
template.close()
return data[index1:index2]
def writeMainTemplate(template, name):
file = open(name, 'w')
file.write(template)
file.close()
#runMainTemplate('main.template')
def runMainTemplate(template):
code = readMainTemplate(template)
writeMainTemplate(code, 'main.cpp')
他们基本上假设从文件中读取某种模板(类似这样)
--template "main"
[
#include <iostream>
using namespace std;
int main()
{
return 0;
}
]
然后写入文件(基本生成main.cpp模板)
我使用这个命令从命令行运行它
python -c "from genmain import runMainTemplate; runMainTemplate('main.template')"
但是我遇到了这个错误
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "genmain.py", line 18, in runMainTemplate
code = readMainTemplate(template)
File "genmain.py", line 6, in readMainTemplate
index1 = data.index['['] #originally I passed it into data[]
TypeError: 'builtin_function_or_method' object has no attribute '__getitem__'
我认为data = template.read() 应该返回string 并且字符串应该允许执行操作切片[:]。
但为什么会出现错误?
还有一个问题:我应该把python 脚本放在哪里以便在文件系统中的任何位置运行它?(我想通过提供在当前文件夹的文件系统中的任何位置生成文件模板路径)
【问题讨论】:
标签: python