python - 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")
解决方案
运行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);
}
}
推荐阅读
- scala - 如何折叠光滑的列的总和?
- amazon-web-services - 无法访问 Elastic Beanstalk IP 地址之一?
- c# - 是否可以从 URL 将图像加载到统一画布中?
- java - 如何解决 java.lang.RuntimeException: RESTEASY007545: Unable to find a MessageBodyReader for media type
- module - 构建的内核模块不包括 ccflags -y
- laravel - 简写 isset 后跟 eval
- python - 如何通过单击外部窗口使 tkinter 窗口无法消失?
- macos - mac OSX 10.15.1 无法删除系统根证书
- c++ - 将 void* 参数转换为各种类型是 UB 吗?
- go - 查找与字符串匹配的结构字段类型