【发布时间】:2011-11-22 17:03:06
【问题描述】:
如何从用 C++ 或 python 编写的 Windows 应用程序执行任意 shell 命令?
我的 Cygwin 安装通常从以下 bat 文件启动:
@echo off
C:
chdir C:\cygwin\bin
bash --login -i
【问题讨论】:
-
我想做类似的事情,但我没有发现任何可能,这会很有用
如何从用 C++ 或 python 编写的 Windows 应用程序执行任意 shell 命令?
我的 Cygwin 安装通常从以下 bat 文件启动:
@echo off
C:
chdir C:\cygwin\bin
bash --login -i
【问题讨论】:
在 Python 中,使用 os.system、os.popen 或 subprocess 运行 bash,并传递适当的命令行参数。
os.system(r'C:\cygwin\bin\bash --login -c "some bash commands"')
【讨论】:
--login。我已经相应地修改了我的答案。
当使用 -c 标志时,Bash 应该接受来自 args 的命令:
C:\cygwin\bin\bash.exe -c "somecommand"
将它与 C++ 的 exec 或 python 的 os.system 结合起来运行命令。
【讨论】:
以下函数将运行 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]
【讨论】: