argparse使用
import argparse
def parse_opt(known=False):
parser = argparse.ArgumentParser()
parser.add_argument('--a', type=str, default="1", help='1')
parser.add_argument('--b', type=str, default='2', help='2')
parser.add_argument('--c', type=str, default="3", help='3')
opt = parser.parse_known_args()[0] if known else parser.parse_args()
return opt
def main(opt):
print(opt.a)
print(opt.b)
print(opt.c)
if __name__ == "__main__":
opt = parse_opt()
main(opt)
测试
python main.py --a 231 --b 12312 --c 999
C# 调用
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AI_PUCP
{
public partial class FrmMain : Form
{
public FrmMain()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
//调用Python程序
Process p = new Process();//开启一个新进程
string filePath = @"D:\workplace\python\PUCP_Test1\main.py";//参数由目标应用程序进行分析和解释,因此必须与该应用程序的预期保持一致。
p.StartInfo.FileName = @"D:\software\Anaconda3\python.exe";//要启动的应用程序的名称
p.StartInfo.Arguments = filePath+" --a 123123 --b 5678 --c 9874";
p.StartInfo.UseShellExecute = false;//不使用shell
p.StartInfo.RedirectStandardOutput = true;//捕获输出的消息
p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
p.StartInfo.RedirectStandardError = true;//重定向标准错误输出
p.StartInfo.CreateNoWindow = false;//为true,则启动该进程而不新建窗口
p.StartInfo.StandardErrorEncoding = Encoding.UTF8;//将编码设置成utf-8,保证中文不会乱码。
p.Start();//开始进程
string output = p.StandardOutput.ReadToEnd();
MessageBox.Show(output);
p.WaitForExit();
p.Close();
MessageBox.Show("执行完毕");
}
catch (Exception ex)
{
MessageBox.Show("报错信息:" + ex.Message);
}
}
}
}