首页 > 解决方案 > 如何在通过程序执行系统/shell/OS 命令后保持程序的 Python 命令行运行

问题描述

好的,所以我制作了一个 Python 程序,用于执行日期、时间、注销等命令。它使用来自用户的输入来使用命令提示符执行这些命令(因为我使用的是 Windows),它可能会以类似的方式工作在 Mac 操作系统或 Kali shell 上。

因此,如果用户输入如下命令:

>>>date

输出将是这样的:

>>>The current date is: 12/18/19

这里使用的代码是:

     input1=input("Your Input")
     if (input1=="date"):
     import os
     os.system('cmd /k "date"')

这在 Python 运行的同一窗口中( C:\Windows\py.exe )给出了日期的输出。

在此之后,它给出以下内容:

The current date is: Wed 12/18/2019
Enter the new date: (mm-dd-yy)

C:\WINDOWS\system32>

但我不希望这个程序在显示日期后结束,我希望它循环并要求我再次输入命令。但即使在使用了:

while True:

上面的模块,它不会循环,只是在 Date 之后将其作为输出:

The current date is: Wed 12/18/2019
Enter the new date: (mm-dd-yy)  #when you press the Enter key, you get the following:

C:\WINDOWS\system32>

有什么解决办法吗?这对我有很大帮助!谢谢!

标签: pythonpython-3.xwindowsloopscmd

解决方案


while 1:
    input1=input("Your Input")
    if (input1=="date"):
        import os
        os.system('cmd /k "date"')

如果输入为 exit,您还可以添加一些逻辑来退出程序,例如,使用break.

注意:我不建议重新导入os内部循环,您可以将其导入外部并使用os.system.


推荐阅读