argparse使用

该代码演示了如何使用Python的argparse模块定义和解析命令行参数。函数`parse_opt`创建了一个ArgumentParser对象,添加了三个带有默认值的参数`--a`,`--b`,`--c`,然后根据`known`参数选择性地解析已知或所有参数。在`main`函数中,打印出这些参数的值。
摘要由CSDN通过智能技术生成

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);
            }
          

        }
    }
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值