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

标签 linux multithreading python-2.7 time subprocess

我想让我的 Python 脚本文件,当我向用户“宣布”某事时,像这样变成绿色:

TakenfromDyMerge

如何做到这一点?我看到一个脚本将其与 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/

相关文章:

Python 子进程在一定数量的数据后失败

python - Python请求-线程/进程与IO

python-2.7 - 在 Python 2.7.13 上使用 pip 安装 sqlite 时出错

python-2.7 - python 中变量名末尾应该使用分号吗?

c linux多线程网络

c - Linux 上的 pthread 执行

java - 尽管使用了同步,wait()和notify()仍然不可靠吗?

python - 如何在类的 __init__ 函数中使用函数

c++ - 如何锁定需要只写的缓冲区?

linux - 访问未通过 EXPORT_SYMBOL* 导出的 Linux 内核符号