views:

718

answers:

8

I had an idea, if I add a python .py file to my C# project, and tag the file with a custom generator that would execute the python file, and treat the output as the result of the code generation, ie. put it into a C# file, that would allow me to do quite a lot of code generation as part of the build process.

Does anyone know if such a custom generator for Visual Studio 2008 exists?

+2  A: 

I recall that in previous versions of VS, there was a way to add custom build steps to the build process. I used that a lot to do exactly the kind of automated code generation you describe.

I imagine the custom build step feature is still there in 2008.

Greg Hewgill
A: 

Yes, they are of course, but I'd still like to have a custom generator, as this would automatically be invoked if I changed the Python file, and thus regenerating the code in question.

Lasse V. Karlsen
+1  A: 

I don't understand what you are trying to do here. Are you trying to execute a Python script that generates a C# file and then compile that with the project? Or are you trying to compile a Python script to C#?

dguaraglia
A: 

@davidg

What I want is to add a .py file to my C# project, and specify a custom tool for this file. When the tool is invoked, it executes the .py file, and takes all its output (print statements for simplicity) and stores that into a C# file. This C# file is then added to the C# project, and compiled as part of the rest of the code.

Here's a simple such piece of python code that could be used

print "namespace TestApp {"
print "    public static class GeneratedClass {
print "        public static String HelloWorld() { return "Hello world"; }
print "    }"
print "}"
Lasse V. Karlsen
+1  A: 

OK, I see. Well, as far as I know there isn't any code generator for Python. There is a good introduction on how to roll your own here.

Actually, that's quite an under-used part of the environment, I suppose it's so because it needs you to use the IDE to compile the project, as it'd seem only the IDE knows about these "generators", but MSBuild ignores them.

dguaraglia
A: 

Hmm, MSBuild ignores them, I hadn't considered that part.

I guess I'll dig more into this then, thanks for that heads up.

Lasse V. Karlsen
+2  A: 

I think Cog does what you want.

jwfearn
+1  A: 

I dug through my old bookmarks (I love Del.icio.us!) and found this article: Code Generation with Python, Cog, and Nant. Keep in mind that anything you can do in NAnt can probably be done in MSBuild as well. This should be enough to get you started.

technomalogical