我想从c sharp中读取变量为python。我怎样才能读取一个变量从C锐成Python?
.cs文件
class MyClass
{
string str = "Hello world";
}
.py文件
fp = open(path, 'r').read()
#str = ???
print 'str: ' + str
当我跑我的Python代码,我希望得到的结果:
str: Hello world
我想从c sharp中读取变量为python。我怎样才能读取一个变量从C锐成Python?
.cs文件
class MyClass
{
string str = "Hello world";
}
.py文件
fp = open(path, 'r').read()
#str = ???
print 'str: ' + str
当我跑我的Python代码,我希望得到的结果:
str: Hello world
您可以使用正则表达式,我强烈建议使用with
打开你的文件,因为你可以关闭文件时节省一些代码行。
import re
path = 'my_file.cs'
var_name = 'str'
with open(path) as f:
for line in f:
match = re.search(r'{} = "(.*?)"'.format(var_name), line)
if match:
print('{}: {}'.format(var_name, match.group(1)))
输出:
str: Hello world
在这种情况下,我假设你的文件在同一目录下你的Python文件,但你可以改变路径变量,如果没有。
Thx。但我想使用另一个目录 –
好,理想情况下,您希望使用智能解析器足以知道C#。但你可以用正则表达式作弊,并使其适用于这个例子。
import re
fp = open(path, 'r').read()
match = re.search(r'str = "(.*?)"', fp)
print("Str: %s" % match.group(1))
此代码返回错误:AttributeError:'NoneType'对象没有属性'组' –
使用readlines。 +正则表达式来找到你想要的字符串。 – anupsabraham