I’m developing a Winform application. I want to run python script from c# via command prompt (i’m using System.Diagnostics.Process
class)
I have a function to run python script that need to pass a python script file name.
public void Run(string cmd)
{
Process p = new Process()
{
StartInfo = new ProcessStartInfo()
{
FileName = "python",
CreateNoWindow = true,
UseShellExecute = false,
ErrorDialog = false,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
WorkingDirectory = Directory.GetCurrentDirectory() + @"PythonScripts",
Arguments = string.Format("{0}", cmd)
},
EnableRaisingEvents = true,
SynchronizingObject = this
};
p.OutputDataReceived += (s, e) => SetOutputText(e.Data);
p.ErrorDataReceived += (s, e) => SetErrorText(e.Data);
p.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine();
}
It works correctly until I print a string that contain unicode character.
My test.py
code contains just a single line.
print("xin chào việt nam")
When I compiled this test.py
command prompt from start
it worked perfectly. But when I compiled from c# via command prompt I got this error:
Traceback (most recent call last):
File "test.py", line 1, in <module> ufeffprint("xin chào viu1ec7t nam")
File "C:UsersD SeriousAppDataLocalProgramsPythonPython36libencodingscp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)
[0]UnicodeEncodeError: 'charmap' codec can't encode character 'u1ec7' in position 11: character maps to <undefined>
I think the problem here caused by C# when it run command prompt and read the python script, the process can not decode utf8 correctly. Thank you.
Advertisement
Answer
After hours finding the reason, I found it. Python decoding doesn’t have problem, that is command prompt problem. So that I fix my function to:
public void Run(string cmd)
{
Process p = new Process()
{
StartInfo = new ProcessStartInfo()
{
FileName = "cmd",
CreateNoWindow = true,
UseShellExecute = false,
ErrorDialog = false,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
WorkingDirectory = Directory.GetCurrentDirectory() + @"PythonScripts",
StandardOutputEncoding = Encoding.UTF8,
StandardErrorEncoding = Encoding.UTF8,
StandardInputEncoding = Encoding.UTF8
},
EnableRaisingEvents = true,
SynchronizingObject = this
};
p.Start();
using (StreamWriter sw = p.StandardInput)
{
sw.WriteLine("chcp 65001");
sw.WriteLine("set PYTHONIOENCODING=utf-8");
sw.WriteLine($"python {cmd}");
}
p.OutputDataReceived += (s, e) => SetOutputText(e.Data);
p.ErrorDataReceived += (s, e) => SetErrorText(e.Data);
p.WaitForExit();
p.BeginOutputReadLine();
p.BeginErrorReadLine();
}
I added sw.WriteLine("chcp 65001");
and sw.WriteLine("set PYTHONIOENCODING=utf-8");
to get better decode unicode. Thank for your attention