2011-09-22 126 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] 
相關問題