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

时间:2021-01-04 08:16:32

标签: python user-interface logging user-input command-prompt

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

我需要知道的:

  1. 假设我给出了诸如“日期”之类的命令,而 cmd 正在询问我的新日期。所以我需要在为用户执行命令之前取值。
  2. 类似我想在执行命令之前从用户那里获取 2-3 个输入,而不是命令将被执行,并且来自 cmd 的询问将被 Python 自动填充。
  3. 我也想在后台执行此操作。不希望该用户正在观看正在使用 cmd 的程序。
  4. 想要在 GUI 中显示日志。就像第一个输入正在粘贴...第二个输入正在粘贴...粘贴!

提前感谢所有伙伴

1 个答案:

答案 0 :(得分:0)

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