【问题标题】:How to keep Python command line of your Programme running after executing a system/shell/OS command through your Programme如何在通过程序执行系统/shell/OS 命令后保持程序的 Python 命令行运行
【发布时间】:2019-12-18 19:20:53
【问题描述】:

好的,所以我制作了一个 Python 程序,用于执行日期、时间、注销等命令。 它使用来自用户的输入来使用命令提示符执行这些命令(因为我使用的是 Windows),它可能在 Mac os 或 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>

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

【问题讨论】:

标签: python python-3.x windows loops cmd


【解决方案1】:
while 1:
    input1=input("Your Input")
    if (input1=="date"):
        import os
        os.system('cmd /k "date"')

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

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

【讨论】:

  • 谢谢,其实我找到了另一种方法,即使用 datetime 模块,我会试试这个并告诉你! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-20
相关资源
最近更新 更多