2011-09-22 124 views
2

从用C++或python编写的Windows应用程序中,如何执行任意shell命令?从另一个应用程序在Cygwin中运行bash命令

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

@echo off 

C: 
chdir C:\cygwin\bin 

bash --login -i 
+1

我愿做同样的事情,但我没有发现任何可能性,这将 –

回答

4

从Python中,运行的bash与os.systemos.popensubprocess,并通过适当的命令行参数。使用-c标志时

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

你能告诉我这个计划的一些例子是有用的? –

+0

谢谢,我正在尝试 –

+0

不,我的命令没有执行os.system(r“C:\ cygwin \ bin \ bash.exe -c \”〜/ project1/make \“”) –

1

猛砸应当接受来自ARGS的命令:

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

再加上C++的exec或Python的os.system运行命令。

+0

我认为我必须在我的python应用程序中运行Cygwin的新进程,因为:http://i.imgur.com/Anfla.png –

2

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