我正在运行 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
, theCOMSPEC
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/