Run Python 2.7 sript from C# with command line params - c#

How do I run this python 2.7 code from C# (file name is myPythonScript.py):
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'-sd', '-start_date', help='start date to download data')
parser.add_argument(
'-ed', '-end_date', help='end date to download data')
args = parser.parse_args()
#print(args.accumulate(args.start_date))
print(args.sd, args.ed)
Above code only takes two dates as command line params and shows it to the user. I want to run it as a process from C#.
When I use this C# code it runs script without params well. But when I add params it can`t find python file. Why? How to resolve this?
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = #"C:\Anaconda2\python.exe";
// path to my python script
string appEXE = AppDomain.CurrentDomain.BaseDirectory;
// this scripts runs without params
python_script_name = #"myPythonScript.py -sd 01/01/2015 -ed 05/09/2017";
startInfo.Arguments="\""+appEXE+ "Python\\"+ python_script_name + "\"";
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.CreateNoWindow = true;
startInfo.RedirectStandardError = true;
using (Process process = Process.Start(startInfo))
{
using (StreamReader reader = process.StandardOutput)
{
string result = reader.ReadToEnd();
//MessageBox.Show("Normal results"+result);
Debug.WriteLine(result);
}
process.WaitForExit();
// This will show error: no such file or directory
MessageBox.Show("Errors"+process.StandardError.ReadToEnd());
GC.Collect();

Try these lines out:
string scriptPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Python", "myPythonScript.py")
startInfo.Arguments = "\"" + scriptPath + "\"" + " -sd 01/01/2015 -ed 05/09/2017"
I think you had an issue with quotation marks.

Related

Execute cat command to overwrite file

I am trying to execute the cat command from my C# code, but I am running into problems.
So, this is just a very simple test, but I end up with the error:
Error: cat: '>': No such file or directory
Now... both source and target files actually exist.. and same result if target file does not exist.
If I open a console on my Raspberry Pi, it executes just fine. Any help is much appreciated.
My code:
var srcFile = "/home/pi/tm-satellite/Helpers/wpa_supplicant.conf";
var outFile = "/home/pi/tm-satellite/network-test.txt";
StringBuilder sb = new StringBuilder();
var info = new ProcessStartInfo();
info.FileName = "/bin/bash";
info.Arguments = $"-c 'cat {srcFile} > {outFile}'";
info.UseShellExecute = false;
info.CreateNoWindow = true;
info.RedirectStandardOutput = true;
info.RedirectStandardError = true;
var p = Process.Start(info);
//* Read the output (or the error)
sb.AppendLine($"Args: {info.Arguments}");
sb.AppendLine($"Output: {p!.StandardOutput.ReadToEnd()}");
sb.AppendLine($"Error: {p!.StandardError.ReadToEnd()}");
p!.WaitForExit();
return $"Overwrite system file {path}: {p.ExitCode}{Environment.NewLine}{sb}";
This is because you're passing the cat program the > argument.
> only makes sense in bash or sh process where it tells to the interpreter that stdout outputs should be dumped into file. It's not a valid argument for cat.
To get around this, invoke your cat process within your shell:
sh -c 'cat file1 > file2'
In C#
var srcFile = "/home/pi/tm-satellite/Helpers/wpa_supplicant.conf"
var outFile = "/home/pi/tm-satellite/network-test.txt"
var info = new ProcessStartInfo();
info.FileName = "sh";
info.Arguments = $"-c 'cat {srcFile} > {outFile}'";
Alternatively you can use C#'s File utilities to read the first file and write its contents into the second as it might be faster due to less I/O operations.
I've fixed my sample. Use double quotes instead of single quotes:
var srcFile = "~/bad";
var outFile = "~/good";
var pInfo = new ProcessStartInfo()
{
FileName = "sh",
Arguments = $"-c \"cat {srcFile} > {outFile}\""
};
var process = Process.Start(pInfo);
process.WaitForExit();

c# automation stop process

I have C# automation code that start a process
var proc1 = new ProcessStartInfo();
string anyCommand = " adb logcat - v threadtime emulator-5554 > logcat.log";
proc1.UseShellExecute = true;
proc1.WorkingDirectory = outputDirectory;
proc1.FileName = #"C:\Windows\System32\cmd.exe";
proc1.Verb = "runas";
proc1.Arguments = "/c " + anyCommand;
proc1.WindowStyle = ProcessWindowStyle.Hidden;
Process p = new Process();
p.StartInfo = proc1;
p.Start();
Console.WriteLine(p.Id);
TestLogger.WriteInformationStep("p.Id: " + p.Id);
after some steps I'm trying to read the file
string text2 = System.IO.File.ReadAllText(element);
but I receive error message
System.IO.IOException : The process cannot access the file
'C:\Users\test\Documents\overview9\bin\Debug\Results\logcat.log'
because it is being used by another process. TearDown :
HarVE.Log.FailedStepException : There were 1 failed step(s): Test did
not run to completion
what should i do?
I tried p.Close();p.Kill();
non of them work for me.
If p.Kill(); where placed after System.IO.File.ReadAllText(element); write p.Kill() before System.IO.File.ReadAllText(element),
if it placed correctly, then seems like other process is reading/writting that file,
try to use StreamReader from System.IO, StreamReader can read multiple times, something like this:
StreamReader sr = new StreamReader(path_to_file);//replace path_to_file by your txt file path
string text2 = sr.ReadToEnd();

How to get SVN Commit log using c# Process

I need to get the commit log by date for a svn project using C# application i.e if we have provided the URl , start and end date , we should use the svn.exe in a process to get log details
I have use the command svn log -r {"2007-07-07"}:{2019-11-08} to get the log in command prompt.
SourcePath = args[0]; // URL link
var startDate = args[1];
var endDate = args[2];
var svnSource = args[3]; // svn.exe location in my machine
var cmd1 = "cd /";
var cmd2 = "c:";
var cmd3 = string.Concat("cd ", svnSource);
var cmd4 = string.Concat("svn log ", SourcePath, " -r {", startDate, "}:{", endDate, "}");
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "svn.exe";
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
Process process = new Process();
process.StartInfo = startInfo;
process.Start();
process.StandardInput.WriteLine(cmd1);
process.StandardInput.WriteLine(cmd2);
process.StandardInput.WriteLine(cmd3);
process.StandardInput.WriteLine(cmd4);
while (!process.StandardOutput.EndOfStream)
{
string line = process.StandardOutput.ReadLine();
if (!string.IsNullOrEmpty(line))
{
if (!process.HasExited)
{
}
}
}
I expect the result in the string "line" with all log values but i am getting actual output value as empty. breakpoint does not hit the "while (!process.StandardOutput.EndOfStream)" part itself while debugging.
How to resolve this ? what am i doing wrong here?
First of all, svn.exe will not interpret commands like that, so instead you should start a shell like cmd.exe.
If you're supplying a URL for your SourcePath then svn can run from anywhere from cmd, so you don't need the first 3 commands at all: cmd1, cmd2, cmd3.
That being said, you're not gonna need the svnSource variable either.
Of course, you can cd to the root directory to make your output look cleaner.
So these are the modifications I made to your code:
var SourcePath = args[0]; // URL link
var startDate = args[1];
var endDate = args[2];
var cmd1 = "cd c:\\";
var cmd2 = string.Concat("svn log ", SourcePath, " -r {", startDate, "}:{", endDate, "}");
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "cmd.exe";
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
Process process = new Process();
process.StartInfo = startInfo;
process.Start();
process.StandardInput.WriteLine(cmd1);
process.StandardInput.WriteLine(cmd2);
// It's always a good idea to close your standard input when you're not gonna need it anymore,
// otherwise the process will wait indefinitely for any input and your while condition will never
// be true or in other words it will become an infinite loop...
process.StandardInput.Close();
string result = string.Empty; // for storing the svn commit log
while (!process.StandardOutput.EndOfStream)
{
string line = process.StandardOutput.ReadLine();
if (!string.IsNullOrEmpty(line))
{
if (!process.HasExited)
{
result += line + Environment.NewLine;
}
}
}

Pass arabic parameter to python script from c#

I want to pass Arabic string to python script from c#.
And then I will write output to txt file. But my arabic string parameter couldn't pass correctly. It transforms to "????" question marks.
I tried some code, like unicode, but it doesn't work
if __name__ == '__main__':
my_input = sys.argv[1]
out = open("C:\\output.txt", "wb")
p = unicode(my_input, encoding='utf-8')
out.write(p)
out.close()
Also my c# code is like that
public static string run_cmd(string args)
{
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = "C:/Python27/python.exe";
start.Arguments = "C:/test.py" + " " + args;
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
result = reader.ReadToEnd();
}
}
}
Do you have any idea how can I fix this problem?
Or is there something that I missing?
Any idea will be great!

How can i get build/rebuild realtime output

I'm making Visual Studio package where i start devenv.exe and try to build other solution.I need to get building output in realtime, so user can see buiding progress(output), but i don't know how to do it and if it's even possible.
I tried such way :
string rebuildLog = string.Empty;
string logFileName = System.IO.Path.GetTempFileName();
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo();
psi.FileName = #"devenv.exe";
psi.Arguments = "\"" + config.DmsPath + "\"" + #" /rebuild" + " Release|x64 " +" /out " + logFileName;
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo = psi;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.UseShellExecute = false;
process.Start();
while (!process.StandardOutput.EndOfStream)
{
string line = process.StandardOutput.ReadLine();
MessageBox.Show(line); // just to see if it works. It should go to log form
}
rebuildLog = GetRebuildLog(logFileName);
And rebuildLog has output.
Can anybody help ?
I found answer.
devenv.exe doesn't write simple console output, so i had to change
psi.FileName = #"devenv.exe"; to psi.FileName = #"devenv.com"; and it worked.

Categories