0

I am a newbie in programming, and I have an MVC project. I want to use C# call the Python py file and pass parameters in order to make a chart.

I refer to this article How do I run a Python script from C#? .

I have used this method to make lots of charts, and they can execute and pass parameters successfully. There's only two files cannot be successfully called and passed parameters, and I think it's Python has an error that can't call the py.
Here is a failure below. When I run proportion.py alone in Spyder, it can successfully use the Fixed parameters. BUT when i use C# to call it, there will be no response.

The syntax in the file has been confirmed to be executed without problems, and methods i have been tried lots of methods, but still not resolved. Please save my projetct, I will be very thankful!!
Thanks for any help.

Here is how i use C# to call Python below.

public ActionResult Index(string searchString, DateTime? startdate, DateTime? enddate)
{
    run_sound("D:/Python/pie.py", "" + sd + "", "" + ed + "", "" + searchString + "");
    run_Emoanalysis("picture/AAApy.py", "" + sd + "", "" + ed + "", "" + searchString + "");
    run_proportion("D:/Microsoft Visual Studio/MVC project/MVC project/picture /proportion.py", "" + sd + "", "" + ed + "", "" + searchString + "");
}
    
    
    
//The following is the function of run_proportion,
//other functions(run_sound) are the same as this method, and carefully confirmed.
    
private string run_proportion(string cmd, string sdate, string edate, string condition)
{
    ProcessStartInfo start = new ProcessStartInfo();
    start.FileName = @"C:/Users/user/AppData/Local/Programs/Python/Python38-32/python.exe";
    start.CreateNoWindow = true;
    start.Arguments = string.Format("{0} {1} {2} {3}", cmd, sdate, edate, condition);
    start.UseShellExecute = false;
    start.RedirectStandardOutput = true;

    using (Process process = Process.Start(start))
    {
        using (StreamReader reader = process.StandardOutput)
        {
            string result = reader.ReadToEnd();
            //Console.Write(result);
            process.WaitForExit();
            return result;
        }
    }
}

Here is proportion.py below that cannot be called and executed BY C#.


sd= sys.argv[1]
ed = sys.argv[2]
cdn = sys.argv[3]

sqlcom = "SELECT  COUNT(DISTINCT url) FROM JIEBA WHERE (title LIKE '%" +str(cdn)+ "%') AND (post BETWEEN '" +str(sd)+ "' AND '" +str(ed)+ "')"
sqlcom2 = "SELECT COUNT(DISTINCT  url) as KeyWordCount FROM JIEBA WHERE (title LIKE '%" +str(cdn)+ "%')"
 

df = pd.read_sql(sqlcom, con=cnxn) 


df1 = np.array(df)
df0 = df1.tolist()

df2 = pd.read_sql(sqlcom2, con=cnxn)  

df3 = np.array(df2) 

df4 = df3.tolist()
df5 = str(df4[0][0])
print(df5)
df6 = str(df0[0][0])
print(df6)
c = int(df5)-int(df6)
# =============================================================================
count = float(df5)/float(df5)
print(count)
# 
keyword = float(df6)/float(df5)
print(keyword)
# 
keyword2 = str(round(float(df6)/float(df5)*100,2))+'%'
print(keyword2)
# 
count2 = str(round((1-float(df6)/float(df5))*100,2))+'%'
print(count2)

 
# Change color
fig = plt.figure(figsize = (7,5))
ax = fig.add_subplot(111)
squarify.plot(sizes=[int(c),int(df6)], label=['期間"外"所佔筆數', '查詢後所佔比數'],value =(str(c)+'筆/'+str(df5)+'筆'+'\n'+'佔 '+str(count2),str(df6)+'筆/'+str(df5)+'筆'+'\n'+'佔 '+str(keyword2)), color=["red","blue"], alpha=.4)
plt.rcParams['font.sans-serif'] = 'Microsoft YaHei'
plt.rcParams['axes.unicode_minus'] = False
ax.set_title('關鍵字搜尋期間所佔比例',fontsize = 18)
plt.axis('off')
plt.tight_layout()
plt.savefig("D:\Microsoft Visual Studio\MVC project\MVC project\picture\keyproportion.png")
li neil
  • 11
  • 2
  • Not sure if it's your problem, but `"" + s + ""` won't add quotes around `s` (which is what I assume you think it will do) -- `""` is an empty string, so it will add two empty strings to `s`, which just leaves... `s`. You probably wanted `"\""` + s + "\""` (`"\""` is a string containing a double quote character), alternatively `'"' + s + '"'` or `@"\"{s}\""` – canton7 Nov 05 '20 at 17:22
  • 1
    The M in MRE stands for **minimal**. Please condense your code down into a [mre]. Pasting your entire code here is a great way to get people to click away from your question. – Pranav Hosangadi Nov 05 '20 at 17:42
  • @canton7 Thanks for your reply! I type `" " + s + " "` is because my other function(run_bar,run_wc.....) can successfully pass parameters and be excuted, so i do the same function when i call run_proportion, BUT just `proportion.py` can't be excute – li neil Nov 05 '20 at 17:44
  • @PranavHosangadi OH OK, I improve it now! – li neil Nov 05 '20 at 17:46

1 Answers1

0

Also had some issues with running python, first would suggest replacing quotes in strings with a variable since it makes tracking them easier

        var quote = '"';

also after doing the whole string do a

var commandUnescaped = Regex.Unescape(command);

pasting my way to call commands in case you want it, need to adapt it to windows , but same logic:

   private (bool,string,string) RunCommand(string command, string args)
    {
        args = args.Replace("\"", "\\\"");
        var process = new Process()
        {
            StartInfo = new ProcessStartInfo
            {
                FileName = "/bin/bash",
                Arguments = $"-c \"{args}\"",
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                UseShellExecute = false,
                CreateNoWindow = true,
            }
        };
        process.Start();
        string output = process.StandardOutput.ReadToEnd();
        string error = process.StandardError.ReadToEnd();
        process.WaitForExit();

        if (string.IsNullOrEmpty(error))
        {
            return (true,output,error);
        }
        else
        {
            return (false,output,error);
        }
    }
Rodrigo Chapeta
  • 119
  • 1
  • 10