SaeHyun Kim SaeHyun Kim - 4 years ago 127
C# Question

How can I read a variable from c sharp into python?

I want to read variable from c sharp into python.

.cs file

class MyClass
{
string str = "Hello world";
}


.py file

fp = open(path, 'r').read()
#str = ???
print 'str: ' + str


When I run my python code, I want to get result:

str: Hello world

Answer Source

You can use a regex, and I strongly suggest using with to open your file since you could save some lines of code when closing your file.

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)))

Output:

str: Hello world

In this case, I am assuming your file is in the same directory as your python file, but you can change the path variable if not.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download