使Python文本变为绿色并使用旋转光标 - 新手问题

时间:2017-02-08 10:54:51

标签: linux multithreading python-2.7 time subprocess

我想制作我的Python脚本文件,当我"宣布"给用户一些东西,像这样绿色:

dateFormat

如何做到这一点?我看到一个脚本使用它与sys.stdout.write,但我不明白如何使用它,我使用简单的"打印"命令..

另外,我希望只要此命令运行就会旋转Spinning游标,并且只有在此命令停止时才会停止(完成):

print('running network scan') output = subprocesss.check_output('nmap -sL 192.168.1.0/24',shell=True) print('Done')

任何方式(完成任务之前的未知时间)?

我正在使用TakenfromDyMerge建议的代码: nos

1 个答案:

答案 0 :(得分:1)

因此,关于将终端颜色变为绿色,有一个称为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)