如何在没有 .exe 文件的情况下从 C# 运行 python
How to run python from C# without .exe file
我是一个 Python 初学者,并从我的 C# 代码中写了一些 Python 我想 运行 的代码。
在我已经看到的所有答案中,方法是从 .py 文件创建一个 .exe 文件,然后 运行 通过系统调用。
但是,我想要它,这样我就不需要制作 .exe 文件,并且可以像在命令行中一样编写带有参数的命令。
C:\Users\ntuser> python C:\Users\ntuser\Documents\run_python.py 3
有办法吗?
我找到了一种只传递一个命令的方法——但我需要做两个: 1. 转到“C:\Users\ntuser” 2. 运行 Python 代码。
谢谢!
好的,所以我找到了解决方案。
感谢 UnholySheep 的帮助。
您需要做的是:
- 将 python 设为 system variable
通过代码转到您的主目录:
Directory.SetCurrentDirectory(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile));
添加此代码以调用 python 代码:
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;//if you want to hide the window
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/C python pytonPath\python_code.py";
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();//if you want to wait
我是一个 Python 初学者,并从我的 C# 代码中写了一些 Python 我想 运行 的代码。
在我已经看到的所有答案中,方法是从 .py 文件创建一个 .exe 文件,然后 运行 通过系统调用。
但是,我想要它,这样我就不需要制作 .exe 文件,并且可以像在命令行中一样编写带有参数的命令。
C:\Users\ntuser> python C:\Users\ntuser\Documents\run_python.py 3
有办法吗? 我找到了一种只传递一个命令的方法——但我需要做两个: 1. 转到“C:\Users\ntuser” 2. 运行 Python 代码。
谢谢!
好的,所以我找到了解决方案。 感谢 UnholySheep 的帮助。
您需要做的是:
- 将 python 设为 system variable
通过代码转到您的主目录:
Directory.SetCurrentDirectory(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile));
添加此代码以调用 python 代码:
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;//if you want to hide the window
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/C python pytonPath\python_code.py";
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();//if you want to wait