python - 有没有办法可以用 bash 而不是 cmd 进行编译?

标签 python linux windows bash

我正在运行 Windows 10,并且我正在观看运行 Linux 的某人。

他正在教授 subprocess 模块,并演示如何通过终端(在 Linux 中)调用命令。

我的问题是Linux的命令与Windows中的命令不同,例如对于ifconfig,您需要在Windows中调用ipconfig/all

因此我前往 Microsoft Store 下载了一款名为 Kali Linux 的产品。

我的问题是如何在 Visual Studio 中使用 bash 而不是 cmd?

示例:

import subprocess

# Linux command
subprocess.call('ifconfig', shell=True)

# Windows command
subprocess.call('ipconfig /all', shell=True)

Python 终端或 cmd 无法识别 ifconfig 命令。

最佳答案

我假设您安装了适用于 Linux 的 Windows 子系统 (WSL)。使用 WSL,您可以从 Windows 的 cmd 中执行 bash。您只需使用其 -c 选项将要在 bash 中执行的命令传递给 bash 命令即可:

subprocess.call('bash -c ifconfig', shell=True)

请注意,整个命令必须作为单个参数传递给 bash。也就是说,如果你想执行ls -l,你必须使用bash -c "ls -l"

如果您想使用多个 subprocess.call 执行多个命令,那么您必须在每次调用中使用 bash -c 或更改默认 shell(请参阅 python's manual ):

On Windows with shell=True, the COMSPEC environment variable specifies the default shell.

cmd 命令 where bash 显示您必须在 COMPSPEC 中指定的路径,以将默认 shell 更改为 bash。在我的 Windows 10 系统上,它是 C:\Windows\System32\bash.exe

关于python - 有没有办法可以用 bash 而不是 cmd 进行编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59446585/

相关文章:

linux - 如何在 linux shell 脚本中计算日期 -N?

windows - 如何在用户桌面上创建到计算机的快捷方式

windows - 跟踪 Windows 注册表中的更改

windows - Windows上的Qt dll部署

python - 在 Python 中对齐两侧的文本

python - 使用 Tornado 和 Prototype 的异步 COMET 查询

linux - 内核调度程序中的 CFS 和 FIFO

linux - GCC 编译因 pthread 和选项 std=c99 而失败

python - 将列表从数据帧转换为 numpy 数组

Python matplotlib 在 Windows 7 上为 freetype、png 包安装问题