2017-02-08 33 views
0

我要讓我的Python腳本文件,當我「宣佈」的東西給用戶,是綠色的是這樣的:使Python的文本綠色和使用紡紗光標 - 新手問題

TakenfromDyMerge

哪有這是做?我看到一個腳本使用這與sys.stdout.write,但我不明白如何使用它,我使用一個簡單的「打印」命令..

此外,我想旋轉游標旋轉只要此命令運行並且僅在此命令停止時結束(完成):

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

任何方式做到這一點(未知的時間,直到完成任務)?

即時通訊使用nos這裏建議代碼: Spinning Cursor

回答

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) 
+0

完美地工作,因爲我想..謝謝! – eyal360