【问题标题】:Run bash command in Cygwin from another application从另一个应用程序在 Cygwin 中运行 bash 命令
【发布时间】:2011-11-22 17:03:06
【问题描述】:

如何从用 C++ 或 python 编写的 Windows 应用程序执行任意 shell 命令?

我的 Cygwin 安装通常从以下 bat 文件启动:

@echo off

C:
chdir C:\cygwin\bin

bash --login -i

【问题讨论】:

  • 我想做类似的事情,但我没有发现任何可能,这会很有用

标签: c++ python windows cygwin


【解决方案1】:

在 Python 中,使用 os.systemos.popensubprocess 运行 bash,并传递适当的命令行参数。

os.system(r'C:\cygwin\bin\bash --login -c "some bash commands"')

【讨论】:

  • 你能给我一些这个程序的例子吗?
  • 不,我的命令没有执行 os.system(r"C:\cygwin\bin\bash.exe -c \"~/project1/make\"")
  • 我自己刚试了一下,发现需要在bash命令行中添加--login。我已经相应地修改了我的答案。
【解决方案2】:

当使用 -c 标志时,Bash 应该接受来自 args 的命令:

C:\cygwin\bin\bash.exe -c "somecommand"

将它与 C++ 的 exec 或 python 的 os.system 结合起来运行命令。

【讨论】:

  • 我认为我必须在我的 python 应用程序中运行 Cygwin 的新进程,因为:i.imgur.com/Anfla.png
【解决方案3】:

以下函数将运行 Cygwin 的 Bash 程序,同时确保 bin 目录位于系统路径中,因此您可以访问非内置命令。这是使用登录 (-l) 选项的替代方法,它可能会将您重定向到您的主目录。

def cygwin(command):
    """
    Run a Bash command with Cygwin and return output.
    """
    # Find Cygwin binary directory
    for cygwin_bin in [r'C:\cygwin\bin', r'C:\cygwin64\bin']:
        if os.path.isdir(cygwin_bin):
            break
    else:
        raise RuntimeError('Cygwin not found!')
    # Make sure Cygwin binary directory in path
    if cygwin_bin not in os.environ['PATH']:
        os.environ['PATH'] += ';' + cygwin_bin
    # Launch Bash
    p = subprocess.Popen(
        args=['bash', '-c', command],
        stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    p.wait()
    # Raise exception if return code indicates error
    if p.returncode != 0:
        raise RuntimeError(p.stderr.read().rstrip())
    # Remove trailing newline from output
    return (p.stdout.read() + p.stderr.read()).rstrip()

使用示例:

print cygwin('pwd')
print cygwin('ls -l')
print cygwin(r'dos2unix $(cygpath -u "C:\some\file.txt")')
print cygwin(r'md5sum $(cygpath -u "C:\another\file")').split(' ')[0]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-11
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多