使用Python打开命令窗口并向其传递内容

2024-10-06 06:26:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在使用一个软件包,该软件包允许您创建Python脚本并从该软件包中执行它们。任何脚本的结果都会保存回程序中。脚本执行时,不会显示命令提示窗口

是否有一种简单的方法可以从脚本内部打开命令提示窗口并传递信息以供显示,例如数据帧标题、字符串或值列表

我从之前的SO帖子中发现,我可以使用:

import os
os.system('cmd /k "Some random text"')

这与预期一样有效,但当我使用以下代码时:

x = str(2 * 2)
output= f'cmd /k "{x}"'

os.system(output)

数字4被传递到命令窗口,但出现以下消息:

'4' is not recognized as an internal or external command, operable program or batch file.


Tags: or数据方法字符串命令程序脚本cmd
2条回答

改用子流程

“subprocess”比“Os”有更多的好处:
  1. The subprocess module provides a consistent interface to creating and working with additional processes.
  2. It offers a higher-level interface than some of the other available modules, and is intended to replace functions such as os.system(), os.spawn*(), os.popen*(), popen2.*() and commands.*().
    Reference

如果要在另一个cmd选项卡中编写类似于打印4的内容,请执行以下操作:

import subprocess
var = '4'
subprocess.Popen(['start','cmd','/k','echo',var], shell = True, stdin = subprocess.PIPE, stdout = subprocess.PIPE, text = True)

结果:
enter image description here

  • 它打开另一个cmd选项卡并传递一个命令,如echo var

答案在问题中

'4' is not recognized as an internal or external command, operable program or batch file.

打开cmd并键入它将给出错误的任何内容,除非我们键入cmd可以识别的内容。e、 g一个帮助命令

如果我们想在cmd中输入一些东西,并让它在控制台上得到处理/打印,我们就使用一个命令

echo

enter image description here

在您的程序中,只有echo命令丢失,这将使您的输出打印在cmd上

enter image description here

Last but not the least, always remember the ZEN of Python

enter image description here

相关问题 更多 >