我找到了如何使用 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.")
从 C# 触发 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.")
myProcessStart.Arguments = $"\"{myPythonApp}\" \"{OllamDocsPath}\" \"{OllamaChromaFilename}\"";
try:
OllamaPath = sys.argv[1]
OllamaChroma = sys.argv[2]
except IndexError:
print("Error: Not enough arguments passed from C#")
sys.exit(1)
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
按照这些步骤,您的 Python 脚本应该可以从 C# 成功触发,并且参数将正确传递。