在另一个应用程序中运行Cygwin中的bash命令

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

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

@echo off C: chdir C:\cygwin\bin bash --login -i 

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

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

以下函数将运行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] 

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

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

将其与C ++的exec或python的os.system起来运行该命令。