【问题标题】:Process.StartInfo with '*' character - finding distro of linuxProcess.StartInfo with '*' character - 查找Linux发行版
【发布时间】:2012-05-03 15:28:46
【问题描述】:

我的 linux 命令中的星号字符有点问题 - 我需要找出发行版。当我替换这个角色女巫时,例如'fedora' 那么这个命令给出了很好的结果。在这种情况下,它会这样写:/bin/cat: /etc/*-release: Directory or file doesn't exist.

我的代码是:

    Process p = new Process();
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.FileName = "cat";
    p.StartInfo.Arguments = "/etc/*-release";
    p.Start();
    string output = p.StandardOutput.ReadToEnd();
    p.WaitForExit();

提前感谢您的回答。 马特杰

【问题讨论】:

    标签: c# gtk#


    【解决方案1】:

    当您从 shell 运行 cat /etc/*-release 时,shell 负责将 * 扩展为匹配文件列表(如果有)。

    当您自己直接执行程序时(就像您在这里使用Process 接口所做的那样),您需要自己重新创建shell 的行为。这实际上是最好的,因为运行cat 从功能齐全的编程语言中读取文件有点傻——当然,该语言提供了一些简单的逻辑等价物:

    list = glob(/etc/*-release)
    foreach file in (list):
        fd = open(file, "read");
        contents = read(fd)
        close(fd)
        dosomething_with(contents)
    

    您可以使用任何您喜欢的机制来替换那里的glob() 位; a fellow stacker has provided his own glob() mechanism in another answer.

    【讨论】:

    • 谢谢。您知道如何运行这样的命令:iptables -L | grep Protect_blacklist | wc -l 吗?我试过p.StartInfo.FileName = "iptables"; p.StartInfo.Arguments = "-L | grep Protect_blacklist | wc -l"; 但没有成功。提前致谢。
    • 那些| 不是命令的参数;它们是外壳元字符。您可能可以在您的命令中使用sh -c "iptables -L | grep Protect_blacklist | wc -l",但只执行iptables -L 然后在您的编程语言内部进行过滤和行计数也不会那么糟糕。 (无论哪种方式都可能很好。)
    猜你喜欢
    • 2011-05-19
    • 2011-02-14
    • 1970-01-01
    • 2015-06-17
    • 2017-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多