python - 如何在通过程序执行系统/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>
有什么解决办法吗?这对我有很大帮助!谢谢!
解决方案
while 1:
input1=input("Your Input")
if (input1=="date"):
import os
os.system('cmd /k "date"')
如果输入为 exit,您还可以添加一些逻辑来退出程序,例如,使用break
.
注意:我不建议重新导入os
内部循环,您可以将其导入外部并使用os.system
.
推荐阅读
- php - 包括带有提交表单而不刷新页面的php页面
- django - 内联表单集在保存时返回空列表?
- node.js - 错误:无法加载 gRPC 二进制模块
- c - 遍历转换为 void* 的数组
- android - 当发布数据显示此错误 Android 改造 Expected BEGIN_OBJECT but was STRING
- r - R 连接到 SQL Server
- c# - 在 C# windows 窗体应用程序中获取浏览器的活动 url
- python - 从 `matplotlib.patches.RegularPolygon` 继承在实例化时会产生 `ValueError`
- javascript - 将 Promise.race 与数据数组结合作为参数
- swift - 从字符串创建类类型以作为具体类型传递给泛型参数 Swift