初歩的な質問で恐縮です.
C#でコマンドからpythonファイルを実行しています.このpythonファイル(pythonFilePath)に,jsonファイル(jsonFilePath)をインプットします.
現状,以下のコードです.正常に動きます.
C#
1Process process = new Process(); 2process.StartInfo.FileName = "cmd"; 3process.StartInfo.Arguments = string.Format("/c \"python {0} < {1}\"", pythonFilePath, jsonFilePath); 4process.StartInfo.UseShellExecute = false; 5process.StartInfo.RedirectStandardInput = true; 6process.StartInfo.RedirectStandardOutput = true; 7process.StartInfo.CreateNoWindow = true; 8process.Start(); 9 10StringBuilder buffer = new StringBuilder(); 11while (process.StandardOutput.EndOfStream == false) 12{ 13 buffer.AppendLine(process.StandardOutput.ReadLine()); 14} 15var text = buffer.ToString();
jsonファイルは,例えば,以下のような内容です.
json
1{ 2 "id": [ 3 2 4 ] 5}
他の仕様との関係上,jsonファイル(jsonFilePath)の内容を,直接,pythonファイル(pythonFilePath)に渡す必要があります.StandardInputを使って,以下のように修正したのですが,動かなくなりました.
C#
1Process process = new Process(); 2process.StartInfo.FileName = "cmd"; 3process.StartInfo.Arguments = string.Format("/c \"python {0}\"", pythonFilePath); 4process.StartInfo.UseShellExecute = false; 5process.StartInfo.RedirectStandardInput = true; 6process.StartInfo.RedirectStandardOutput = true; 7process.StartInfo.CreateNoWindow = true; 8process.Start(); 9 10//仕様上,jsonファイルの内容を直接渡したい.”<”で渡せない. 11using (var reader = new StreamReader(jsonFilePath, Encoding.UTF8)) 12{ 13 while (!reader.EndOfStream) 14 { 15 var line = reader.ReadLine(); 16 process.StandardInput.WriteLine(line); 17 } 18} 19 20StringBuilder buffer = new StringBuilder(); 21while (process.StandardOutput.EndOfStream == false) 22{ 23 buffer.AppendLine(process.StandardOutput.ReadLine()); 24} 25var text = buffer.ToString();
pythonファイルでコマンド実行する際に,jsonファイルの内容を直接渡す方法について,アドバイスを頂戴できますと幸いです.
回答2件
あなたの回答
tips
プレビュー