从用户处获取输入并粘贴到命令提示符| Python中

2024-04-19 22:55:54 发布

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

我是这门语言的新手。所以我想写一个Python应用程序。它将从用户处获取输入并逐步粘贴到CMD中。因为我有多个输入

我需要知道的是:

  1. 假设我发出“date”这样的命令,cmd会询问我新的日期。因此,我需要在为用户执行命令之前获取该值
  2. 类似地,我希望在执行命令之前从用户那里获取2-3个输入,而不是执行命令,并且Python将自动填充cmd中的询问内容
  3. 我还想在后台做。不希望用户正在观看节目正在使用cmd
  4. 要在GUI中显示登录。就像第一个输入是粘贴。。。第二个输入是粘贴。。。粘贴

感谢所有队友的支持


Tags: 用户命令cmd语言应用程序内容date粘贴
1条回答
网友
1楼 · 发布于 2024-04-19 22:55:54
import os
command = input("Enter the command to be executed on CMD : ")
os.system(f'cmd /c "{command}"') #Executes the command on CMD which is running in  background and it gets closes as soon as the output is generated

上面的代码不会打开CMD并键入命令,而是在后台执行CMD并打印命令的输出

例如:

>>> Enter the command to be executed on CMD : net user
>>> User accounts for \\DESKTOP-XYZ

                                       -
Administrator            DefaultAccount           Guest
USER1                    USER2                    GuestAcc
The command completed successfully.

如果您想将命令的输出存储在文本文件中,那么 替换
os.system(f'cmd /c "{command}"')os.system(f'cmd /c "{command}>txt_file_name.txt"')

因此,如果您还想存储输出,最后的代码是:

import os
command = input("Enter the command to be executed on CMD : ")
os.system(f'cmd /c "{command}>txt_file_name.txt"') 
'''
It executes the command and stores the output in .txt file named as 'txt_file_name.txt' 
which is saved in the same path as of the source code
'''

还有一些命令需要管理员权限才能执行。对于这些命令,上述代码将返回一个错误,并且无法正确执行。如果您希望执行管理命令,那么您可以参考this

相关问题 更多 >