asp.net c# webform 将参数传递给未运行的 python 脚本

问题描述 投票:0回答:1

我找到了如何使用 PythonNet 传递参数的示例,但我无法让它触发我的 Python 代码。 在 VS 2022 上开发。如果子目录尚不存在,我想(首先)创建一个子目录。 路径和目录应从 C# 传递。

 protected void btnPythonTest_Click(object sender, EventArgs e)
 {        
     // full path of python interpreter 
     string python = @"C:\Users\User\AppData\Local\Programs\Python\Python312\python.exe";

     // python app to call 
     string myPythonApp = @"C:\OllamaDocs\MyTestPython.py";

     // Paramters to send to Python  (location of docs and Chroma for this user
     string OllamDocsPath = @"C:\OllamaDocs\100\1\";
     string OllamaChromaFilename = "Chroma_100_1B";
     
     try
     {
         System.Diagnostics.ProcessStartInfo myProcessStart = new System.Diagnostics.ProcessStartInfo(python);
         myProcessStart.UseShellExecute = true;
         myProcessStart.RedirectStandardOutput = false;

         // pass arguments to python script
         myProcessStart.Arguments = myPythonApp + " " + OllamDocsPath + " " + OllamaChromaFilename;

         System.Diagnostics.Process myProcess = new System.Diagnostics.Process();

         myProcess.StartInfo = myProcessStart;

         myProcess.Start();

         lblStatus.Text = myPythonApp + " Created " + OllamDocsPath + OllamaChromaFilename;

     }
     catch (Exception ex)
     {
         errorMessage = ex.Message;
         lblStatus.Text = errorMessage;

     }

 }   // end PythonTest()

我的Python测试脚本位于C:根目录下,如下(MyTestPython.py)

import os import sys

# Test Phase II

#Get args from C# 
OllamaPath = sys.argv[0] 
OllamaChroma = sys.argv[1]
    
# Define the directory for vector store persistence
#persist_directory = "C:\\OllamaDocs\\100\\1\\chroma_db_100-1" 
persist_directory = OllamaPath

# Check if the vector store already exists 
if not os.path.exists(persist_directory):
    print("Creating new Chroma Directory " + persist_directory)
    os.makedirs(persist_directory) else:
    # Load the existing Chroma vector store
else:
# Load the existing Chroma vector store
print("path exists.")
python c#
1个回答
0
投票

从 C# 触发 Python 代码时,似乎有一些问题可能导致该问题。以下是一些需要检查的要点和解决方案:

  1. 参数索引:在 Python 脚本中,sys.argv[0] 将是 Python 脚本本身,而不是 C# 的第一个参数。你应该 检索从 sys.argv[1] 开始的参数。这是 更正后的Python代码:
import os
import sys

# Get args from C#
OllamaPath = sys.argv[1]  # Changed from sys.argv[0]
OllamaChroma = sys.argv[2]  # Changed from sys.argv[1]
 
# Define the directory for vector store persistence
persist_directory = OllamaPath

# Check if the vector store already exists 
if not os.path.exists(persist_directory):
    print("Creating new Chroma Directory " + persist_directory)
    os.makedirs(persist_directory)
else:
    # Load the existing Chroma vector store
    print("Path exists.")

  1. C# 中的参数传递:确保传递参数 在 C# 中正确。你做对了 myProcessStart.Arguments,但确保之间有空格 构造字符串时的参数。 例如:
myProcessStart.Arguments = $"\"{myPythonApp}\" \"{OllamDocsPath}\" \"{OllamaChromaFilename}\"";

  1. 错误处理:在 Python 脚本中添加错误处理以捕获任何错误 参数解析或路径处理问题。这可以帮助 更好地诊断问题。
try:
    OllamaPath = sys.argv[1]
    OllamaChroma = sys.argv[2]
except IndexError:
    print("Error: Not enough arguments passed from C#")
    sys.exit(1)

  1. 进程重定向:在 C# 代码中,您使用 UseShellExecute = true,这将禁用 RedirectStandardOutput。如果你想捕捉 Python 的输出(如 print 语句),您需要设置 UseShellExecute 设置为 false 并启用 RedirectStandardOutput = true:
myProcessStart.UseShellExecute = false;
myProcessStart.RedirectStandardOutput = true;

然后您可以捕获输出:

myProcess.OutputDataReceived += (sender, e) => 
{
    if (!String.IsNullOrEmpty(e.Data))
    {
        lblStatus.Text += e.Data;  // Update label with Python output
    }
};

myProcess.Start();
myProcess.BeginOutputReadLine();  // Start reading the output

  1. 检查文件路径:确保Python脚本和目录 存在并且您所经过的路径是正确的。你可能想要 检查路径对于正在运行的用户是否可访问且有效 应用程序。

按照这些步骤,您的 Python 脚本应该可以从 C# 成功触发,并且参数将正确传递。

© www.soinside.com 2019 - 2024. All rights reserved.