简体   繁体   English

如何使用 python 在 CMD 中执行命令?

[英]How to execute commands in CMD using python?

I want to automate cmd commands using python but I also want the commands to show in CMD like I wrote them manually after launching the script.我想使用 python 自动化 cmd 命令,但我也希望命令显示在 CMD 中,就像我在启动脚本后手动编写的那样。 So for example, I want to use dir command in cmd, I tried doing that using subprocess module and the command executes properly but I also need the command to show like I wrote it myself before executing.因此,例如,我想在 cmd 中使用 dir 命令,我尝试使用 subprocess 模块执行此操作,并且该命令正确执行,但我还需要显示该命令,就像我在执行之前自己编写的一样。 I dont want the command to only execute and show the results.我不希望命令只执行并显示结果。 For example after launching the python script I want it to look like that:例如,在启动 python 脚本后,我希望它看起来像这样:

C:\Users\User\Bob>dir C:\Users\User\Bob>dir

And after that, the output of the command would show below.之后,命令的 output 将显示如下。 How do I do that?我怎么做?

My code that I used to execute dir command in cmd:我用来在 cmd 中执行 dir 命令的代码:

import subprocess, os
list_files = subprocess.run('dir', shell=True)
os.system("pause")

It executes the command just fine but I need the command as well.它执行命令很好,但我也需要命令。

There is a nice library called invoke which can help you to automate shell commands with python.有一个名为invoke的不错的库,它可以帮助您使用 python 自动化 shell 命令。 I've used it a couple times to do exactly that.我已经使用它几次来做到这一点。 You can install it via python -m pip install invoke .您可以通过python -m pip install invoke安装它。 To make it output the shell command itself as well as it's output you could use it like this:为了使它成为 output shell 命令本身以及它的 output 您可以像这样使用它:

from invoke import run
result = run("echo hello", hide=False, echo=True)

output would be output 将是

echo hi
hi

Have a look at the documentation for the runners here .这里查看跑步者的文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM