3

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
Adam R. Grey
  • 1,861
  • 17
  • 30
G-71
  • 3,626
  • 12
  • 45
  • 69

3 Answers3

5

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"')
Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
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]
1

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.

agf
  • 171,228
  • 44
  • 289
  • 238
David C. Bishop
  • 6,437
  • 3
  • 28
  • 22
  • i think that i must run new process of Cygwin in my python application, because: http://i.imgur.com/Anfla.png – G-71 Sep 22 '11 at 11:31