0

I want to make my Python script file,when I "announce" something to the user, to be green like this:

TakenfromDyMerge

How can this be done?I saw a script using this with sys.stdout.write but I dont understand how to use it, Im using a simple "print" commands..

Also, I would like to have the Spinning cursor spin as long as this command runs and only stops when this command stops(finishes):

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

Any way to do that (unknown time until task is done)?

Im using a code suggested by nos here: Spinning Cursor

Community
  • 1
  • 1
eyal360
  • 33
  • 4

1 Answers1

2

So, about getting the terminal color to be green, there is a neat package called colorama that generally works great for me. To check whether the process is running or not, I would recommend using Popen instead of check_output, since the latter does not allow you to communicate with the process as far as I know. But you need to since you want to know if your subprocess is still running. Here is a little code example that should get you running:

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)
alexblae
  • 746
  • 1
  • 5
  • 13