You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET使用Process调用带参数exe输出始终为0的问题求助

问题原因及修复方案

1. 修复Python打包代码逻辑

你当前的Python代码没有读取传入的命令行参数,user_input变量未初始化默认值为0,所以执行后永远输出0,这是核心问题。修改后的Python代码如下:

import sys

# 读取命令行第一个参数转为整数
try:
    user_input = int(sys.argv[1])
except (IndexError, ValueError):
    # 无参数或参数非数字时输出错误
    print("invalid input")
    sys.exit(1)

_rev = 0
while user_input > 0:
    dig = user_input % 10
    _rev = _rev * 10 + dig
    user_input = user_input // 10
print(_rev)

修改完成后重新打包为exe替换原有文件即可。

2. 修复C#调用代码逻辑

你当前的代码在启动异步读取输出后,没有等待进程执行完成、也没有等待输出读取完成就直接读取输出内容,大概率会拿到空值或不完整结果。修改后的C#代码如下:

System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.FileName = Server.MapPath("~/Content/reverse.exe");
process.StartInfo.Arguments = UI.UserInput;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;

process.Start();

StringBuilder output = new StringBuilder();
StringBuilder error = new StringBuilder();

using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
{
    process.OutputDataReceived += (sender, e) => {
        if (e.Data == null)
        {
            outputWaitHandle.Set();
        }
        else
        {
            output.AppendLine(e.Data);
        }
    };
    process.ErrorDataReceived += (sender, e) =>
    {
        if (e.Data == null)
        {
            errorWaitHandle.Set();
        }
        else
        {
            error.AppendLine(e.Data);
        }
    };

    process.BeginOutputReadLine();
    process.BeginErrorReadLine();

    // 增加等待逻辑,设置10秒超时避免进程卡死
    if (process.WaitForExit(10000) 
        && outputWaitHandle.WaitOne(10000)
        && errorWaitHandle.WaitOne(10000))
    {
        // 去掉输出内容多余的换行符
        UI.Output = output.ToString().Trim();
        // 可在此处添加错误输出的处理逻辑
    }
    else
    {
        UI.Output = "执行超时";
    }
}
process.Dispose();

额外注意事项

  • 如果输入可能包含负数,需要在Python代码中单独处理符号逻辑,当前反转逻辑仅支持正整数
  • 部署到IIS时需要确认站点运行身份对reverse.exe有执行权限,避免权限不足导致执行失败

内容的提问来源于stack exchange,提问作者kostas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 08:15:04