首页 > 解决方案 > C#不能调用python和传递参数

问题描述

我是编程新手,我有一个 MVC 项目。我想使用C#调用 Pythonpy文件并传递参数来制作图表。

我参考这篇文章如何从 C# 运行 Python 脚本?.

我已经用这种方法制作了很多图表,并且可以成功执行和传递参数。只有两个文件无法成功调用和传递参数,我认为它Python有一个错误,无法调用py.
这是下面的失败。当我proportion.py在 Spyder 中单独运行时,它可以成功使用 Fixed 参数。但是当我用C#它来调用它时,将没有任何响应。

文件中的语法已经确认执行没有问题,方法我已经尝试了很多方法,但仍然没有解决。请保存我的项目,我将非常感谢!
谢谢你的帮助。

这是我在下面C#调用的方式Python

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;
        }
    }
}

下面是proportion.py不能被调用和执行的 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")

标签: pythonc#

解决方案


运行python也有一些问题,首先建议用变量替换字符串中的引号,因为这样可以更容易地跟踪它们

        var quote = '"';

在完成整个字符串之后也做一个

var commandUnescaped = Regex.Unescape(command);

粘贴我调用命令的方式以防万一,需要将其调整为 windows ,但逻辑相同:

   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);
        }
    }

推荐阅读