我想让我的 Python 脚本文件,当我向用户“宣布”某事时,像这样变成绿色:
如何做到这一点?我看到一个脚本将其与 sys.stdout.write 一起使用,但我不明白如何使用它,我使用的是简单的“打印”命令..
此外,只要此命令运行并且仅当此命令停止(完成)时才停止,我希望旋转光标旋转:
print('运行网络扫描')
output = subprocesss.check_output('nmap -sL 192.168.1.0/24',shell=True)
打印('完成')
有什么方法可以做到这一点(任务完成前未知时间)?
我正在使用 nos 建议的代码这里: Spinning Cursor
最佳答案
因此,关于将终端颜色设置为绿色,有一个名为 colorama 的简洁包这通常对我很有用。要检查进程是否正在运行,我建议使用 Popen
而不是 check_output
,因为据我所知,后者不允许您与进程通信.但是你需要这样做,因为你想知道你的子进程是否仍在运行。这是一个应该让您运行的小代码示例:
import subprocess
import shlex
import time
import sys
import colorama
def spinning_cursor():
"""Spinner taken from http://stackoverflow.com/questions/4995733/how-to-create-a-spinning-command-line-cursor-using-python/4995896#4995896."""
while True:
for cursor in '|/-\\':
yield cursor
# Create spinner
spinner = spinning_cursor()
# Print and change color to green
print(colorama.Fore.GREEN + 'running network scan')
# Define command we want to run
cmd = 'your command goes here'
# Split args for POpen
args=shlex.split(cmd)
# Create subprocess
p = subprocess.Popen(args,stdout=subprocess.PIPE)
# Check if process is still running
while p.poll()==None:
# Print spinner
sys.stdout.write(spinner.next())
sys.stdout.flush()
sys.stdout.write('\b')
print('Done')
# Grab output
output=p.communicate()[0]
# Reset color (otherwise your terminal is green)
print(colorama.Style.RESET_ALL)
关于linux - 使 Python 文本变绿并使用旋转光标 - 新手问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42111167/