【问题标题】:How to access command line arguments in .csx script?如何访问 .csx 脚本中的命令行参数?
【发布时间】:2016-07-22 14:30:24
【问题描述】:

我正在使用csi.exe C# 交互式编译器来运行.csx 脚本。如何访问提供给我的脚本的任何命令行参数?

csi script.csx 2000

如果您不熟悉 csi.exe,以下是使用信息:

>csi /?
Microsoft (R) Visual C# Interactive Compiler version 1.3.1.60616
Copyright (C) Microsoft Corporation. All rights reserved.

Usage: csi [option] ... [script-file.csx] [script-argument] ...

Executes script-file.csx if specified, otherwise launches an interactive REPL (Read Eval Print Loop).

【问题讨论】:

标签: c# c#-interactive csi


【解决方案1】:

CSI 有一个Args global which parses out the arguments for you。在大多数情况下,这将为您提供所需的参数,就像您在 C/C++ 程序中访问 argv 或在 C# Main() 签名 static void Main(string[] args) 中访问 args 一样。

Args 的类型是 IList<string> 而不是 string[]。所以你将使用.Count而不是.Length来查找参数的数量。

以下是一些用法示例:

#!/usr/bin/env csi
Console.WriteLine($"There are {Args.Count} args: {string.Join(", ", Args.Select(arg => $"“{arg}”"))}");

还有一些示例调用:

ohnob@DESKTOP-RC0QNSG MSYS ~/AppData/Local/Temp
$ ./blah.csx
There are 0 args:

ohnob@DESKTOP-RC0QNSG MSYS ~/AppData/Local/Temp
$ ./blah.csx hi, these are args.
There are 4 args: “hi,”, “these”, “are”, “args.”

ohnob@DESKTOP-RC0QNSG MSYS ~/AppData/Local/Temp
$ ./blah.csx 'hi, this is one arg.'
There are 1 args: “hi, this is one arg.”

【讨论】:

    【解决方案2】:

    这是我的脚本:

        var t = Environment.GetCommandLineArgs();
        foreach (var i in t)
            Console.WriteLine(i);
    

    将参数传递给 csx:

        scriptcs hello.csx -- arg1 arg2 argx
    

    打印出来:

        hello.csx
        --
        arg1
        arg2
        argx
    

    键是 csx 和脚本参数之间的“--”。

    【讨论】:

    • @binki 这应该是它自己的答案,而不是评论。
    • @ChrisCharabaruk 我已将其提升为答案并删除了我的评论。谢谢!
    【解决方案3】:

    Environment.GetCommandLineArgs() 在该示例中返回 ["csi", "script.csx", "2000"]。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-31
    • 2020-09-30
    • 2022-01-19
    • 2017-09-08
    • 1970-01-01
    • 2014-07-24
    相关资源
    最近更新 更多