我是这门语言的新手。所以我想写一个 Python 应用程序。它将从用户那里获得输入并逐步将其粘贴到 CMD 中。因为我有多个输入。
我需要知道的:
提前感谢所有伙伴
答案 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