Run bash command in Cygwin from another application

不想你离开。 提交于 2019-12-19 09:24:25

问题


From a windows application written on C++ or python, how can I execute arbitrary shell commands?

My installation of Cygwin is normally launched from the following bat file:

@echo off

C:
chdir C:\cygwin\bin

bash --login -i

回答1:


From Python, run bash with os.system, os.popen or subprocess and pass the appropriate command-line arguments.

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



回答2:


The following function will run Cygwin's Bash program while making sure the bin directory is in the system path, so you have access to non-built-in commands. This is an alternative to using the login (-l) option, which may redirect you to your home directory.

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()

Example use:

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]



回答3:


Bash should accept a command from args when using the -c flag:

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

Combine that with C++'s exec or python's os.system to run the command.



来源:https://stackoverflow.com/questions/7513133/run-bash-command-in-cygwin-from-another-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!