Вот моя простая реализация:
class Node:
def __init__(self):
self.data = None
self.next = None
def __str__(self):
return "Data %s: Next -> %s"%(self.data, self.next)
class LinkedList:
def __init__(self):
self.head = Node()
self.curNode = self.head
def insertNode(self, data):
node = Node()
node.data = data
node.next = None
if self.head.data == None:
self.head = node
self.curNode = node
else:
self.curNode.next = node
self.curNode = node
def printList(self):
print self.head
l = LinkedList()
l.insertNode(1)
l.insertNode(2)
l.insertNode(34)
Выход:
Data 1: Next -> Data 2: Next -> Data 34: Next -> Data 4: Next -> None
// Start the child process.
Process p = new Process();
// Redirect the output stream of the child process.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "YOURBATCHFILE.bat";
p.Start();
// Do not wait for the child process to exit before
// reading to the end of its redirected stream.
// p.WaitForExit();
// Read the output stream first and then wait.
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
Код от MSDN.
Это может быть не самым лучшим / простым способом, но может быть вариантом:
Когда вы выполняете из своего кода, добавьте «> output.txt» и затем прочитайте в файле output.txt.
Это может быть полезно для кого-то, если вы пытаетесь запросить локальный ARP-кэш на ПК / сервере.
List<string[]> results = new List<string[]>();
using (Process p = new Process())
{
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.Arguments = "/c arp -a";
p.StartInfo.FileName = @"C:\Windows\System32\cmd.exe";
p.Start();
string line;
while ((line = p.StandardOutput.ReadLine()) != null)
{
if (line != "" && !line.Contains("Interface") && !line.Contains("Physical Address"))
{
var lineArr = line.Trim().Split(' ').Select(n => n).Where(n => !string.IsNullOrEmpty(n)).ToArray();
var arrResult = new string[]
{
lineArr[0],
lineArr[1],
lineArr[2]
};
results.Add(arrResult);
}
}
p.WaitForExit();
}
System.Diagnostics.ProcessStartInfo psi =
new System.Diagnostics.ProcessStartInfo(@"program_to_call.exe");
psi.RedirectStandardOutput = true;
psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
psi.UseShellExecute = false;
System.Diagnostics.Process proc System.Diagnostics.Process.Start(psi);;
System.IO.StreamReader myOutput = proc.StandardOutput;
proc.WaitForExit(2000);
if (proc.HasExited)
{
string output = myOutput.ReadToEnd();
}
Необходимо будет использовать ProcessStartInfo
с RedirectStandardOutput
, включил - тогда можно считать поток вывода. Вы могли бы найти легче использовать ">"; перенаправить вывод в файл (через ОС), и затем затем считать файл.
[редактирование: как то, что сделал Ray: +1]
Можно запустить любую программу командной строки с помощью класса Процесса и установить свойство StandardOutput экземпляра Процесса с потоковым читателем, которого Вы создаете (или на основе строки или на основе ячейки памяти). После того, как процесс завершается, можно тогда сделать любую разность, Вы должны на том потоке.
Вот быстрый образец:
//Create process
System.Diagnostics.Process pProcess = new System.Diagnostics.Process();
//strCommand is path and file name of command to run
pProcess.StartInfo.FileName = strCommand;
//strCommandParameters are parameters to pass to program
pProcess.StartInfo.Arguments = strCommandParameters;
pProcess.StartInfo.UseShellExecute = false;
//Set output of program to be written to process output stream
pProcess.StartInfo.RedirectStandardOutput = true;
//Optional
pProcess.StartInfo.WorkingDirectory = strWorkingDirectory;
//Start the process
pProcess.Start();
//Get program output
string strOutput = pProcess.StandardOutput.ReadToEnd();
//Wait for process to finish
pProcess.WaitForExit();
Команда выполнения остроты:
new Process() { StartInfo = new ProcessStartInfo("echo", "Hello, World") }.Start();
вывод Read команды в самом коротком объеме кода reable:
var cliProcess = new Process() {
StartInfo = new ProcessStartInfo("echo", "Hello, World") {
UseShellExecute = false,
RedirectStandardOutput = true
}
};
cliProcess.Start();
string cliOut = cliProcess.StandardOutput.ReadToEnd();
cliProcess.WaitForExit();
cliProcess.Close();
В открытом исходном коде PublicDomain есть класс ProcessHelper, который может вас заинтересовать.
Есть еще один полезный параметр, который я использую для удаления окна процесса
pProcess.StartInfo.CreateNoWindow = true;
, он помогает полностью скрыть черное окно консоли от пользователя, если вы этого хотите.