C#
ASP.NET
VSTO
Python To Word
Capture script output in MS Word
using Word = Microsoft.Office.Interop.Word;
public class PyScriptForm : System.Windows.Forms.Form
{
private System.Windows.Forms.OpenFileDialog openFileDialog;
private System.Windows.Forms.Button btnRun;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.Button btnBrowseForScript;
private System.Windows.Forms.TextBox txtScriptFile;
private System.Windows.Forms.TextBox txtArgs;
private System.Windows.Forms.CheckBox chkCaptureStdOut;
private readonly Word.Application __application;
private const string DEFAULT_SCRIPT_DIRECTORY =
@"C:\Program Files\Python\Python24\Scripts";
public PyScriptForm( Word.Application application )
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
__application = application;
}
private void BrowseForScript_Click(object sender, System.EventArgs e)
{
if ( this.openFileDialog.ShowDialog() == DialogResult.OK )
{
this.txtScriptFile.Clear();
this.txtScriptFile.Focus();
this.txtScriptFile.AppendText( openFileDialog.FileName);
}
}
private void btnRun_Click(object sender, System.EventArgs e)
{
ProcessStartInfo startInfo;
Process process;
string directory;
string pyArgs;
string script;
script = this.txtScriptFile.Text.Trim();
if ( script == null || script.Length == 0 )
{
return;
}
try
{
directory = Path.GetDirectoryName( script );
script = Path.GetFileName( script );
}
catch (ArgumentException)
{
MessageBox.Show("The script file path contains invalid characters.",
"Invalid Script Path",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
if ( script.Length == 0 )
{
MessageBox.Show("No script file has been specified.",
"Invalid Script Path",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
if ( directory == null || directory.Length == 0 )
{
directory = DEFAULT_SCRIPT_DIRECTORY;
}
pyArgs = this.txtArgs.Text.Trim();
startInfo = new ProcessStartInfo("python");
startInfo.WorkingDirectory = directory;
startInfo.Arguments = script + " " + pyArgs;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
process = new Process();
process.StartInfo = startInfo;
process.Start();
string s;
while ((s = process.StandardOutput.ReadLine()) != null)
{
this.__application.Selection.TypeText( s + "\n" );
}
while ((s = process.StandardError.ReadLine()) != null)
{
this.__application.Selection.TypeText( s + "\n" );
}
}
}