标签归档:terminal

终端中的Python脚本执行命令

问题:终端中的Python脚本执行命令

我在某个地方读过这篇文章,但似乎找不到。我试图找到一个将在终端中执行命令然后输出结果的命令。

例如:脚本将是:

command 'ls -l'

它将在终端中运行该命令的结果

I read this somewhere a while ago but cant seem to find it. I am trying to find a command that will execute commands in the terminal and then output the result.

For example: the script will be:

command 'ls -l'

It will out the result of running that command in the terminal


回答 0

做这件事有很多种方法:

一种简单的方法是使用os模块:

import os
os.system("ls -l")

子流程模块可以实现更复杂的事情:例如:

import subprocess
test = subprocess.Popen(["ping","-W","2","-c", "1", "192.168.1.70"], stdout=subprocess.PIPE)
output = test.communicate()[0]

There are several ways to do this:

A simple way is using the os module:

import os
os.system("ls -l")

More complex things can be achieved with the subprocess module: for example:

import subprocess
test = subprocess.Popen(["ping","-W","2","-c", "1", "192.168.1.70"], stdout=subprocess.PIPE)
output = test.communicate()[0]

回答 1

我更喜欢使用子流程模块:

from subprocess import call
call(["ls", "-l"])

原因是,如果您想在脚本中传递一些变量,这将提供非常简单的方法,例如,采用以下代码部分

abc = a.c
call(["vim", abc])

I prefer usage of subprocess module:

from subprocess import call
call(["ls", "-l"])

Reason is that if you want to pass some variable in the script this gives very easy way for example take the following part of the code

abc = a.c
call(["vim", abc])

回答 2

实际上,关于子流程的任何问题都将是一本好书


回答 3

您还应该查看commands.getstatusoutput

这将返回一个长度为2的元组。第一个是返回整数(0-命令成功时),第二个是整个输出,如终端所示。

对于ls

    import commands
    s=commands.getstatusoutput('ls')
    print s
    >> (0, 'file_1\nfile_2\nfile_3')
    s[1].split("\n")
    >> ['file_1', 'file_2', 'file_3']

You should also look into commands.getstatusoutput

This returns a tuple of length 2.. The first is the return integer ( 0 – when the commands is successful ) second is the whole output as will be shown in the terminal.

For ls

    import commands
    s=commands.getstatusoutput('ls')
    print s
    >> (0, 'file_1\nfile_2\nfile_3')
    s[1].split("\n")
    >> ['file_1', 'file_2', 'file_3']

回答 4

import os
os.system("echo 'hello world'")

这应该工作。我不知道如何将输出打印到python Shell中。

import os
os.system("echo 'hello world'")

This should work. I do not know how to print the output into the python Shell.


回答 5

os.popen()是非常简单的使用,但因为Python 2.6已经过时。您应该改为使用子流程模块。

在此处阅读:将os.popen(command)读入字符串

The os.popen() is pretty simply to use, but it has been deprecated since Python 2.6. You should use the subprocess module instead.

Read here: reading a os.popen(command) into a string


回答 6

朱皮特

在Jupyter笔记本电脑中,您可以使用魔术功能 !

!echo "execute a command"
files = !ls -a /data/dir/ #get the output into a variable

ipython的

要将其作为.py脚本执行,您需要使用ipython

files = get_ipython().getoutput('ls -a /data/dir/')

执行脚本

$ ipython my_script.py

Jupyter

In a jupyter notebook you can use the magic function !

!echo "execute a command"
files = !ls -a /data/dir/ #get the output into a variable

ipython

To execute this as a .py script you would need to use ipython

files = get_ipython().getoutput('ls -a /data/dir/')

execute script

$ ipython my_script.py

回答 7

您可以导入“ os”模块并像这样使用它:

import os
os.system('#DesiredAction')

You could import the ‘os’ module and use it like this :

import os
os.system('#DesiredAction')

回答 8

对于python3使用子进程

import subprocess
s = subprocess.getstatusoutput(f'ps -ef | grep python3')
print(s)

for python3 use subprocess

import subprocess
s = subprocess.getstatusoutput(f'ps -ef | grep python3')
print(s)

为什么apt-get功能在Mac OS X v10.9(Mavericks)的终端中不起作用?

问题:为什么apt-get功能在Mac OS X v10.9(Mavericks)的终端中不起作用?

我正在观看此视频,如您所见,告诉我的第一个命令是:

sudo apt-get install python-setuptools

当我这样做时,它输出:

sudo: apt-get: command not found

我不知道为什么会这样。

如何解决此问题,以便正确遵循本教程?

I was watching this, and, as you can see, the first command I am told to put in is:

sudo apt-get install python-setuptools

When I do this, it outputs:

sudo: apt-get: command not found

I have no idea why this is the case.

How can I resolve this so I am following the tutorial correctly?


回答 0

Mac OS X没有apt-get。有一个叫做Homebrew的程序包管理器代替了。

该命令将是:

brew安装python

使用Homebrew安装否则会用到的软件包apt-get

我链接到的页面具有安装Homebrew的最新方法,但是目前,您可以按以下方式安装Homebrew:

在Mac OS X终端中键入以下内容:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

在那之后,Homebrew的用法为brew install <package>

XCode命令行工具是Homebrew的前提条件之一。

  1. 从App Store安装XCode。
  2. 请按照此Stack Overflow答案中的说明安装XCode命令行工具

背景

软件包管理器(如apt-getbrew)只是为您的系统提供了一种简单且自动化的安装软件包或库的方法。不同的系统使用不同的程序。 apt及其派生类在基于Debian的linux系统上使用。使用Red Hat式的Linux系统rpm(或者至少在很多年前,他们做了很多)。 yum还是基于RedHat的系统的软件包管理器。

基于高山的系统使用apk

警告

自2016年4月25日起,默认情况下自制软件会选择让用户加入分析。可以通过两种方式选择退出:

设置环境变量:

  1. 打开您喜欢的环境变量编辑器
  2. 进行以下设置:HOMEBREW_NO_ANALYTICS=1 在保存环境变量的任何地方(通常是~/.bash_profile
  3. 关闭文件,然后重新启动终端或source ~/.bash_profile

运行以下命令:

brew analytics off

然后可以使用以下命令检查分析状态:

brew analytics

Mac OS X doesn’t have apt-get. There is a package manager called Homebrew that is used instead.

This command would be:

brew install python

Use Homebrew to install packages that you would otherwise use apt-get for.

The page I linked to has an up-to-date way of installing homebrew, but at present, you can install Homebrew as follows:

Type the following in your Mac OS X terminal:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

After that, usage of Homebrew is brew install <package>.

One of the prerequisites for Homebrew are the XCode command line tools.

  1. Install XCode from the App Store.
  2. Follow the directions in this Stack Overflow answer to install the XCode Command Line Tools.

Background

A package manager (like apt-get or brew) just gives your system an easy and automated way to install packages or libraries. Different systems use different programs. apt and its derivatives are used on Debian based linux systems. Red Hat-ish Linux systems use rpm (or at least they did many, many, years ago). yum is also a package manager for RedHat based systems.

Alpine based systems use apk.

Warning

As of 25 April 2016, homebrew opts the user in to sending analytics by default. This can be opted out of in two ways:

Setting an environment variable:

  1. Open your favorite environment variable editor.
  2. Set the following: HOMEBREW_NO_ANALYTICS=1 in whereever you keep your environment variables (typically something like ~/.bash_profile)
  3. Close the file, and either restart the terminal or source ~/.bash_profile.

Running the following command:

brew analytics off

the analytics status can then be checked with the command:

brew analytics

回答 1

因为Homebrew是我在macOS上的最爱,尽管有可能apt-get使用Fink在macOS上使用。

As Homebrew is my favorite for macOS although it is possible to have apt-get on macOS using Fink.


回答 2

MacPorts是OS X的另一个软件包管理器:。

安装说明在该MacPorts的项目-下载和安装之后,一个问题sudo port install pythonXX,这里XX2735

MacPorts is another package manager for OS X:.

Installation instructions are at The MacPorts Project — Download & Installation after which one issues sudo port install pythonXX, where XX is 27 or 35.


回答 3

Conda也可以用作程序包管理器。可以从Anaconda安装。

另外,一个免费的最小安装程序是Miniconda

Conda can also be used as package manager. It can be installed from Anaconda.

Alternatively, a free minimal installer is Miniconda.


回答 4

您还可以使用curl命令安装东西,只要在URL提及apt-get的地方…

例如,

curl -O http://www.magentocommerce.com/downloads/assets/1.8.1.0/magento-1.8.1.0.tar.gz

Alternatively You can use the brew or curl command for installing things, wherever apt-get is mentioned with a URL…

For example,

curl -O http://www.magentocommerce.com/downloads/assets/1.8.1.0/magento-1.8.1.0.tar.gz

Http-prompt 构建在HTTPie之上的交互式命令行HTTP和API测试客户端,具有自动完成、语法突出显示等功能

如何在Python中获取Linux控制台窗口宽度

问题:如何在Python中获取Linux控制台窗口宽度

python中有没有办法以编程方式确定控制台的宽度?我的意思是不换行就适合一行的字符数,而不是窗口的像素宽度。

编辑

寻找适用于Linux的解决方案

Is there a way in python to programmatically determine the width of the console? I mean the number of characters that fits in one line without wrapping, not the pixel width of the window.

Edit

Looking for a solution that works on Linux


回答 0

import os
rows, columns = os.popen('stty size', 'r').read().split()

使用“ stty size”命令,该命令根据python邮件列表上的线程在linux上相当普遍。它以文件形式打开“ stty size”命令,并从中“读取”,并使用简单的字符串拆分来分隔坐标。

与os.environ [“ COLUMNS”]值(尽管使用bash作为我的标准Shell不能访问)不同,数据也将是最新的,而我相信os.environ [“ COLUMNS”]该值仅在python解释器启动时有效(假设从那时起用户调整了窗口的大小)。

(有关如何在python 3.3+上执行此操作,请参见@GringoSuave的回答)

import os
rows, columns = os.popen('stty size', 'r').read().split()

uses the ‘stty size’ command which according to a thread on the python mailing list is reasonably universal on linux. It opens the ‘stty size’ command as a file, ‘reads’ from it, and uses a simple string split to separate the coordinates.

Unlike the os.environ[“COLUMNS”] value (which I can’t access in spite of using bash as my standard shell) the data will also be up-to-date whereas I believe the os.environ[“COLUMNS”] value would only be valid for the time of the launch of the python interpreter (suppose the user resized the window since then).

(See answer by @GringoSuave on how to do this on python 3.3+)


回答 1

不知道为什么它在模块中shutil,但是它在Python 3.3中降落在那里,查询输出终端的大小

>>> import shutil
>>> shutil.get_terminal_size((80, 20))  # pass fallback
os.terminal_size(columns=87, lines=23)  # returns a named-tuple

os模块中有一个底层实现。在Windows中也可以使用。

反向移植现在可用于Python 3.2及以下版本:

Not sure why it is in the module shutil, but it landed there in Python 3.3, Querying the size of the output terminal:

>>> import shutil
>>> shutil.get_terminal_size((80, 20))  # pass fallback
os.terminal_size(columns=87, lines=23)  # returns a named-tuple

A low-level implementation is in the os module. Also works in Windows.

A backport is now available for Python 3.2 and below:


回答 2

import console
(width, height) = console.getTerminalSize()

print "Your terminal's width is: %d" % width

编辑:哦,对不起。那不是python标准库,这是console.py的来源(我不知道它来自哪里)。

该模块似乎像这样工作:检查是否termcap可用,何时可用。它使用它;如果不是,它将检查终端是否支持特殊ioctl调用,并且该调用也不起作用,它将检查某些shell为此导出的环境变量。这可能仅适用于UNIX。

def getTerminalSize():
    import os
    env = os.environ
    def ioctl_GWINSZ(fd):
        try:
            import fcntl, termios, struct, os
            cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ,
        '1234'))
        except:
            return
        return cr
    cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
    if not cr:
        try:
            fd = os.open(os.ctermid(), os.O_RDONLY)
            cr = ioctl_GWINSZ(fd)
            os.close(fd)
        except:
            pass
    if not cr:
        cr = (env.get('LINES', 25), env.get('COLUMNS', 80))

        ### Use get(key[, default]) instead of a try/catch
        #try:
        #    cr = (env['LINES'], env['COLUMNS'])
        #except:
        #    cr = (25, 80)
    return int(cr[1]), int(cr[0])

use

import console
(width, height) = console.getTerminalSize()

print "Your terminal's width is: %d" % width

EDIT: oh, I’m sorry. That’s not a python standard lib one, here’s the source of console.py (I don’t know where it’s from).

The module seems to work like that: It checks if termcap is available, when yes. It uses that; if no it checks whether the terminal supports a special ioctl call and that does not work, too, it checks for the environment variables some shells export for that. This will probably work on UNIX only.

def getTerminalSize():
    import os
    env = os.environ
    def ioctl_GWINSZ(fd):
        try:
            import fcntl, termios, struct, os
            cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ,
        '1234'))
        except:
            return
        return cr
    cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
    if not cr:
        try:
            fd = os.open(os.ctermid(), os.O_RDONLY)
            cr = ioctl_GWINSZ(fd)
            os.close(fd)
        except:
            pass
    if not cr:
        cr = (env.get('LINES', 25), env.get('COLUMNS', 80))

        ### Use get(key[, default]) instead of a try/catch
        #try:
        #    cr = (env['LINES'], env['COLUMNS'])
        #except:
        #    cr = (25, 80)
    return int(cr[1]), int(cr[0])

回答 3

上面的代码未在我的Linux上返回正确的结果,因为winsize-struct有4条未签名的短裤,而不是2条已签名的短裤:

def terminal_size():
    import fcntl, termios, struct
    h, w, hp, wp = struct.unpack('HHHH',
        fcntl.ioctl(0, termios.TIOCGWINSZ,
        struct.pack('HHHH', 0, 0, 0, 0)))
    return w, h

hp和hp应该包含像素的宽度和高度,但不包含。

Code above didn’t return correct result on my linux because winsize-struct has 4 unsigned shorts, not 2 signed shorts:

def terminal_size():
    import fcntl, termios, struct
    h, w, hp, wp = struct.unpack('HHHH',
        fcntl.ioctl(0, termios.TIOCGWINSZ,
        struct.pack('HHHH', 0, 0, 0, 0)))
    return w, h

hp and hp should contain pixel width and height, but don’t.


回答 4

我四处搜寻,找到了Windows的解决方案:

http://code.activestate.com/recipes/440694-determine-size-of-console-window-on-windows/

以及适用于Linux的解决方案。

所以这是一个可以在linux,os x和Windows / cygwin上运行的版本:

""" getTerminalSize()
 - get width and height of console
 - works on linux,os x,windows,cygwin(windows)
"""

__all__=['getTerminalSize']


def getTerminalSize():
   import platform
   current_os = platform.system()
   tuple_xy=None
   if current_os == 'Windows':
       tuple_xy = _getTerminalSize_windows()
       if tuple_xy is None:
          tuple_xy = _getTerminalSize_tput()
          # needed for window's python in cygwin's xterm!
   if current_os == 'Linux' or current_os == 'Darwin' or  current_os.startswith('CYGWIN'):
       tuple_xy = _getTerminalSize_linux()
   if tuple_xy is None:
       print "default"
       tuple_xy = (80, 25)      # default value
   return tuple_xy

def _getTerminalSize_windows():
    res=None
    try:
        from ctypes import windll, create_string_buffer

        # stdin handle is -10
        # stdout handle is -11
        # stderr handle is -12

        h = windll.kernel32.GetStdHandle(-12)
        csbi = create_string_buffer(22)
        res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
    except:
        return None
    if res:
        import struct
        (bufx, bufy, curx, cury, wattr,
         left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
        sizex = right - left + 1
        sizey = bottom - top + 1
        return sizex, sizey
    else:
        return None

def _getTerminalSize_tput():
    # get terminal width
    # src: http://stackoverflow.com/questions/263890/how-do-i-find-the-width-height-of-a-terminal-window
    try:
       import subprocess
       proc=subprocess.Popen(["tput", "cols"],stdin=subprocess.PIPE,stdout=subprocess.PIPE)
       output=proc.communicate(input=None)
       cols=int(output[0])
       proc=subprocess.Popen(["tput", "lines"],stdin=subprocess.PIPE,stdout=subprocess.PIPE)
       output=proc.communicate(input=None)
       rows=int(output[0])
       return (cols,rows)
    except:
       return None


def _getTerminalSize_linux():
    def ioctl_GWINSZ(fd):
        try:
            import fcntl, termios, struct, os
            cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ,'1234'))
        except:
            return None
        return cr
    cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
    if not cr:
        try:
            fd = os.open(os.ctermid(), os.O_RDONLY)
            cr = ioctl_GWINSZ(fd)
            os.close(fd)
        except:
            pass
    if not cr:
        try:
            cr = (env['LINES'], env['COLUMNS'])
        except:
            return None
    return int(cr[1]), int(cr[0])

if __name__ == "__main__":
    sizex,sizey=getTerminalSize()
    print  'width =',sizex,'height =',sizey

I searched around and found a solution for windows at :

http://code.activestate.com/recipes/440694-determine-size-of-console-window-on-windows/

and a solution for linux here.

So here is a version which works both on linux, os x and windows/cygwin :

""" getTerminalSize()
 - get width and height of console
 - works on linux,os x,windows,cygwin(windows)
"""

__all__=['getTerminalSize']


def getTerminalSize():
   import platform
   current_os = platform.system()
   tuple_xy=None
   if current_os == 'Windows':
       tuple_xy = _getTerminalSize_windows()
       if tuple_xy is None:
          tuple_xy = _getTerminalSize_tput()
          # needed for window's python in cygwin's xterm!
   if current_os == 'Linux' or current_os == 'Darwin' or  current_os.startswith('CYGWIN'):
       tuple_xy = _getTerminalSize_linux()
   if tuple_xy is None:
       print "default"
       tuple_xy = (80, 25)      # default value
   return tuple_xy

def _getTerminalSize_windows():
    res=None
    try:
        from ctypes import windll, create_string_buffer

        # stdin handle is -10
        # stdout handle is -11
        # stderr handle is -12

        h = windll.kernel32.GetStdHandle(-12)
        csbi = create_string_buffer(22)
        res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
    except:
        return None
    if res:
        import struct
        (bufx, bufy, curx, cury, wattr,
         left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
        sizex = right - left + 1
        sizey = bottom - top + 1
        return sizex, sizey
    else:
        return None

def _getTerminalSize_tput():
    # get terminal width
    # src: http://stackoverflow.com/questions/263890/how-do-i-find-the-width-height-of-a-terminal-window
    try:
       import subprocess
       proc=subprocess.Popen(["tput", "cols"],stdin=subprocess.PIPE,stdout=subprocess.PIPE)
       output=proc.communicate(input=None)
       cols=int(output[0])
       proc=subprocess.Popen(["tput", "lines"],stdin=subprocess.PIPE,stdout=subprocess.PIPE)
       output=proc.communicate(input=None)
       rows=int(output[0])
       return (cols,rows)
    except:
       return None


def _getTerminalSize_linux():
    def ioctl_GWINSZ(fd):
        try:
            import fcntl, termios, struct, os
            cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ,'1234'))
        except:
            return None
        return cr
    cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
    if not cr:
        try:
            fd = os.open(os.ctermid(), os.O_RDONLY)
            cr = ioctl_GWINSZ(fd)
            os.close(fd)
        except:
            pass
    if not cr:
        try:
            cr = (env['LINES'], env['COLUMNS'])
        except:
            return None
    return int(cr[1]), int(cr[0])

if __name__ == "__main__":
    sizex,sizey=getTerminalSize()
    print  'width =',sizex,'height =',sizey

回答 5

要么是:

import os
columns, rows = os.get_terminal_size(0)
# or
import shutil
columns, rows = shutil.get_terminal_size()

shutil函数只是一个包装器,os可以捕获一些错误并设置后备功能,但是它有一个巨大的警告- 在管道传输时会中断!,这是一笔不小的数目。
要获得配管时的端子尺寸,请os.get_terminal_size(0)改用。

第一个参数0是指示应使用stdin文件描述符而不是默认stdout的参数。我们要使用stdin,因为stdout在被管道传输时会自行分离,在这种情况下会引发错误。

我试图弄清楚什么时候使用stdout代替stdin参数有意义,并且不知道为什么它是默认值。

It’s either:

import os
columns, rows = os.get_terminal_size(0)
# or
import shutil
columns, rows = shutil.get_terminal_size()

The shutil function is just a wrapper around os one that catches some errors and set up a fallback, however it has one huge caveat – it breaks when piping!, which is a pretty huge deal.
To get terminal size when piping use os.get_terminal_size(0) instead.

First argument 0 is an argument indicating that stdin file descriptor should be used instead of default stdout. We want to use stdin because stdout detaches itself when it is being piped which in this case raises an error.

I’ve tried to figure out when would it makes sense to use stdout instead of stdin argument and have no idea why it’s a default here.


回答 6

从Python 3.3开始,它很简单:https : //docs.python.org/3/library/os.html#querying-the-size-of-a-terminal

>>> import os
>>> ts = os.get_terminal_size()
>>> ts.lines
24
>>> ts.columns
80

Starting at Python 3.3 it is straight forward: https://docs.python.org/3/library/os.html#querying-the-size-of-a-terminal

>>> import os
>>> ts = os.get_terminal_size()
>>> ts.lines
24
>>> ts.columns
80

回答 7

该代码Johannes似乎有一些问题:

  • getTerminalSize 需要 import os
  • 是什么env?看起来像os.environ

另外,为什么要切换linescols返回之前?如果TIOCGWINSZ并且stty都说lines那么cols,我说就这样吧。在我注意到不一致之前,这使我困惑了10分钟。

Sridhar,通过管道输出时没有出现该错误。我很确定它会被try-except正确捕获。

pascal,"HHHH"在我的机器上"hh"不起作用,但是可以。我在查找该功能的文档时遇到了麻烦。看起来它与平台有关。

chochem,注册成立。

这是我的版本:

def getTerminalSize():
    """
    returns (lines:int, cols:int)
    """
    import os, struct
    def ioctl_GWINSZ(fd):
        import fcntl, termios
        return struct.unpack("hh", fcntl.ioctl(fd, termios.TIOCGWINSZ, "1234"))
    # try stdin, stdout, stderr
    for fd in (0, 1, 2):
        try:
            return ioctl_GWINSZ(fd)
        except:
            pass
    # try os.ctermid()
    try:
        fd = os.open(os.ctermid(), os.O_RDONLY)
        try:
            return ioctl_GWINSZ(fd)
        finally:
            os.close(fd)
    except:
        pass
    # try `stty size`
    try:
        return tuple(int(x) for x in os.popen("stty size", "r").read().split())
    except:
        pass
    # try environment variables
    try:
        return tuple(int(os.getenv(var)) for var in ("LINES", "COLUMNS"))
    except:
        pass
    # i give up. return default.
    return (25, 80)

It looks like there are some problems with that code, Johannes:

  • getTerminalSize needs to import os
  • what is env? looks like os.environ.

Also, why switch lines and cols before returning? If TIOCGWINSZ and stty both say lines then cols, I say leave it that way. This confused me for a good 10 minutes before I noticed the inconsistency.

Sridhar, I didn’t get that error when I piped output. I’m pretty sure it’s being caught properly in the try-except.

pascal, "HHHH" doesn’t work on my machine, but "hh" does. I had trouble finding documentation for that function. It looks like it’s platform dependent.

chochem, incorporated.

Here’s my version:

def getTerminalSize():
    """
    returns (lines:int, cols:int)
    """
    import os, struct
    def ioctl_GWINSZ(fd):
        import fcntl, termios
        return struct.unpack("hh", fcntl.ioctl(fd, termios.TIOCGWINSZ, "1234"))
    # try stdin, stdout, stderr
    for fd in (0, 1, 2):
        try:
            return ioctl_GWINSZ(fd)
        except:
            pass
    # try os.ctermid()
    try:
        fd = os.open(os.ctermid(), os.O_RDONLY)
        try:
            return ioctl_GWINSZ(fd)
        finally:
            os.close(fd)
    except:
        pass
    # try `stty size`
    try:
        return tuple(int(x) for x in os.popen("stty size", "r").read().split())
    except:
        pass
    # try environment variables
    try:
        return tuple(int(os.getenv(var)) for var in ("LINES", "COLUMNS"))
    except:
        pass
    # i give up. return default.
    return (25, 80)

回答 8

如果在调用此脚本时没有控制终端,则此处的许多Python 2实现将失败。您可以检查sys.stdout.isatty()来确定这是否实际上是一个终端,但这将排除一堆情况,因此我认为找出终端大小的最有效方法是使用内置的curses包。

import curses
w = curses.initscr()
height, width = w.getmaxyx()

Many of the Python 2 implementations here will fail if there is no controlling terminal when you call this script. You can check sys.stdout.isatty() to determine if this is in fact a terminal, but that will exclude a bunch of cases, so I believe the most pythonic way to figure out the terminal size is to use the builtin curses package.

import curses
w = curses.initscr()
height, width = w.getmaxyx()

回答 9

我正在尝试从此处调用的解决方案stty size

columns = int(subprocess.check_output(['stty', 'size']).split()[1])

但是,这对我来说失败了,因为我正在处理一个脚本,该脚本期望stdin上的重定向输入,并且stty在这种情况下会抱怨“ stdin不是终端”。

我能够使它像这样工作:

with open('/dev/tty') as tty:
    height, width = subprocess.check_output(['stty', 'size'], stdin=tty).split()

I was trying the solution from here that calls out to stty size:

columns = int(subprocess.check_output(['stty', 'size']).split()[1])

However this failed for me because I was working on a script that expects redirected input on stdin, and stty would complain that “stdin isn’t a terminal” in that case.

I was able to make it work like this:

with open('/dev/tty') as tty:
    height, width = subprocess.check_output(['stty', 'size'], stdin=tty).split()

回答 10

@reannual的答案很好用,但是有一个问题:os.popen 现在已弃用。该subprocess模块应改为使用,所以这里的@ reannual的代码,使用一个版本subprocess,直接回答了这个问题(通过直接向列宽为int

import subprocess

columns = int(subprocess.check_output(['stty', 'size']).split()[1])

在OS X 10.9上测试

@reannual’s answer works well, but there’s an issue with it: os.popen is now deprecated. The subprocess module should be used instead, so here’s a version of @reannual’s code that uses subprocess and directly answers the question (by giving the column width directly as an int:

import subprocess

columns = int(subprocess.check_output(['stty', 'size']).split()[1])

Tested on OS X 10.9


回答 11

尝试“祝福”

我一直在寻找同样的东西。它非常易于使用,并提供用于在终端上进行着色,样式和定位的工具。您所需要的很简单:

from blessings import Terminal

t = Terminal()

w = t.width
h = t.height

在Linux中像灵符一样工作。(我不确定MacOSX和Windows)

在此处下载和文档

或者您可以使用pip安装它:

pip install blessings

Try “blessings”

I was looking for the very same thing. It is very easy to use and offers tools for coloring, styling and positioning in the terminal. What you need is as easy as:

from blessings import Terminal

t = Terminal()

w = t.width
h = t.height

Works like a charm in Linux. (I’m not sure about MacOSX and Windows)

Download and documentation here

or you can install it with pip:

pip install blessings

回答 12

如果您使用的是Python 3.3或更高版本,建议您get_terminal_size()按照已推荐的内置方法进行操作。但是,如果您坚持使用较旧的版本,并希望通过一种简单的跨平台方法来执行此操作,则可以使用asciimatics。该软件包支持Python 2.7之前的版本,并使用与上面建议的选项类似的选项来获取当前的终端/控制台大小。

只需构造您的Screen类并使用该dimensions属性即可获取高度和宽度。它已被证明可以在Linux,OSX和Windows上运行。

哦,这里有完整的披露:我是作者,因此,如果您有任何疑问,请随时打开一个新期刊。

If you’re using Python 3.3 or above, I’d recommend the built-in get_terminal_size() as already recommended. However if you are stuck with an older version and want a simple, cross-platform way of doing this, you could use asciimatics. This package supports versions of Python back to 2.7 and uses similar options to those suggested above to get the current terminal/console size.

Simply construct your Screen class and use the dimensions property to get the height and width. This has been proven to work on Linux, OSX and Windows.

Oh – and full disclosure here: I am the author, so please feel free to open a new issue if you have any problems getting this to work.


回答 13

这是应该与Linux和Solaris兼容的版本。基于madchine的帖子和评论。需要子流程模块。

def termsize():
    导入shlex,子流程,重新
    输出= subprocess.check_output(shlex.split('/ bin / stty -a'))
    m = re.search('rows \ D +(?P \ d +); column \ D +(?P \ d +);',输出)
    如果m:
        返回m.group('rows'),m.group('columns')
    引发OSError('错误响应:%s'%(输出))
>>> termize()
(“ 40”,“ 100”)

Here is an version that should be Linux and Solaris compatible. Based on the posts and commments from madchine. Requires the subprocess module.

def termsize():
    import shlex, subprocess, re
    output = subprocess.check_output(shlex.split('/bin/stty -a'))
    m = re.search('rows\D+(?P\d+); columns\D+(?P\d+);', output)
    if m:
        return m.group('rows'), m.group('columns')
    raise OSError('Bad response: %s' % (output))
>>> termsize()
('40', '100')

在Python中管道输出标准输出时设置正确的编码

问题:在Python中管道输出标准输出时设置正确的编码

当传递Python程序的输出的管道时,Python解释器会对编码感到困惑,并将其设置为None。这意味着这样的程序:

# -*- coding: utf-8 -*-
print u"åäö"

正常运行时可以正常工作,但失败:

UnicodeEncodeError:’ascii’编解码器无法在位置0编码字符u’\ xa0’:序数不在范围内(128)

以管道顺序使用时。

使管道工作的最佳方法是什么?我能告诉它使用外壳程序/文件系统/正在使用的任何编码吗?

到目前为止,我所看到的建议是直接修改site.py,或使用此hack硬编码defaultencoding:

# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
print u"åäö"

有没有更好的方法可以使管道工作?

When piping the output of a Python program, the Python interpreter gets confused about encoding and sets it to None. This means a program like this:

# -*- coding: utf-8 -*-
print u"åäö"

will work fine when run normally, but fail with:

UnicodeEncodeError: ‘ascii’ codec can’t encode character u’\xa0′ in position 0: ordinal not in range(128)

when used in a pipe sequence.

What is the best way to make this work when piping? Can I just tell it to use whatever encoding the shell/filesystem/whatever is using?

The suggestions I have seen thus far is to modify your site.py directly, or hardcoding the defaultencoding using this hack:

# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
print u"åäö"

Is there a better way to make piping work?


回答 0

您的代码在脚本中运行时有效,因为Python将输出编码为您的终端应用程序正在使用的任何编码。如果要进行管道传输,则必须自己对其进行编码。

经验法则是:始终在内部使用Unicode。解码收到的内容,并对发送的内容进行编码。

# -*- coding: utf-8 -*-
print u"åäö".encode('utf-8')

另一个教学示例是一个Python程序,用于在ISO-8859-1和UTF-8之间进行转换,从而使两者之间的所有内容均大写。

import sys
for line in sys.stdin:
    # Decode what you receive:
    line = line.decode('iso8859-1')

    # Work with Unicode internally:
    line = line.upper()

    # Encode what you send:
    line = line.encode('utf-8')
    sys.stdout.write(line)

设置系统默认编码不是一个好主意,因为您使用的某些模块和库可能依赖于它是ASCII的事实。不要这样

Your code works when run in an script because Python encodes the output to whatever encoding your terminal application is using. If you are piping you must encode it yourself.

A rule of thumb is: Always use Unicode internally. Decode what you receive, and encode what you send.

# -*- coding: utf-8 -*-
print u"åäö".encode('utf-8')

Another didactic example is a Python program to convert between ISO-8859-1 and UTF-8, making everything uppercase in between.

import sys
for line in sys.stdin:
    # Decode what you receive:
    line = line.decode('iso8859-1')

    # Work with Unicode internally:
    line = line.upper()

    # Encode what you send:
    line = line.encode('utf-8')
    sys.stdout.write(line)

Setting the system default encoding is a bad idea, because some modules and libraries you use can rely on the fact it is ASCII. Don’t do it.


回答 1

首先,关于此解决方案:

# -*- coding: utf-8 -*-
print u"åäö".encode('utf-8')

每次都使用给定的编码显式打印是不实际的。那将是重复的并且容易出错。

更好的解决方案是sys.stdout在程序开始时进行更改,以使用选定的编码进行编码。这是我在Python上找到的一种解决方案:如何选择sys.stdout.encoding?,特别是“ toka”的评论:

import sys
import codecs
sys.stdout = codecs.getwriter('utf8')(sys.stdout)

First, regarding this solution:

# -*- coding: utf-8 -*-
print u"åäö".encode('utf-8')

It’s not practical to explicitly print with a given encoding every time. That would be repetitive and error-prone.

A better solution is to change sys.stdout at the start of your program, to encode with a selected encoding. Here is one solution I found on Python: How is sys.stdout.encoding chosen?, in particular a comment by “toka”:

import sys
import codecs
sys.stdout = codecs.getwriter('utf8')(sys.stdout)

回答 2

您可能需要尝试将环境变量“ PYTHONIOENCODING”更改为“ utf_8”。我写了一篇关于这个问题的磨难页面

博客文章的Tl; dr:

import sys, locale, os
print(sys.stdout.encoding)
print(sys.stdout.isatty())
print(locale.getpreferredencoding())
print(sys.getfilesystemencoding())
print(os.environ["PYTHONIOENCODING"])
print(chr(246), chr(9786), chr(9787))

给你

utf_8
False
ANSI_X3.4-1968
ascii
utf_8
ö ☺ ☻

You may want to try changing the environment variable “PYTHONIOENCODING” to “utf_8”. I have written a page on my ordeal with this problem.

Tl;dr of the blog post:

import sys, locale, os
print(sys.stdout.encoding)
print(sys.stdout.isatty())
print(locale.getpreferredencoding())
print(sys.getfilesystemencoding())
print(os.environ["PYTHONIOENCODING"])
print(chr(246), chr(9786), chr(9787))

gives you

utf_8
False
ANSI_X3.4-1968
ascii
utf_8
ö ☺ ☻

回答 3

export PYTHONIOENCODING=utf-8

做这项工作,但不能在python本身上设置它…

我们可以做的是验证是否未设置,并在调用脚本之前通过以下命令告诉用户进行设置:

if __name__ == '__main__':
    if (sys.stdout.encoding is None):
        print >> sys.stderr, "please set python env PYTHONIOENCODING=UTF-8, example: export PYTHONIOENCODING=UTF-8, when write to stdout."
        exit(1)

更新以回复评论:该问题仅在传递到stdout时存在。我在Fedora 25 Python 2.7.13中进行了测试

python --version
Python 2.7.13

猫b.py

#!/usr/bin/env python
#-*- coding: utf-8 -*-
import sys

print sys.stdout.encoding

运行./b.py

UTF-8

运行./b.py | 减

None
export PYTHONIOENCODING=utf-8

do the job, but can’t set it on python itself …

what we can do is verify if isn’t setting and tell the user to set it before call script with :

if __name__ == '__main__':
    if (sys.stdout.encoding is None):
        print >> sys.stderr, "please set python env PYTHONIOENCODING=UTF-8, example: export PYTHONIOENCODING=UTF-8, when write to stdout."
        exit(1)

Update to reply to the comment: the problem just exist when piping to stdout . I tested in Fedora 25 Python 2.7.13

python --version
Python 2.7.13

cat b.py

#!/usr/bin/env python
#-*- coding: utf-8 -*-
import sys

print sys.stdout.encoding

running ./b.py

UTF-8

running ./b.py | less

None

回答 4

上周有一个类似的问题。在我的IDE(PyCharm)中很容易修复。

这是我的解决方法:

从PyCharm菜单栏开始:文件->设置…->编辑器->文件编码,然后将:“ IDE编码”,“项目编码”和“属性文件的默认编码”全部设置为UTF-8,她现在可以工作了像个魅力。

希望这可以帮助!

I had a similar issue last week. It was easy to fix in my IDE (PyCharm).

Here was my fix:

Starting from PyCharm menu bar: File -> Settings… -> Editor -> File Encodings, then set: “IDE Encoding”, “Project Encoding” and “Default encoding for properties files” ALL to UTF-8 and she now works like a charm.

Hope this helps!


回答 5

克雷格·麦昆(Craig McQueen)的答案可能是经过消毒的版本。

import sys, codecs
class EncodedOut:
    def __init__(self, enc):
        self.enc = enc
        self.stdout = sys.stdout
    def __enter__(self):
        if sys.stdout.encoding is None:
            w = codecs.getwriter(self.enc)
            sys.stdout = w(sys.stdout)
    def __exit__(self, exc_ty, exc_val, tb):
        sys.stdout = self.stdout

用法:

with EncodedOut('utf-8'):
    print u'ÅÄÖåäö'

An arguable sanitized version of Craig McQueen’s answer.

import sys, codecs
class EncodedOut:
    def __init__(self, enc):
        self.enc = enc
        self.stdout = sys.stdout
    def __enter__(self):
        if sys.stdout.encoding is None:
            w = codecs.getwriter(self.enc)
            sys.stdout = w(sys.stdout)
    def __exit__(self, exc_ty, exc_val, tb):
        sys.stdout = self.stdout

Usage:

with EncodedOut('utf-8'):
    print u'ÅÄÖåäö'

回答 6

我可以通过以下方式“自动化”它:

def __fix_io_encoding(last_resort_default='UTF-8'):
  import sys
  if [x for x in (sys.stdin,sys.stdout,sys.stderr) if x.encoding is None] :
      import os
      defEnc = None
      if defEnc is None :
        try:
          import locale
          defEnc = locale.getpreferredencoding()
        except: pass
      if defEnc is None :
        try: defEnc = sys.getfilesystemencoding()
        except: pass
      if defEnc is None :
        try: defEnc = sys.stdin.encoding
        except: pass
      if defEnc is None :
        defEnc = last_resort_default
      os.environ['PYTHONIOENCODING'] = os.environ.get("PYTHONIOENCODING",defEnc)
      os.execvpe(sys.argv[0],sys.argv,os.environ)
__fix_io_encoding() ; del __fix_io_encoding

是的,如果此“ setenv”失败,则有可能在此处获得无限循环。

I could “automate” it with a call to:

def __fix_io_encoding(last_resort_default='UTF-8'):
  import sys
  if [x for x in (sys.stdin,sys.stdout,sys.stderr) if x.encoding is None] :
      import os
      defEnc = None
      if defEnc is None :
        try:
          import locale
          defEnc = locale.getpreferredencoding()
        except: pass
      if defEnc is None :
        try: defEnc = sys.getfilesystemencoding()
        except: pass
      if defEnc is None :
        try: defEnc = sys.stdin.encoding
        except: pass
      if defEnc is None :
        defEnc = last_resort_default
      os.environ['PYTHONIOENCODING'] = os.environ.get("PYTHONIOENCODING",defEnc)
      os.execvpe(sys.argv[0],sys.argv,os.environ)
__fix_io_encoding() ; del __fix_io_encoding

Yes, it’s possible to get an infinite loop here if this “setenv” fails.


回答 7

我只是以为我在这里提到了一些东西,在我最终意识到发生了什么之前,我不得不花很长时间进行试验。对于这里的每个人来说,这可能是如此明显,以至于他们都没有理会它。但是如果他们有的话,这对我会有所帮助,所以按照这个原则…!

注意:我专门使用的是Jython 2.7版,所以可能这可能不适用于CPython

NB2:我的.py文件的前两行是:

# -*- coding: utf-8 -*-
from __future__ import print_function

“%”(也称为“插值运算符”)字符串构造机制也会引起其他问题……如果“环境”的默认编码为ASCII,则尝试执行类似的操作

print( "bonjour, %s" % "fréd" )  # Call this "print A"

您将在Eclipse中运行没有困难…在Windows CLI(DOS窗口)中,您会发现编码是代码页850(我的Windows 7 OS)或类似的东西,至少可以处理欧洲带有重音符号的字符,因此它会工作的。

print( u"bonjour, %s" % "fréd" ) # Call this "print B"

也可以。

如果是OTOH,您从CLI定向到文件,则stdout编码将为None,它将默认设置为ASCII(无论如何在我的OS上),它将无法处理以上任何打印…(可怕的编码)错误)。

因此,您可能会考虑使用来重定向您的标准输出

sys.stdout = codecs.getwriter('utf8')(sys.stdout)

并尝试在CLI管道中运行到文件…很奇怪,上面的打印A可以工作…但是上面的打印B将抛出编码错误!但是,以下内容可以正常运行:

print( u"bonjour, " + "fréd" ) # Call this "print C"

我得出的结论(临时)是,如果将使用“ u”前缀指定为Unicode字符串的字符串提交给%-handling机制,则似乎涉及使用默认环境编码,无论是否已将stdout设置为重定向!

人们如何处理这是一个选择问题。我欢迎Unicode专家说出为什么会发生这种情况,我是否以某种方式出错了,对此的首选解决方案,是否也适用于CPython,它是否发生在Python 3中,等等。

I just thought I’d mention something here which I had to spent a long time experimenting with before I finally realised what was going on. This may be so obvious to everyone here that they haven’t bothered mentioning it. But it would’ve helped me if they had, so on that principle…!

NB: I am using Jython specifically, v 2.7, so just possibly this may not apply to CPython

NB2: the first two lines of my .py file here are:

# -*- coding: utf-8 -*-
from __future__ import print_function

The “%” (AKA “interpolation operator”) string construction mechanism causes ADDITIONAL problems too… If the default encoding of the “environment” is ASCII and you try to do something like

print( "bonjour, %s" % "fréd" )  # Call this "print A"

You will have no difficulty running in Eclipse… In a Windows CLI (DOS window) you will find that the encoding is code page 850 (my Windows 7 OS) or something similar, which can handle European accented characters at least, so it’ll work.

print( u"bonjour, %s" % "fréd" ) # Call this "print B"

will also work.

If, OTOH, you direct to a file from the CLI, the stdout encoding will be None, which will default to ASCII (on my OS anyway), which will not be able to handle either of the above prints… (dreaded encoding error).

So then you might think of redirecting your stdout by using

sys.stdout = codecs.getwriter('utf8')(sys.stdout)

and try running in the CLI piping to a file… Very oddly, print A above will work… But print B above will throw the encoding error! The following will however work OK:

print( u"bonjour, " + "fréd" ) # Call this "print C"

The conclusion I have come to (provisionally) is that if a string which is specified to be a Unicode string using the “u” prefix is submitted to the %-handling mechanism it appears to involve the use of the default environment encoding, regardless of whether you have set stdout to redirect!

How people deal with this is a matter of choice. I would welcome a Unicode expert to say why this happens, whether I’ve got it wrong in some way, what the preferred solution to this, whether it also applies to CPython, whether it happens in Python 3, etc., etc.


回答 8

我在旧版应用程序中遇到了这个问题,很难确定打印的内容。我帮助自己解决了这个问题:

# encoding_utf8.py
import codecs
import builtins


def print_utf8(text, **kwargs):
    print(str(text).encode('utf-8'), **kwargs)


def print_utf8(fn):
    def print_fn(*args, **kwargs):
        return fn(str(*args).encode('utf-8'), **kwargs)
    return print_fn


builtins.print = print_utf8(print)

在我的脚本之上,test.py:

import encoding_utf8
string = 'Axwell Λ Ingrosso'
print(string)

请注意,这会将所有调用更改为使用编码进行打印,因此您的控制台将打印以下内容:

$ python test.py
b'Axwell \xce\x9b Ingrosso'

I ran into this problem in a legacy application, and it was difficult to identify where what was printed. I helped myself with this hack:

# encoding_utf8.py
import codecs
import builtins


def print_utf8(text, **kwargs):
    print(str(text).encode('utf-8'), **kwargs)


def print_utf8(fn):
    def print_fn(*args, **kwargs):
        return fn(str(*args).encode('utf-8'), **kwargs)
    return print_fn


builtins.print = print_utf8(print)

On top of my script, test.py:

import encoding_utf8
string = 'Axwell Λ Ingrosso'
print(string)

Note that this changes ALL calls to print to use an encoding, so your console will print this:

$ python test.py
b'Axwell \xce\x9b Ingrosso'

回答 9

在Windows上,当从编辑器(例如Sublime Text)运行Python代码时,我经常遇到此问题,但没有从命令行运行它时。

在这种情况下,请检查编辑器的参数。对于SublimeText,这Python.sublime-build解决了它:

{
  "cmd": ["python", "-u", "$file"],
  "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
  "selector": "source.python",
  "encoding": "utf8",
  "env": {"PYTHONIOENCODING": "utf-8", "LANG": "en_US.UTF-8"}
}

On Windows, I had this problem very often when running a Python code from an editor (like Sublime Text), but not if running it from command-line.

In this case, check your editor’s parameters. In the case of SublimeText, this Python.sublime-build solved it:

{
  "cmd": ["python", "-u", "$file"],
  "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
  "selector": "source.python",
  "encoding": "utf8",
  "env": {"PYTHONIOENCODING": "utf-8", "LANG": "en_US.UTF-8"}
}

Gitsome-增强型Git/GitHub命令行界面(CLI)。GitHub和GitHub企业的官方集成:https://github.com/works-with/category/desktop-tools

一个Official Integration对于GitHub和GitHub Enterprise

为什么gitsome

Git命令行

虽然标准的Git命令行是管理基于Git的repo的一个很好的工具,但是它可以很难记住这个用法地址为:

  • 150多个瓷器和管道命令
  • 无数特定于命令的选项
  • 标签和分支等资源

Git命令行不与GitHub集成,强制您在命令行和浏览器之间切换

gitsome-具有自动完成功能的增压Git/GitHub CLI

gitsome旨在通过专注于以下方面来增强您的标准git/shell界面:

  • 提高易用性
  • 提高工作效率

深度GitHub集成

并不是所有的GitHub工作流都能在终端中很好地工作;gitsome试图将目标对准那些这样做的人

gitsome包括29个与一起使用的GitHub集成命令ALL外壳:

$ gh <command> [param] [options]

gh命令以及Git-Extrashub解锁更多GitHub集成的命令!

带有交互式帮助的Git和GitHub自动完成程序

您可以运行可选壳牌:

 $ gitsome

要启用自动完成交互式帮助对于以下内容:

通用自动补全程序

gitsome自动完成以下内容:

  • Shell命令
  • 文件和目录
  • 环境变量
  • 手册页
  • python

要启用其他自动完成,请查看Enabling Bash Completions部分

鱼式自动建议

gitsome支持鱼式自动建议。使用right arrow完成建议的关键

Python REPL

gitsome由以下人员提供动力xonsh,它支持Python REPL

在shell命令旁边运行Python命令:

附加内容xonsh功能可在xonsh tutorial

命令历史记录

gitsome跟踪您输入的命令并将其存储在~/.xonsh_history.json使用向上和向下箭头键循环查看命令历史记录

可自定义的突出显示

可以控制用于突出显示的ansi颜色,方法是更新~/.gitsomeconfig文件

颜色选项包括:

'black', 'red', 'green', 'yellow',
'blue', 'magenta', 'cyan', 'white'

对于无颜色,请将值设置为Nonewhite在某些终端上可能显示为浅灰色

可用的平台

gitsome适用于Mac、Linux、Unix、Windows,以及Docker

待办事项

并不是所有的GitHub工作流都能在终端中很好地工作;gitsome试图将目标对准那些这样做的人

  • 添加其他GitHub API集成

gitsome才刚刚开始。请随意……contribute!

索引

GitHub集成命令

安装和测试

杂项

GitHub集成命令语法

用法:

$ gh <command> [param] [options]

GitHub集成命令列表

  configure            Configure gitsome.
  create-comment       Create a comment on the given issue.
  create-issue         Create an issue.
  create-repo          Create a repo.
  emails               List all the user's registered emails.
  emojis               List all GitHub supported emojis.
  feed                 List all activity for the given user or repo.
  followers            List all followers and the total follower count.
  following            List all followed users and the total followed count.
  gitignore-template   Output the gitignore template for the given language.
  gitignore-templates  Output all supported gitignore templates.
  issue                Output detailed information about the given issue.
  issues               List all issues matching the filter.
  license              Output the license template for the given license.
  licenses             Output all supported license templates.
  me                   List information about the logged in user.
  notifications        List all notifications.
  octo                 Output an Easter egg or the given message from Octocat.
  pull-request         Output detailed information about the given pull request.
  pull-requests        List all pull requests.
  rate-limit           Output the rate limit.  Not available for Enterprise.
  repo                 Output detailed information about the given filter.
  repos                List all repos matching the given filter.
  search-issues        Search for all issues matching the given query.
  search-repos         Search for all repos matching the given query.
  starred              Output starred repos.
  trending             List trending repos for the given language.
  user                 List information about the given user.
  view                 View the given index in the terminal or a browser.

GitHub集成命令参考:COMMANDS.md

请参阅GitHub Integration Commands Reference in COMMANDS.md对于详细讨论所有GitHub集成命令、参数、选项和示例

请查看下一节,了解快速参考

GitHub集成命令快速参考

配置gitsome

要与GitHub正确集成,您必须首先配置gitsome

$ gh configure

对于GitHub Enterprise用户,使用-e/--enterprise标志:

$ gh configure -e

列表源

列出您的新闻源

$ gh feed

列出用户的活动摘要

查看您的活动订阅源或其他用户的活动订阅源,也可以选择使用寻呼机-p/--pager这个pager option可用于许多命令

$ gh feed donnemartin -p

列出回购的活动提要

$ gh feed donnemartin/gitsome -p

列出通知

$ gh notifications

列出拉式请求

查看您的回购的所有拉式请求:

$ gh pull-requests

过滤问题

查看您提到的所有未决问题:

$ gh issues --issue_state open --issue_filter mentioned

查看所有问题,只筛选分配给您的问题,而不考虑状态(打开、关闭):

$ gh issues --issue_state all --issue_filter assigned

有关过滤和州限定词的更多信息,请访问gh issues参考位置COMMANDS.md

过滤星级报告

$ gh starred "repo filter"

搜索问题和报告

搜索问题

+1最多的搜索问题:

$ gh search-issues "is:open is:issue sort:reactions-+1-desc" -p

评论最多的搜索问题:

$ gh search-issues "is:open is:issue sort:comments-desc" -p

使用“需要帮助”标签搜索问题:

$ gh search-issues "is:open is:issue label:\"help wanted\"" -p

已标记您的用户名的搜索问题@donnemartin

$ gh search-issues "is:issue donnemartin is:open" -p

搜索您所有未解决的私人问题:

$ gh search-issues "is:open is:issue is:private" -p

有关查询限定符的更多信息,请访问searching issues reference

搜索报告

搜索2015年或之后创建的所有Python repos,>=1000星:

$ gh search-repos "created:>=2015-01-01 stars:>=1000 language:python" --sort stars -p

有关查询限定符的更多信息,请访问searching repos reference

列出趋势报告和开发人员

查看趋势回购:

$ gh trending [language] [-w/--weekly] [-m/--monthly] [-d/--devs] [-b/--browser]

查看趋势DEV(目前仅浏览器支持DEV):

$ gh trending [language] --devs --browser

查看内容

这个view命令

查看前面列出的通知、拉取请求、问题、回复、用户等,HTML格式适合您的终端,也可以选择在您的浏览器中查看:

$ gh view [#] [-b/--browser]

这个issue命令

查看问题:

$ gh issue donnemartin/saws/1

这个pull-request命令

查看拉取请求:

$ gh pull-request donnemartin/awesome-aws/2

设置.gitignore

列出所有可用的.gitignore模板:

$ gh gitignore-templates

设置您的.gitignore

$ gh gitignore-template Python > .gitignore

设置LICENSE

列出所有可用的LICENSE模板:

$ gh licenses

设置您的或LICENSE

$ gh license MIT > LICENSE

召唤十月猫

在十月猫那天打电话说出给定的信息或复活节彩蛋:

$ gh octo [say]

查看配置文件

查看用户的配置文件

$ gh user octocat

查看您的个人资料

使用查看您的个人资料gh user [YOUR_USER_ID]命令或使用以下快捷方式:

$ gh me

创建评论、问题和报告

创建评论:

$ gh create-comment donnemartin/gitsome/1 -t "hello world"

创建问题:

$ gh create-issue donnemartin/gitsome -t "title" -b "body"

创建回购:

$ gh create-repo gitsome

选项:在寻呼机中查看

许多gh命令支持-p/--pager在寻呼机中显示结果的选项(如果可用)

用法:

$ gh <command> [param] [options] -p
$ gh <command> [param] [options] --pager

选项:在浏览器中查看

许多gh命令支持-b/--browser在默认浏览器(而不是终端)中显示结果的选项

用法:

$ gh <command> [param] [options] -b
$ gh <command> [param] [options] --browser

请参阅COMMANDS.md有关所有GitHub集成命令、参数、选项和示例的详细列表

记住这些命令有困难吗?看看手边的autocompleter with interactive help来指导您完成每个命令

注意,您可以将gitsome与其他实用程序(如Git-Extras

安装

PIP安装

gitsome托管在PyPI将安装以下命令gitsome

$ pip3 install gitsome

您还可以安装最新的gitsome来自GitHub源,可能包含尚未推送到PyPI的更改:

$ pip3 install git+https://github.com/donnemartin/gitsome.git

如果您没有安装在virtualenv,您可能需要运行sudo

$ sudo pip3 install gitsome

pip3

根据您的设置,您可能还希望运行pip3使用-H flag

$ sudo -H pip3 install gitsome

对于大多数Linux用户来说,pip3可以使用python3-pip套餐

例如,Ubuntu用户可以运行:

$ sudo apt-get install python3-pip

看这个ticket有关更多详细信息,请参阅

虚拟环境安装

您可以将Python包安装在virtualenv要避免依赖项或权限的潜在问题,请执行以下操作

如果您是Windows用户,或者如果您想了解更多有关virtualenv,看看这个guide

安装virtualenvvirtualenvwrapper

$ pip3 install virtualenv
$ pip3 install virtualenvwrapper
$ export WORKON_HOME=~/.virtualenvs
$ source /usr/local/bin/virtualenvwrapper.sh

创建gitsomevirtualenv并安装gitsome

$ mkvirtualenv gitsome
$ pip3 install gitsome

如果pip安装不起作用,您可能默认运行的是Python2。检查您正在运行的Python版本:

$ python --version

如果上面的调用结果是Python 2,请找到Python 3的路径:

$ which python3  # Python 3 path for mkvirtualenv's --python option

如果需要,安装Python 3。调用时设置Python版本mkvirtualenv

$ mkvirtualenv --python [Python 3 path from above] gitsome
$ pip3 install gitsome

如果要激活gitsomevirtualenv稍后再次运行:

$ workon gitsome

要停用gitsomevirtualenv,运行:

$ deactivate

作为Docker容器运行

您可以在Docker容器中运行gitome,以避免安装Python和pip3当地的。要安装Docker,请查看official Docker documentation

一旦安装了docker,您就可以运行gitome:

$ docker run -ti --rm mariolet/gitsome

您可以使用Docker卷让gitome访问您的工作目录、本地的.gitSomeconfig和.gitconfig:

$ docker run -ti --rm -v $(pwd):/src/              \
   -v ${HOME}/.gitsomeconfig:/root/.gitsomeconfig  \
   -v ${HOME}/.gitconfig:/root/.gitconfig          \
   mariolet/gitsome

如果您经常运行此命令,则可能需要定义别名:

$ alias gitsome="docker run -ti --rm -v $(pwd):/src/              \
                  -v ${HOME}/.gitsomeconfig:/root/.gitsomeconfig  \
                  -v ${HOME}/.gitconfig:/root/.gitconfig          \
                  mariolet/gitsome"

要从源构建Docker映像,请执行以下操作:

$ git clone https://github.com/donnemartin/gitsome.git
$ cd gitsome
$ docker build -t gitsome .

启动gitsome

安装后,运行可选的gitsome带有交互式帮助的自动完成程序:

$ gitsome

运行可选的gitsomeShell将为您提供自动完成、交互式帮助、鱼式建议、Python REPL等

正在运行gh命令

运行GitHub集成命令:

$ gh <command> [param] [options]

注意:运行gitsome不需要执行外壳程序gh命令。之后installinggitsome你可以跑gh来自任何shell的命令

运行gh configure命令

要与GitHub正确集成,gitsome必须正确配置:

$ gh configure

针对GitHub企业用户

使用-e/--enterprise标志:

$ gh configure -e

要查看更多详细信息,请访问gh configure部分

启用Bash完成

默认情况下,gitsome查看以下内容locations to enable bash completions

要添加其他bash完成,请更新~/.xonshrc包含bash完成位置的文件

如果~/.xonshrc不存在,请创建它:

$ touch ~/.xonshrc

例如,如果在/usr/local/etc/my_bash_completion.d/completion.bash,将以下行添加到~/.xonshrc

$BASH_COMPLETIONS.append('/usr/local/etc/my_bash_completion.d/completion.bash')

您将需要重新启动gitsome要使更改生效,请执行以下操作

正在启用gh在外部完成制表符gitsome

你可以跑gh外部的命令gitsome外壳完成器。要启用gh此工作流的制表符完成,请将gh_complete.sh本地文件

让bash知道可以完成gh当前会话中的命令:

$ source /path/to/gh_complete.sh

要为所有终端会话启用制表符完成,请将以下内容添加到您的bashrc文件:

source /path/to/gh_complete.sh

重新加载您的bashrc

$ source ~/.bashrc

提示:.是的缩写source,因此您可以改为运行以下命令:

$ . ~/.bashrc

对于Zsh用户

zsh包括与bash完成兼容的模块

下载gh_complete.sh文件,并将以下内容附加到您的.zshrc

autoload bashcompinit
bashcompinit
source /path/to/gh_complete.sh

重新加载您的zshrc

 $ source ~/.zshrc

可选:安装PILPillow

将化身显示为gh megh user命令需要安装可选的PILPillow依赖性

Windows*和Mac:

$ pip3 install Pillow

*请参阅Windows Support有关化身限制的部分

Ubuntu用户,看看这些instructions on askubuntu

支持的Python版本

  • Python 3.4
  • Python 3.5
  • Python 3.6
  • Python 3.7

gitsome由以下人员提供动力xonsh,它当前不支持Python2.x,如本文中所讨论的ticket

支持的平台

  • Mac OS X
    • 在OS X 10.10上测试
  • Linux、Unix
    • 在Ubuntu 14.04 LTS上测试
  • 窗口
    • 在Windows 10上测试

Windows支持

gitsome已在Windows 10上进行了测试,cmdcmder

虽然您可以使用标准的Windows命令提示符,但使用这两种命令提示符都可能会有更好的体验cmderconemu

纯文本化身

命令gh usergh me将永远拥有-t/--text_avatar标志已启用,因为img2txt不支持Windows上的ANSI头像

配置文件

在Windows上,.gitsomeconfig 文件可在以下位置找到%userprofile%例如:

C:\Users\dmartin\.gitsomeconfig

开发人员安装

如果您有兴趣为gitsome,请运行以下命令:

$ git clone https://github.com/donnemartin/gitsome.git
$ cd gitsome
$ pip3 install -e .
$ pip3 install -r requirements-dev.txt
$ gitsome
$ gh <command> [param] [options]

pip3

如果您在安装时收到一个错误,提示您需要Python 3.4+,这可能是因为您的pip命令是为旧版本的Python配置的。要解决此问题,建议安装pip3

$ sudo apt-get install python3-pip

看这个ticket有关更多详细信息,请参阅

持续集成

有关持续集成的详细信息,请访问Travis CI

单元测试和代码覆盖率

在活动的Python环境中运行单元测试:

$ python tests/run_tests.py

使用运行单元测试tox在多个Python环境中:

$ tox

文档

源代码文档将很快在Readthedocs.org请查看source docstrings

运行以下命令构建文档:

$ scripts/update_docs.sh

贡献

欢迎投稿!

回顾Contributing Guidelines有关如何执行以下操作的详细信息,请执行以下操作:

  • 提交问题
  • 提交拉式请求

学分

联系信息

请随时与我联系,讨论任何问题、问题或评论

我的联系信息可以在我的GitHub page

许可证

我在开放源码许可下向您提供此存储库中的代码和资源。因为这是我的个人存储库,您获得的我的代码和资源的许可证来自我,而不是我的雇主(Facebook)

Copyright 2016 Donne Martin

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

如何在Python的终端中打印彩色文本?

问题:如何在Python的终端中打印彩色文本?

如何在Python中将彩色文本输出到终端?代表实体块的最佳Unicode符号是什么?

How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?


回答 0

这在某种程度上取决于您所使用的平台。最常见的方法是打印ANSI转义序列。对于一个简单的示例,这是Blender构建脚本中的一些python代码:

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

要使用这样的代码,您可以执行以下操作

print(bcolors.WARNING + "Warning: No active frommets remain. Continue?" + bcolors.ENDC)

或者,使用Python3.6 +:

print(f"{bcolors.WARNING}Warning: No active frommets remain. Continue?{bcolors.ENDC}")

这将在包括OS X,Linux和Windows的Unix上运行(前提是您使用ANSICON,或者在Windows 10中,前提是您启用了VT100仿真)。有用于设置颜色,移动光标等的ansi代码。

如果您要对此进行复杂化处理(听起来就像是在编写游戏),则应查看“ curses”模块,该模块为您处理了许多复杂的部分。在Python的诅咒HOWTO是一个很好的介绍。

如果您没有使用扩展的ASCII码(即不在PC上),那么您将只能使用127以下的ASCII字符,而“#”或“ @”可能是您最好的选择。如果可以确保您的终端使用的是IBM 扩展的ascii字符集,那么您还有更多选择。字符176、177、178和219是“块字符”。

一些现代的基于文本的程序,例如“矮人要塞”,以图形模式模拟文本模式,并使用经典PC字体的图像。您可以在Dwarf Fortress Wiki see(用户制作的tileset)上找到一些可以使用的位图。

文本模式设计大赛已在文本模式下做图形更多的资源。

嗯..我认为这个答案有点过头了。不过,我正在计划一个史诗般的基于文本的冒险游戏。祝您彩色文字好运!

This somewhat depends on what platform you are on. The most common way to do this is by printing ANSI escape sequences. For a simple example, here’s some python code from the blender build scripts:

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

To use code like this, you can do something like

print(bcolors.WARNING + "Warning: No active frommets remain. Continue?" + bcolors.ENDC)

or, with Python3.6+:

print(f"{bcolors.WARNING}Warning: No active frommets remain. Continue?{bcolors.ENDC}")

This will work on unixes including OS X, linux and windows (provided you use ANSICON, or in Windows 10 provided you enable VT100 emulation). There are ansi codes for setting the color, moving the cursor, and more.

If you are going to get complicated with this (and it sounds like you are if you are writing a game), you should look into the “curses” module, which handles a lot of the complicated parts of this for you. The Python Curses HowTO is a good introduction.

If you are not using extended ASCII (i.e. not on a PC), you are stuck with the ascii characters below 127, and ‘#’ or ‘@’ is probably your best bet for a block. If you can ensure your terminal is using a IBM extended ascii character set, you have many more options. Characters 176, 177, 178 and 219 are the “block characters”.

Some modern text-based programs, such as “Dwarf Fortress”, emulate text mode in a graphical mode, and use images of the classic PC font. You can find some of these bitmaps that you can use on the Dwarf Fortress Wiki see (user-made tilesets).

The Text Mode Demo Contest has more resources for doing graphics in text mode.

Hmm.. I think got a little carried away on this answer. I am in the midst of planning an epic text-based adventure game, though. Good luck with your colored text!


回答 1

我很惊讶没有人提到Python termcolor模块。用法很简单:

from termcolor import colored

print colored('hello', 'red'), colored('world', 'green')

或在Python 3中:

print(colored('hello', 'red'), colored('world', 'green'))

但是,对于游戏编程和您要执行的“彩色块”来说,它可能不够复杂…

I’m surprised no one has mentioned the Python termcolor module. Usage is pretty simple:

from termcolor import colored

print colored('hello', 'red'), colored('world', 'green')

Or in Python 3:

print(colored('hello', 'red'), colored('world', 'green'))

It may not be sophisticated enough, however, for game programming and the “colored blocks” that you want to do…


回答 2

答案是Colorama,用于Python中的所有跨平台着色。

Python 3.6示例屏幕截图:

The answer is Colorama for all cross-platform coloring in Python.

A Python 3.6 example screenshot:


回答 3

打印一个以颜色/样式开头的字符串,然后打印该字符串,然后通过以下命令结束颜色/样式更改'\x1b[0m'

print('\x1b[6;30;42m' + 'Success!' + '\x1b[0m')

使用以下代码获取外壳程序文本的格式选项表:

def print_format_table():
    """
    prints table of formatted text format options
    """
    for style in range(8):
        for fg in range(30,38):
            s1 = ''
            for bg in range(40,48):
                format = ';'.join([str(style), str(fg), str(bg)])
                s1 += '\x1b[%sm %s \x1b[0m' % (format, format)
            print(s1)
        print('\n')

print_format_table()

浅色示例(完整)

暗光示例(部分)

Print a string that starts a color/style, then the string, then end the color/style change with '\x1b[0m':

print('\x1b[6;30;42m' + 'Success!' + '\x1b[0m')

Get a table of format options for shell text with following code:

def print_format_table():
    """
    prints table of formatted text format options
    """
    for style in range(8):
        for fg in range(30,38):
            s1 = ''
            for bg in range(40,48):
                format = ';'.join([str(style), str(fg), str(bg)])
                s1 += '\x1b[%sm %s \x1b[0m' % (format, format)
            print(s1)
        print('\n')

print_format_table()

Light-on-dark example (complete)

Dark-on-light example (partial)


回答 4

定义一个以颜色开头的字符串和一个以颜色结尾的字符串,然后打印您的文本,其中起始字符串在前面,结尾字符串在结尾。

CRED = '\033[91m'
CEND = '\033[0m'
print(CRED + "Error, does not compute!" + CEND)

这会产生bash,并urxvt带有Zenburn风格的配色方案:

通过实验,我们可以获得更多的颜色:

注意:\33[5m\33[6m闪烁。

这样,我们可以创建完整的颜色集合:

CEND      = '\33[0m'
CBOLD     = '\33[1m'
CITALIC   = '\33[3m'
CURL      = '\33[4m'
CBLINK    = '\33[5m'
CBLINK2   = '\33[6m'
CSELECTED = '\33[7m'

CBLACK  = '\33[30m'
CRED    = '\33[31m'
CGREEN  = '\33[32m'
CYELLOW = '\33[33m'
CBLUE   = '\33[34m'
CVIOLET = '\33[35m'
CBEIGE  = '\33[36m'
CWHITE  = '\33[37m'

CBLACKBG  = '\33[40m'
CREDBG    = '\33[41m'
CGREENBG  = '\33[42m'
CYELLOWBG = '\33[43m'
CBLUEBG   = '\33[44m'
CVIOLETBG = '\33[45m'
CBEIGEBG  = '\33[46m'
CWHITEBG  = '\33[47m'

CGREY    = '\33[90m'
CRED2    = '\33[91m'
CGREEN2  = '\33[92m'
CYELLOW2 = '\33[93m'
CBLUE2   = '\33[94m'
CVIOLET2 = '\33[95m'
CBEIGE2  = '\33[96m'
CWHITE2  = '\33[97m'

CGREYBG    = '\33[100m'
CREDBG2    = '\33[101m'
CGREENBG2  = '\33[102m'
CYELLOWBG2 = '\33[103m'
CBLUEBG2   = '\33[104m'
CVIOLETBG2 = '\33[105m'
CBEIGEBG2  = '\33[106m'
CWHITEBG2  = '\33[107m'

这是生成测试的代码:

x = 0
for i in range(24):
  colors = ""
  for j in range(5):
    code = str(x+j)
    colors = colors + "\33[" + code + "m\\33[" + code + "m\033[0m "
  print(colors)
  x=x+5

Define a string that starts a color and a string that ends the color, then print your text with the start string at the front and the end string at the end.

CRED = '\033[91m'
CEND = '\033[0m'
print(CRED + "Error, does not compute!" + CEND)

This produces the following in bash, in urxvt with a Zenburn-style color scheme:

Through experimentation, we can get more colors:

Note: \33[5m and \33[6m are blinking.

This way we can create a full color collection:

CEND      = '\33[0m'
CBOLD     = '\33[1m'
CITALIC   = '\33[3m'
CURL      = '\33[4m'
CBLINK    = '\33[5m'
CBLINK2   = '\33[6m'
CSELECTED = '\33[7m'

CBLACK  = '\33[30m'
CRED    = '\33[31m'
CGREEN  = '\33[32m'
CYELLOW = '\33[33m'
CBLUE   = '\33[34m'
CVIOLET = '\33[35m'
CBEIGE  = '\33[36m'
CWHITE  = '\33[37m'

CBLACKBG  = '\33[40m'
CREDBG    = '\33[41m'
CGREENBG  = '\33[42m'
CYELLOWBG = '\33[43m'
CBLUEBG   = '\33[44m'
CVIOLETBG = '\33[45m'
CBEIGEBG  = '\33[46m'
CWHITEBG  = '\33[47m'

CGREY    = '\33[90m'
CRED2    = '\33[91m'
CGREEN2  = '\33[92m'
CYELLOW2 = '\33[93m'
CBLUE2   = '\33[94m'
CVIOLET2 = '\33[95m'
CBEIGE2  = '\33[96m'
CWHITE2  = '\33[97m'

CGREYBG    = '\33[100m'
CREDBG2    = '\33[101m'
CGREENBG2  = '\33[102m'
CYELLOWBG2 = '\33[103m'
CBLUEBG2   = '\33[104m'
CVIOLETBG2 = '\33[105m'
CBEIGEBG2  = '\33[106m'
CWHITEBG2  = '\33[107m'

Here is the code to generate the test:

x = 0
for i in range(24):
  colors = ""
  for j in range(5):
    code = str(x+j)
    colors = colors + "\33[" + code + "m\\33[" + code + "m\033[0m "
  print(colors)
  x=x+5

回答 5

您想了解ANSI转义序列。这是一个简单的示例:

CSI="\x1B["
print(CSI+"31;40m" + "Colored Text" + CSI + "0m")

有关更多信息,请参见http://en.wikipedia.org/wiki/ANSI_escape_code

对于块字符,请尝试使用\ u2588这样的Unicode字符:

print(u"\u2588")

放在一起:

print(CSI+"31;40m" + u"\u2588" + CSI + "0m")

You want to learn about ANSI escape sequences. Here’s a brief example:

CSI="\x1B["
print(CSI+"31;40m" + "Colored Text" + CSI + "0m")

For more info see http://en.wikipedia.org/wiki/ANSI_escape_code

For a block character, try a unicode character like \u2588:

print(u"\u2588")

Putting it all together:

print(CSI+"31;40m" + u"\u2588" + CSI + "0m")

回答 6

我之所以做出回应,是因为我找到了一种在Windows 10上使用ANSI代码的方法,这样您就可以更改文本的颜色而无需任何内置模块:

进行此工作的行是os.system("")或任何其他系统调用,它使您可以在终端中打印ANSI代码:

import os

os.system("")

# Group of Different functions for different styles
class style():
    BLACK = '\033[30m'
    RED = '\033[31m'
    GREEN = '\033[32m'
    YELLOW = '\033[33m'
    BLUE = '\033[34m'
    MAGENTA = '\033[35m'
    CYAN = '\033[36m'
    WHITE = '\033[37m'
    UNDERLINE = '\033[4m'
    RESET = '\033[0m'

print(style.YELLOW + "Hello, World!")

注意:尽管此选项与其他Windows选项具有相同的选项,但是Windows即使使用此技巧也无法完全支持ANSI代码。并非所有的文本装饰颜色都起作用,并且所有“明亮”颜色(代码90-97和100-107)显示的颜色与常规颜色相同(代码30-37和40-47)

编辑:感谢@jl查找更短的方法。

tl; dros.system("")在文件顶部附近添加。

Python版本: 3.6.7

I’m responding because I have found out a way to use ANSI codes on Windows 10, so that you can change the colour of text without any modules that aren’t built in:

The line that makes this work is os.system(""), or any other system call, which allows you to print ANSI codes in the Terminal:

import os

os.system("")

# Group of Different functions for different styles
class style():
    BLACK = '\033[30m'
    RED = '\033[31m'
    GREEN = '\033[32m'
    YELLOW = '\033[33m'
    BLUE = '\033[34m'
    MAGENTA = '\033[35m'
    CYAN = '\033[36m'
    WHITE = '\033[37m'
    UNDERLINE = '\033[4m'
    RESET = '\033[0m'

print(style.YELLOW + "Hello, World!")

Note: Although this gives the same options as other Windows options, Windows does not full support ANSI codes, even with this trick. Not all the text decoration colours work and all the ‘bright’ colours (Codes 90-97 and 100-107) display the same as the regular colours (Codes 30-37 and 40-47)

Edit: Thanks to @j-l for finding an even shorter method.

tl;dr: Add os.system("") near the top of your file.

Python Version: 3.6.7


回答 7

我最喜欢的方法是使用Blessings库(完整披露:我写了它)。例如:

from blessings import Terminal

t = Terminal()
print t.red('This is red.')
print t.bold_bright_red_on_black('Bright red on black')

要打印彩色砖,最可靠的方法是使用背景色打印空间。我用这种技术绘制了鼻子渐进式的进度条

print t.on_green(' ')

您也可以在特定位置打印:

with t.location(0, 5):
    print t.on_yellow(' ')

如果您在游戏过程中不得不考虑其他终端功能,也可以这样做。您可以使用Python的标准字符串格式来保持可读性:

print '{t.clear_eol}You just cleared a {t.bold}whole{t.normal} line!'.format(t=t)

Blessings的好处在于,它尽其所能在各种终端上工作,而不仅仅是(绝大多数)ANSI颜色终端。它还在使代码简洁明了的同时,将无法读取的转义序列保留在代码之外。玩得开心!

My favorite way is with the Blessings library (full disclosure: I wrote it). For example:

from blessings import Terminal

t = Terminal()
print t.red('This is red.')
print t.bold_bright_red_on_black('Bright red on black')

To print colored bricks, the most reliable way is to print spaces with background colors. I use this technique to draw the progress bar in nose-progressive:

print t.on_green(' ')

You can print in specific locations as well:

with t.location(0, 5):
    print t.on_yellow(' ')

If you have to muck with other terminal capabilities in the course of your game, you can do that as well. You can use Python’s standard string formatting to keep it readable:

print '{t.clear_eol}You just cleared a {t.bold}whole{t.normal} line!'.format(t=t)

The nice thing about Blessings is that it does its best to work on all sorts of terminals, not just the (overwhelmingly common) ANSI-color ones. It also keeps unreadable escape sequences out of your code while remaining concise to use. Have fun!


回答 8

sty与colorama相似,但较为冗长,支持8位24位(rgb)颜色,允许您注册自己的样式,支持静音,非常灵活,文档丰富,并且更多。

例子:

from sty import fg, bg, ef, rs

foo = fg.red + 'This is red text!' + fg.rs
bar = bg.blue + 'This has a blue background!' + bg.rs
baz = ef.italic + 'This is italic text' + rs.italic
qux = fg(201) + 'This is pink text using 8bit colors' + fg.rs
qui = fg(255, 10, 10) + 'This is red text using 24bit colors.' + fg.rs

# Add custom colors:

from sty import Style, RgbFg

fg.orange = Style(RgbFg(255, 150, 50))

buf = fg.orange + 'Yay, Im orange.' + fg.rs

print(foo, bar, baz, qux, qui, buf, sep='\n')

印刷品:

演示:

sty is similar to colorama, but it’s less verbose, supports 8bit and 24bit (rgb) colors, allows you to register your own styles, supports muting, is really flexible, well documented and more.

Examples:

from sty import fg, bg, ef, rs

foo = fg.red + 'This is red text!' + fg.rs
bar = bg.blue + 'This has a blue background!' + bg.rs
baz = ef.italic + 'This is italic text' + rs.italic
qux = fg(201) + 'This is pink text using 8bit colors' + fg.rs
qui = fg(255, 10, 10) + 'This is red text using 24bit colors.' + fg.rs

# Add custom colors:

from sty import Style, RgbFg

fg.orange = Style(RgbFg(255, 150, 50))

buf = fg.orange + 'Yay, Im orange.' + fg.rs

print(foo, bar, baz, qux, qui, buf, sep='\n')

prints:

Demo:


回答 9

使用for循环生成一个具有所有颜色的类,以将每种颜色的组合最多迭代到100,然后编写一个带有python颜色的类。请按我的意愿复制并粘贴GPLv2:

class colors:
    '''Colors class:
    reset all colors with colors.reset
    two subclasses fg for foreground and bg for background.
    use as colors.subclass.colorname.
    i.e. colors.fg.red or colors.bg.green
    also, the generic bold, disable, underline, reverse, strikethrough,
    and invisible work with the main class
    i.e. colors.bold
    '''
    reset='\033[0m'
    bold='\033[01m'
    disable='\033[02m'
    underline='\033[04m'
    reverse='\033[07m'
    strikethrough='\033[09m'
    invisible='\033[08m'
    class fg:
        black='\033[30m'
        red='\033[31m'
        green='\033[32m'
        orange='\033[33m'
        blue='\033[34m'
        purple='\033[35m'
        cyan='\033[36m'
        lightgrey='\033[37m'
        darkgrey='\033[90m'
        lightred='\033[91m'
        lightgreen='\033[92m'
        yellow='\033[93m'
        lightblue='\033[94m'
        pink='\033[95m'
        lightcyan='\033[96m'
    class bg:
        black='\033[40m'
        red='\033[41m'
        green='\033[42m'
        orange='\033[43m'
        blue='\033[44m'
        purple='\033[45m'
        cyan='\033[46m'
        lightgrey='\033[47m'

generated a class with all the colors using a for loop to iterate every combination of color up to 100, then wrote a class with python colors. Copy and paste as you will, GPLv2 by me:

class colors:
    '''Colors class:
    reset all colors with colors.reset
    two subclasses fg for foreground and bg for background.
    use as colors.subclass.colorname.
    i.e. colors.fg.red or colors.bg.green
    also, the generic bold, disable, underline, reverse, strikethrough,
    and invisible work with the main class
    i.e. colors.bold
    '''
    reset='\033[0m'
    bold='\033[01m'
    disable='\033[02m'
    underline='\033[04m'
    reverse='\033[07m'
    strikethrough='\033[09m'
    invisible='\033[08m'
    class fg:
        black='\033[30m'
        red='\033[31m'
        green='\033[32m'
        orange='\033[33m'
        blue='\033[34m'
        purple='\033[35m'
        cyan='\033[36m'
        lightgrey='\033[37m'
        darkgrey='\033[90m'
        lightred='\033[91m'
        lightgreen='\033[92m'
        yellow='\033[93m'
        lightblue='\033[94m'
        pink='\033[95m'
        lightcyan='\033[96m'
    class bg:
        black='\033[40m'
        red='\033[41m'
        green='\033[42m'
        orange='\033[43m'
        blue='\033[44m'
        purple='\033[45m'
        cyan='\033[46m'
        lightgrey='\033[47m'

回答 10

试试这个简单的代码

def prRed(prt): print("\033[91m {}\033[00m" .format(prt))
def prGreen(prt): print("\033[92m {}\033[00m" .format(prt))
def prYellow(prt): print("\033[93m {}\033[00m" .format(prt))
def prLightPurple(prt): print("\033[94m {}\033[00m" .format(prt))
def prPurple(prt): print("\033[95m {}\033[00m" .format(prt))
def prCyan(prt): print("\033[96m {}\033[00m" .format(prt))
def prLightGray(prt): print("\033[97m {}\033[00m" .format(prt))
def prBlack(prt): print("\033[98m {}\033[00m" .format(prt))

prGreen("Hello world")

Try this simple code

def prRed(prt): print("\033[91m {}\033[00m" .format(prt))
def prGreen(prt): print("\033[92m {}\033[00m" .format(prt))
def prYellow(prt): print("\033[93m {}\033[00m" .format(prt))
def prLightPurple(prt): print("\033[94m {}\033[00m" .format(prt))
def prPurple(prt): print("\033[95m {}\033[00m" .format(prt))
def prCyan(prt): print("\033[96m {}\033[00m" .format(prt))
def prLightGray(prt): print("\033[97m {}\033[00m" .format(prt))
def prBlack(prt): print("\033[98m {}\033[00m" .format(prt))

prGreen("Hello world")

回答 11

在Windows上,您可以使用模块“ win32console”(在某些Python发行版中可用)或模块“ ctypes”(Python 2.5及更高版本)来访问Win32 API。

要查看完整的代码,同时支持方式,见色控制台报告代码Testoob

ctypes示例:

import ctypes

# Constants from the Windows API
STD_OUTPUT_HANDLE = -11
FOREGROUND_RED    = 0x0004 # text color contains red.

def get_csbi_attributes(handle):
    # Based on IPython's winconsole.py, written by Alexander Belchenko
    import struct
    csbi = ctypes.create_string_buffer(22)
    res = ctypes.windll.kernel32.GetConsoleScreenBufferInfo(handle, csbi)
    assert res

    (bufx, bufy, curx, cury, wattr,
    left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
    return wattr


handle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
reset = get_csbi_attributes(handle)

ctypes.windll.kernel32.SetConsoleTextAttribute(handle, FOREGROUND_RED)
print "Cherry on top"
ctypes.windll.kernel32.SetConsoleTextAttribute(handle, reset)

On Windows you can use module ‘win32console’ (available in some Python distributions) or module ‘ctypes’ (Python 2.5 and up) to access the Win32 API.

To see complete code that supports both ways, see the color console reporting code from Testoob.

ctypes example:

import ctypes

# Constants from the Windows API
STD_OUTPUT_HANDLE = -11
FOREGROUND_RED    = 0x0004 # text color contains red.

def get_csbi_attributes(handle):
    # Based on IPython's winconsole.py, written by Alexander Belchenko
    import struct
    csbi = ctypes.create_string_buffer(22)
    res = ctypes.windll.kernel32.GetConsoleScreenBufferInfo(handle, csbi)
    assert res

    (bufx, bufy, curx, cury, wattr,
    left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
    return wattr


handle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
reset = get_csbi_attributes(handle)

ctypes.windll.kernel32.SetConsoleTextAttribute(handle, FOREGROUND_RED)
print "Cherry on top"
ctypes.windll.kernel32.SetConsoleTextAttribute(handle, reset)

回答 12

基于@joeld的答案非常简单

class PrintInColor:
    RED = '\033[91m'
    GREEN = '\033[92m'
    YELLOW = '\033[93m'
    LIGHT_PURPLE = '\033[94m'
    PURPLE = '\033[95m'
    END = '\033[0m'

    @classmethod
    def red(cls, s, **kwargs):
        print(cls.RED + s + cls.END, **kwargs)

    @classmethod
    def green(cls, s, **kwargs):
        print(cls.GREEN + s + cls.END, **kwargs)

    @classmethod
    def yellow(cls, s, **kwargs):
        print(cls.YELLOW + s + cls.END, **kwargs)

    @classmethod
    def lightPurple(cls, s, **kwargs):
        print(cls.LIGHT_PURPLE + s + cls.END, **kwargs)

    @classmethod
    def purple(cls, s, **kwargs):
        print(cls.PURPLE + s + cls.END, **kwargs)

然后就

PrintInColor.red('hello', end=' ')
PrintInColor.green('world')

Stupidly simple based on @joeld’s answer

class PrintInColor:
    RED = '\033[91m'
    GREEN = '\033[92m'
    YELLOW = '\033[93m'
    LIGHT_PURPLE = '\033[94m'
    PURPLE = '\033[95m'
    END = '\033[0m'

    @classmethod
    def red(cls, s, **kwargs):
        print(cls.RED + s + cls.END, **kwargs)

    @classmethod
    def green(cls, s, **kwargs):
        print(cls.GREEN + s + cls.END, **kwargs)

    @classmethod
    def yellow(cls, s, **kwargs):
        print(cls.YELLOW + s + cls.END, **kwargs)

    @classmethod
    def lightPurple(cls, s, **kwargs):
        print(cls.LIGHT_PURPLE + s + cls.END, **kwargs)

    @classmethod
    def purple(cls, s, **kwargs):
        print(cls.PURPLE + s + cls.END, **kwargs)

Then just

PrintInColor.red('hello', end=' ')
PrintInColor.green('world')

回答 13

我已经将@joeld答案包装到具有全局函数的模块中,可以在代码的任何地方使用它。

文件:log.py

HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = "\033[1m"

def disable():
    HEADER = ''
    OKBLUE = ''
    OKGREEN = ''
    WARNING = ''
    FAIL = ''
    ENDC = ''

def infog( msg):
    print OKGREEN + msg + ENDC

def info( msg):
    print OKBLUE + msg + ENDC

def warn( msg):
    print WARNING + msg + ENDC

def err( msg):
    print FAIL + msg + ENDC

用途如下:

 import log
    log.info("Hello World")
    log.err("System Error")

I have wrapped @joeld answer into a module with global functions that I can use anywhere in my code.

file: log.py

HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = "\033[1m"

def disable():
    HEADER = ''
    OKBLUE = ''
    OKGREEN = ''
    WARNING = ''
    FAIL = ''
    ENDC = ''

def infog( msg):
    print OKGREEN + msg + ENDC

def info( msg):
    print OKBLUE + msg + ENDC

def warn( msg):
    print WARNING + msg + ENDC

def err( msg):
    print FAIL + msg + ENDC

use as follows:

 import log
    log.info("Hello World")
    log.err("System Error")

回答 14

对于Windows,除非使用win32api,否则无法使用颜色打印到控制台。

对于Linux,这就像使用print一样简单,这里概述了转义序列:

色彩

对于要像盒子一样打印的字符,实际上取决于您在控制台窗口中使用的字体。井字符号效果很好,但是取决于字体:

#

For Windows you cannot print to console with colors unless you’re using the win32api.

For Linux it’s as simple as using print, with the escape sequences outlined here:

Colors

For the character to print like a box, it really depends on what font you are using for the console window. The pound symbol works well, but it depends on the font:

#

回答 15

# Pure Python 3.x demo, 256 colors
# Works with bash under Linux and MacOS

fg = lambda text, color: "\33[38;5;" + str(color) + "m" + text + "\33[0m"
bg = lambda text, color: "\33[48;5;" + str(color) + "m" + text + "\33[0m"

def print_six(row, format, end="\n"):
    for col in range(6):
        color = row*6 + col - 2
        if color>=0:
            text = "{:3d}".format(color)
            print (format(text,color), end=" ")
        else:
            print(end="    ")   # four spaces
    print(end=end)

for row in range(0, 43):
    print_six(row, fg, " ")
    print_six(row, bg)

# Simple usage: print(fg("text", 160))

# Pure Python 3.x demo, 256 colors
# Works with bash under Linux and MacOS

fg = lambda text, color: "\33[38;5;" + str(color) + "m" + text + "\33[0m"
bg = lambda text, color: "\33[48;5;" + str(color) + "m" + text + "\33[0m"

def print_six(row, format, end="\n"):
    for col in range(6):
        color = row*6 + col - 2
        if color>=0:
            text = "{:3d}".format(color)
            print (format(text,color), end=" ")
        else:
            print(end="    ")   # four spaces
    print(end=end)

for row in range(0, 43):
    print_six(row, fg, " ")
    print_six(row, bg)

# Simple usage: print(fg("text", 160))


回答 16

我最终这样做了,我觉得那是最干净的:

formatters = {             
    'RED': '\033[91m',     
    'GREEN': '\033[92m',   
    'END': '\033[0m',      
}

print 'Master is currently {RED}red{END}!'.format(**formatters)
print 'Help make master {GREEN}green{END} again!'.format(**formatters)

I ended up doing this, I felt it was cleanest:

formatters = {             
    'RED': '\033[91m',     
    'GREEN': '\033[92m',   
    'END': '\033[0m',      
}

print 'Master is currently {RED}red{END}!'.format(**formatters)
print 'Help make master {GREEN}green{END} again!'.format(**formatters)

回答 17

使用https://pypi.python.org/pypi/lazyme 在@joeld答案上构建pip install -U lazyme

from lazyme.string import color_print
>>> color_print('abc')
abc
>>> color_print('abc', color='pink')
abc
>>> color_print('abc', color='red')
abc
>>> color_print('abc', color='yellow')
abc
>>> color_print('abc', color='green')
abc
>>> color_print('abc', color='blue', underline=True)
abc
>>> color_print('abc', color='blue', underline=True, bold=True)
abc
>>> color_print('abc', color='pink', underline=True, bold=True)
abc

屏幕截图:


color_print使用新的格式化程序对进行了一些更新,例如:

>>> from lazyme.string import palette, highlighter, formatter
>>> from lazyme.string import color_print
>>> palette.keys() # Available colors.
['pink', 'yellow', 'cyan', 'magenta', 'blue', 'gray', 'default', 'black', 'green', 'white', 'red']
>>> highlighter.keys() # Available highlights.
['blue', 'pink', 'gray', 'black', 'yellow', 'cyan', 'green', 'magenta', 'white', 'red']
>>> formatter.keys() # Available formatter, 
['hide', 'bold', 'italic', 'default', 'fast_blinking', 'faint', 'strikethrough', 'underline', 'blinking', 'reverse']

注:italicfast blinkingstrikethrough可能无法在所有终端上使用,在Mac / Ubuntu上也无法使用。

例如

>>> color_print('foo bar', color='pink', highlight='white')
foo bar
>>> color_print('foo bar', color='pink', highlight='white', reverse=True)
foo bar
>>> color_print('foo bar', color='pink', highlight='white', bold=True)
foo bar
>>> color_print('foo bar', color='pink', highlight='white', faint=True)
foo bar
>>> color_print('foo bar', color='pink', highlight='white', faint=True, reverse=True)
foo bar
>>> color_print('foo bar', color='pink', highlight='white', underline=True, reverse=True)
foo bar

屏幕截图:

Building on @joeld answer, using https://pypi.python.org/pypi/lazyme pip install -U lazyme :

from lazyme.string import color_print
>>> color_print('abc')
abc
>>> color_print('abc', color='pink')
abc
>>> color_print('abc', color='red')
abc
>>> color_print('abc', color='yellow')
abc
>>> color_print('abc', color='green')
abc
>>> color_print('abc', color='blue', underline=True)
abc
>>> color_print('abc', color='blue', underline=True, bold=True)
abc
>>> color_print('abc', color='pink', underline=True, bold=True)
abc

Screenshot:


Some updates to the color_print with new formatters, e.g.:

>>> from lazyme.string import palette, highlighter, formatter
>>> from lazyme.string import color_print
>>> palette.keys() # Available colors.
['pink', 'yellow', 'cyan', 'magenta', 'blue', 'gray', 'default', 'black', 'green', 'white', 'red']
>>> highlighter.keys() # Available highlights.
['blue', 'pink', 'gray', 'black', 'yellow', 'cyan', 'green', 'magenta', 'white', 'red']
>>> formatter.keys() # Available formatter, 
['hide', 'bold', 'italic', 'default', 'fast_blinking', 'faint', 'strikethrough', 'underline', 'blinking', 'reverse']

Note: italic, fast blinking and strikethrough may not work on all terminals, doesn’t work on Mac / Ubuntu.

E.g.

>>> color_print('foo bar', color='pink', highlight='white')
foo bar
>>> color_print('foo bar', color='pink', highlight='white', reverse=True)
foo bar
>>> color_print('foo bar', color='pink', highlight='white', bold=True)
foo bar
>>> color_print('foo bar', color='pink', highlight='white', faint=True)
foo bar
>>> color_print('foo bar', color='pink', highlight='white', faint=True, reverse=True)
foo bar
>>> color_print('foo bar', color='pink', highlight='white', underline=True, reverse=True)
foo bar

Screenshot:


回答 18

def black(text):
    print('\033[30m', text, '\033[0m', sep='')

def red(text):
    print('\033[31m', text, '\033[0m', sep='')

def green(text):
    print('\033[32m', text, '\033[0m', sep='')

def yellow(text):
    print('\033[33m', text, '\033[0m', sep='')

def blue(text):
    print('\033[34m', text, '\033[0m', sep='')

def magenta(text):
    print('\033[35m', text, '\033[0m', sep='')

def cyan(text):
    print('\033[36m', text, '\033[0m', sep='')

def gray(text):
    print('\033[90m', text, '\033[0m', sep='')


black("BLACK")
red("RED")
green("GREEN")
yellow("YELLOW")
blue("BLACK")
magenta("MAGENTA")
cyan("CYAN")
gray("GRAY")

在线尝试

def black(text):
    print('\033[30m', text, '\033[0m', sep='')

def red(text):
    print('\033[31m', text, '\033[0m', sep='')

def green(text):
    print('\033[32m', text, '\033[0m', sep='')

def yellow(text):
    print('\033[33m', text, '\033[0m', sep='')

def blue(text):
    print('\033[34m', text, '\033[0m', sep='')

def magenta(text):
    print('\033[35m', text, '\033[0m', sep='')

def cyan(text):
    print('\033[36m', text, '\033[0m', sep='')

def gray(text):
    print('\033[90m', text, '\033[0m', sep='')


black("BLACK")
red("RED")
green("GREEN")
yellow("YELLOW")
blue("BLACK")
magenta("MAGENTA")
cyan("CYAN")
gray("GRAY")

Try online


回答 19

请注意,with关键字与需要重置的修饰符(使用Python 3和Colorama)混合的程度如何:

from colorama import Fore, Style
import sys

class Highlight:
  def __init__(self, clazz, color):
    self.color = color
    self.clazz = clazz
  def __enter__(self):
    print(self.color, end="")
  def __exit__(self, type, value, traceback):
    if self.clazz == Fore:
      print(Fore.RESET, end="")
    else:
      assert self.clazz == Style
      print(Style.RESET_ALL, end="")
    sys.stdout.flush()

with Highlight(Fore, Fore.GREEN):
  print("this is highlighted")
print("this is not")

note how well the with keyword mixes with modifiers like these that need to be reset (using Python 3 and Colorama):

from colorama import Fore, Style
import sys

class Highlight:
  def __init__(self, clazz, color):
    self.color = color
    self.clazz = clazz
  def __enter__(self):
    print(self.color, end="")
  def __exit__(self, type, value, traceback):
    if self.clazz == Fore:
      print(Fore.RESET, end="")
    else:
      assert self.clazz == Style
      print(Style.RESET_ALL, end="")
    sys.stdout.flush()

with Highlight(Fore, Fore.GREEN):
  print("this is highlighted")
print("this is not")

回答 20

您可以使用curses库的Python实现:http : //docs.python.org/library/curses.html

另外,运行此命令,您将找到您的盒子:

for i in range(255):
    print i, chr(i)

You can use the Python implementation of the curses library: http://docs.python.org/library/curses.html

Also, run this and you’ll find your box:

for i in range(255):
    print i, chr(i)

回答 21

您可以使用CLINT:

from clint.textui import colored
print colored.red('some warning message')
print colored.green('nicely done!')

从GitHub获取它

You could use CLINT:

from clint.textui import colored
print colored.red('some warning message')
print colored.green('nicely done!')

Get it from GitHub.


回答 22

如果您正在编写游戏,也许您想更改背景颜色并仅使用空格?例如:

print " "+ "\033[01;41m" + " " +"\033[01;46m"  + "  " + "\033[01;42m"

If you are programming a game perhaps you would like to change the background color and use only spaces? For example:

print " "+ "\033[01;41m" + " " +"\033[01;46m"  + "  " + "\033[01;42m"

回答 23

我知道我迟到了。但是,我有一个名为ColorIt。非常简单。

这里有些例子:

from ColorIt import *

# Use this to ensure that ColorIt will be usable by certain command line interfaces
initColorIt()

# Foreground
print (color ('This text is red', colors.RED))
print (color ('This text is orange', colors.ORANGE))
print (color ('This text is yellow', colors.YELLOW))
print (color ('This text is green', colors.GREEN))
print (color ('This text is blue', colors.BLUE))
print (color ('This text is purple', colors.PURPLE))
print (color ('This text is white', colors.WHITE))

# Background
print (background ('This text has a background that is red', colors.RED))
print (background ('This text has a background that is orange', colors.ORANGE))
print (background ('This text has a background that is yellow', colors.YELLOW))
print (background ('This text has a background that is green', colors.GREEN))
print (background ('This text has a background that is blue', colors.BLUE))
print (background ('This text has a background that is purple', colors.PURPLE))
print (background ('This text has a background that is white', colors.WHITE))

# Custom
print (color ("This color has a custom grey text color", (150, 150, 150))
print (background ("This color has a custom grey background", (150, 150, 150))

# Combination
print (background (color ("This text is blue with a white background", colors.BLUE), colors.WHITE))

这给您:

还值得注意的是,这是跨平台的,并且已经在Mac,Linux和Windows上进行了测试。

您可能想尝试一下:https : //github.com/CodeForeverAndEver/ColorIt

注意:几天后将添加闪烁,斜体,粗体等。

I know that I am late. But, I have a library called ColorIt. It is super simple.

Here are some examples:

from ColorIt import *

# Use this to ensure that ColorIt will be usable by certain command line interfaces
initColorIt()

# Foreground
print (color ('This text is red', colors.RED))
print (color ('This text is orange', colors.ORANGE))
print (color ('This text is yellow', colors.YELLOW))
print (color ('This text is green', colors.GREEN))
print (color ('This text is blue', colors.BLUE))
print (color ('This text is purple', colors.PURPLE))
print (color ('This text is white', colors.WHITE))

# Background
print (background ('This text has a background that is red', colors.RED))
print (background ('This text has a background that is orange', colors.ORANGE))
print (background ('This text has a background that is yellow', colors.YELLOW))
print (background ('This text has a background that is green', colors.GREEN))
print (background ('This text has a background that is blue', colors.BLUE))
print (background ('This text has a background that is purple', colors.PURPLE))
print (background ('This text has a background that is white', colors.WHITE))

# Custom
print (color ("This color has a custom grey text color", (150, 150, 150))
print (background ("This color has a custom grey background", (150, 150, 150))

# Combination
print (background (color ("This text is blue with a white background", colors.BLUE), colors.WHITE))

This gives you:

It’s also worth noting that this is cross platform and has been tested on mac, linux, and windows.

You might want to try it out: https://github.com/CodeForeverAndEver/ColorIt

Note: Blinking, italics, bold, etc. will be added in a few days.


回答 24

如果您使用的是Windows,那么就到这里!

# display text on a Windows console
# Windows XP with Python27 or Python32
from ctypes import windll
# needed for Python2/Python3 diff
try:
    input = raw_input
except:
    pass
STD_OUTPUT_HANDLE = -11
stdout_handle = windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
# look at the output and select the color you want
# for instance hex E is yellow on black
# hex 1E is yellow on blue
# hex 2E is yellow on green and so on
for color in range(0, 75):
     windll.kernel32.SetConsoleTextAttribute(stdout_handle, color)
     print("%X --> %s" % (color, "Have a fine day!"))
     input("Press Enter to go on ... ")

If you are using Windows, then here you go!

# display text on a Windows console
# Windows XP with Python27 or Python32
from ctypes import windll
# needed for Python2/Python3 diff
try:
    input = raw_input
except:
    pass
STD_OUTPUT_HANDLE = -11
stdout_handle = windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
# look at the output and select the color you want
# for instance hex E is yellow on black
# hex 1E is yellow on blue
# hex 2E is yellow on green and so on
for color in range(0, 75):
     windll.kernel32.SetConsoleTextAttribute(stdout_handle, color)
     print("%X --> %s" % (color, "Have a fine day!"))
     input("Press Enter to go on ... ")

回答 25

如果您使用的是Django

>>> from django.utils.termcolors import colorize
>>> print colorize("Hello World!", fg="blue", bg='red',
...                 opts=('bold', 'blink', 'underscore',))
Hello World!
>>> help(colorize)

快照:

(我通常在运行服务器终端上使用彩色输出进行调试,所以我添加了它。)

您可以测试它是否已安装在您的计算机中:
$ python -c "import django; print django.VERSION"
要安装它,请检查:如何安装Django

试试看!!

If you are using Django

>>> from django.utils.termcolors import colorize
>>> print colorize("Hello World!", fg="blue", bg='red',
...                 opts=('bold', 'blink', 'underscore',))
Hello World!
>>> help(colorize)

snapshot:

(I generally use colored output for debugging on runserver terminal so I added it.)

You can test if it is installed in your machine:
$ python -c "import django; print django.VERSION"
To install it check: How to install Django

Give it a Try!!


回答 26

这是一个诅咒的例子:

import curses

def main(stdscr):
    stdscr.clear()
    if curses.has_colors():
        for i in xrange(1, curses.COLORS):
            curses.init_pair(i, i, curses.COLOR_BLACK)
            stdscr.addstr("COLOR %d! " % i, curses.color_pair(i))
            stdscr.addstr("BOLD! ", curses.color_pair(i) | curses.A_BOLD)
            stdscr.addstr("STANDOUT! ", curses.color_pair(i) | curses.A_STANDOUT)
            stdscr.addstr("UNDERLINE! ", curses.color_pair(i) | curses.A_UNDERLINE)
            stdscr.addstr("BLINK! ", curses.color_pair(i) | curses.A_BLINK)
            stdscr.addstr("DIM! ", curses.color_pair(i) | curses.A_DIM)
            stdscr.addstr("REVERSE! ", curses.color_pair(i) | curses.A_REVERSE)
    stdscr.refresh()
    stdscr.getch()

if __name__ == '__main__':
    print "init..."
    curses.wrapper(main)

Here’s a curses example:

import curses

def main(stdscr):
    stdscr.clear()
    if curses.has_colors():
        for i in xrange(1, curses.COLORS):
            curses.init_pair(i, i, curses.COLOR_BLACK)
            stdscr.addstr("COLOR %d! " % i, curses.color_pair(i))
            stdscr.addstr("BOLD! ", curses.color_pair(i) | curses.A_BOLD)
            stdscr.addstr("STANDOUT! ", curses.color_pair(i) | curses.A_STANDOUT)
            stdscr.addstr("UNDERLINE! ", curses.color_pair(i) | curses.A_UNDERLINE)
            stdscr.addstr("BLINK! ", curses.color_pair(i) | curses.A_BLINK)
            stdscr.addstr("DIM! ", curses.color_pair(i) | curses.A_DIM)
            stdscr.addstr("REVERSE! ", curses.color_pair(i) | curses.A_REVERSE)
    stdscr.refresh()
    stdscr.getch()

if __name__ == '__main__':
    print "init..."
    curses.wrapper(main)

回答 27

https://raw.github.com/fabric/fabric/master/fabric/colors.py

"""
.. versionadded:: 0.9.2

Functions for wrapping strings in ANSI color codes.

Each function within this module returns the input string ``text``, wrapped
with ANSI color codes for the appropriate color.

For example, to print some text as green on supporting terminals::

    from fabric.colors import green

    print(green("This text is green!"))

Because these functions simply return modified strings, you can nest them::

    from fabric.colors import red, green

    print(red("This sentence is red, except for " + \
          green("these words, which are green") + "."))

If ``bold`` is set to ``True``, the ANSI flag for bolding will be flipped on
for that particular invocation, which usually shows up as a bold or brighter
version of the original color on most terminals.
"""


def _wrap_with(code):

    def inner(text, bold=False):
        c = code
        if bold:
            c = "1;%s" % c
        return "\033[%sm%s\033[0m" % (c, text)
    return inner

red = _wrap_with('31')
green = _wrap_with('32')
yellow = _wrap_with('33')
blue = _wrap_with('34')
magenta = _wrap_with('35')
cyan = _wrap_with('36')
white = _wrap_with('37')

https://raw.github.com/fabric/fabric/master/fabric/colors.py

"""
.. versionadded:: 0.9.2

Functions for wrapping strings in ANSI color codes.

Each function within this module returns the input string ``text``, wrapped
with ANSI color codes for the appropriate color.

For example, to print some text as green on supporting terminals::

    from fabric.colors import green

    print(green("This text is green!"))

Because these functions simply return modified strings, you can nest them::

    from fabric.colors import red, green

    print(red("This sentence is red, except for " + \
          green("these words, which are green") + "."))

If ``bold`` is set to ``True``, the ANSI flag for bolding will be flipped on
for that particular invocation, which usually shows up as a bold or brighter
version of the original color on most terminals.
"""


def _wrap_with(code):

    def inner(text, bold=False):
        c = code
        if bold:
            c = "1;%s" % c
        return "\033[%sm%s\033[0m" % (c, text)
    return inner

red = _wrap_with('31')
green = _wrap_with('32')
yellow = _wrap_with('33')
blue = _wrap_with('34')
magenta = _wrap_with('35')
cyan = _wrap_with('36')
white = _wrap_with('37')

回答 28

asciimatics为构建文本UI和动画提供了可移植的支持:

#!/usr/bin/env python
from asciimatics.effects import RandomNoise  # $ pip install asciimatics
from asciimatics.renderers import SpeechBubble, Rainbow
from asciimatics.scene import Scene
from asciimatics.screen import Screen
from asciimatics.exceptions import ResizeScreenError


def demo(screen):
    render = Rainbow(screen, SpeechBubble('Rainbow'))
    effects = [RandomNoise(screen, signal=render)]
    screen.play([Scene(effects, -1)], stop_on_resize=True)

while True:
    try:
        Screen.wrapper(demo)
        break
    except ResizeScreenError:
        pass

Asciicast:

asciimatics provides a portable support for building text UI and animations:

#!/usr/bin/env python
from asciimatics.effects import RandomNoise  # $ pip install asciimatics
from asciimatics.renderers import SpeechBubble, Rainbow
from asciimatics.scene import Scene
from asciimatics.screen import Screen
from asciimatics.exceptions import ResizeScreenError


def demo(screen):
    render = Rainbow(screen, SpeechBubble('Rainbow'))
    effects = [RandomNoise(screen, signal=render)]
    screen.play([Scene(effects, -1)], stop_on_resize=True)

while True:
    try:
        Screen.wrapper(demo)
        break
    except ResizeScreenError:
        pass

Asciicast:


回答 29

另一个包装python 3打印功能的pypi模块:

https://pypi.python.org/pypi/colorprint

如果您也可以在python 2.x中使用它from __future__ import print。这是来自模块pypi页面的python 2示例:

from __future__ import print_function
from colorprint import *

print('Hello', 'world', color='blue', end='', sep=', ')
print('!', color='red', format=['bold', 'blink'])

输出“你好,世界!” 用蓝色和感叹号标记为红色和闪烁。

Yet another pypi module that wraps the python 3 print function:

https://pypi.python.org/pypi/colorprint

It’s usable in python 2.x if you also from __future__ import print. Here is a python 2 example from the modules pypi page:

from __future__ import print_function
from colorprint import *

print('Hello', 'world', color='blue', end='', sep=', ')
print('!', color='red', format=['bold', 'blink'])

Outputs “Hello, world!” with the words in blue and the exclamation mark bold red and blinking.


从Python调用外部命令

问题:从Python调用外部命令

您如何在Python脚本中调用外部命令(就像我在Unix Shell或Windows命令提示符下键入的一样)?

How do you call an external command (as if I’d typed it at the Unix shell or Windows command prompt) from within a Python script?


回答 0

查看标准库中的子流程模块:

import subprocess
subprocess.run(["ls", "-l"])

的优势subprocess主场迎战system的是,它是更灵活(你可以得到的stdoutstderr,“真正”的状态代码,更好的错误处理,等等)。

官方文件建议subprocess在替代模块os.system()

subprocess模块提供了更强大的功能来生成新流程并检索其结果。使用该模块优于使用此功能[ os.system()]。

与子模块更换旧的功能中部分subprocess文件可能有一些有益的食谱。

对于3.5之前的Python版本,请使用call

import subprocess
subprocess.call(["ls", "-l"])

Look at the subprocess module in the standard library:

import subprocess
subprocess.run(["ls", "-l"])

The advantage of subprocess vs. system is that it is more flexible (you can get the stdout, stderr, the “real” status code, better error handling, etc…).

The official documentation recommends the subprocess module over the alternative os.system():

The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function [os.system()].

The Replacing Older Functions with the subprocess Module section in the subprocess documentation may have some helpful recipes.

For versions of Python before 3.5, use call:

import subprocess
subprocess.call(["ls", "-l"])

回答 1

下面总结了调用外部程序的方法以及每种方法的优缺点:

  1. os.system("some_command with args")将命令和参数传递到系统的外壳程序。很好,因为您实际上可以以这种方式一次运行多个命令,并设置管道和输入/输出重定向。例如:

    os.system("some_command < input_file | another_command > output_file")  

但是,尽管这样做很方便,但您必须手动处理转义字符(例如空格等)的外壳字符。另一方面,这也使您可以运行仅是外壳程序命令而非实际上是外部程序的命令。请参阅文档

  1. stream = os.popen("some_command with args")os.system除了会为您提供类似于文件的对象之外,您可以使用该对象来访问该过程的标准输入/输出,它的作用与之相同。Popen还有其他3种变体,它们对I / O的处理略有不同。如果您将所有内容都作为字符串传递,那么您的命令将传递到外壳程序;如果将它们作为列表传递,则无需担心转义任何内容。请参阅文档

  2. 模块的Popensubprocess。它旨在替代它,os.popen但缺点是由于太全面而使它稍微复杂一些。例如,您会说:

    print subprocess.Popen("echo Hello World", shell=True, stdout=subprocess.PIPE).stdout.read()

    代替:

    print os.popen("echo Hello World").read()

    但是将所有选项都放在一个统一的类中而不是4个不同的popen函数是一件好事。请参阅文档

  3. call来自subprocess模块的功能。基本上就像Popen类一样,并接受所有相同的参数,但是它只是等待命令完成并提供返回代码。例如:

    return_code = subprocess.call("echo Hello World", shell=True)  

    请参阅文档

  4. 如果您使用的是Python 3.5或更高版本,则可以使用新subprocess.run函数,该函数与上面的代码非常相似,但是更加灵活,并CompletedProcess在命令完成执行后返回一个对象。

  5. os模块还具有您在C程序中拥有的所有fork / exec / spawn函数,但是我不建议直接使用它们。

subprocess模块可能是您所使用的模块。

最后,请注意,对于所有方法,在这些方法中,您将要由外壳执行的最终命令作为字符串传递给您,并且您有责任对其进行转义。如果您传递的字符串的任何部分不能被完全信任,则将带来严重的安全隐患。例如,如果用户正在输入字符串的某些/任何部分。如果不确定,请仅将这些方法与常量一起使用。为了给您暗示的含义,请考虑以下代码:

print subprocess.Popen("echo %s " % user_input, stdout=PIPE).stdout.read()

并想象用户输入了“我的妈妈不爱我&& rm -rf /”这可能会擦除整个文件系统的信息。

Here’s a summary of the ways to call external programs and the advantages and disadvantages of each:

  1. os.system("some_command with args") passes the command and arguments to your system’s shell. This is nice because you can actually run multiple commands at once in this manner and set up pipes and input/output redirection. For example:

    os.system("some_command < input_file | another_command > output_file")  
    

However, while this is convenient, you have to manually handle the escaping of shell characters such as spaces, etc. On the other hand, this also lets you run commands which are simply shell commands and not actually external programs. See the documentation.

  1. stream = os.popen("some_command with args") will do the same thing as os.system except that it gives you a file-like object that you can use to access standard input/output for that process. There are 3 other variants of popen that all handle the i/o slightly differently. If you pass everything as a string, then your command is passed to the shell; if you pass them as a list then you don’t need to worry about escaping anything. See the documentation.

  2. The Popen class of the subprocess module. This is intended as a replacement for os.popen but has the downside of being slightly more complicated by virtue of being so comprehensive. For example, you’d say:

    print subprocess.Popen("echo Hello World", shell=True, stdout=subprocess.PIPE).stdout.read()
    

    instead of:

    print os.popen("echo Hello World").read()
    

    but it is nice to have all of the options there in one unified class instead of 4 different popen functions. See the documentation.

  3. The call function from the subprocess module. This is basically just like the Popen class and takes all of the same arguments, but it simply waits until the command completes and gives you the return code. For example:

    return_code = subprocess.call("echo Hello World", shell=True)  
    

    See the documentation.

  4. If you’re on Python 3.5 or later, you can use the new subprocess.run function, which is a lot like the above but even more flexible and returns a CompletedProcess object when the command finishes executing.

  5. The os module also has all of the fork/exec/spawn functions that you’d have in a C program, but I don’t recommend using them directly.

The subprocess module should probably be what you use.

Finally please be aware that for all methods where you pass the final command to be executed by the shell as a string and you are responsible for escaping it. There are serious security implications if any part of the string that you pass can not be fully trusted. For example, if a user is entering some/any part of the string. If you are unsure, only use these methods with constants. To give you a hint of the implications consider this code:

print subprocess.Popen("echo %s " % user_input, stdout=PIPE).stdout.read()

and imagine that the user enters something “my mama didnt love me && rm -rf /” which could erase the whole filesystem.


回答 2

典型的实现:

import subprocess

p = subprocess.Popen('ls', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in p.stdout.readlines():
    print line,
retval = p.wait()

您可以随意使用stdout管道中的数据进行所需的操作。实际上,您可以简单地省略这些参数(stdout=stderr=),其行为类似于os.system()

Typical implementation:

import subprocess

p = subprocess.Popen('ls', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in p.stdout.readlines():
    print line,
retval = p.wait()

You are free to do what you want with the stdout data in the pipe. In fact, you can simply omit those parameters (stdout= and stderr=) and it’ll behave like os.system().


回答 3

关于从调用者中分离子进程的一些提示(在后台启动子进程)。

假设您要从CGI脚本开始一个长任务。也就是说,子进程的生存期应比CGI脚本执行进程的生存期长。

子流程模块文档中的经典示例是:

import subprocess
import sys

# Some code here

pid = subprocess.Popen([sys.executable, "longtask.py"]) # Call subprocess

# Some more code here

这里的想法是,您不想在long任务.py完成之前在“调用子进程”行中等待。但是尚不清楚示例中“这里有更多代码”行之后会发生什么。

我的目标平台是FreeBSD,但是开发是在Windows上进行的,因此我首先在Windows上遇到了问题。

在Windows(Windows XP)上,直到longtask.py完成工作后,父进程才会完成。这不是CGI脚本中想要的。这个问题不是特定于Python的。在PHP社区中,问题是相同的。

解决方案是将DETACHED_PROCESS 进程创建标志传递给Windows API中的基础CreateProcess函数。如果碰巧安装了pywin32,则可以从win32process模块​​中导入该标志,否则您应该自己定义它:

DETACHED_PROCESS = 0x00000008

pid = subprocess.Popen([sys.executable, "longtask.py"],
                       creationflags=DETACHED_PROCESS).pid

/ * UPD 2015.10.27 @eryksun在下面的注释中指出,语义正确的标志是CREATE_NEW_CONSOLE(0x00000010)* /

在FreeBSD上,我们还有另一个问题:父进程完成后,它也会完成子进程。那也不是您在CGI脚本中想要的。一些实验表明,问题似乎出在共享sys.stdout。可行的解决方案如下:

pid = subprocess.Popen([sys.executable, "longtask.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)

我没有检查其他平台上的代码,也不知道FreeBSD上该行为的原因。如果有人知道,请分享您的想法。谷歌搜索在Python中启动后台进程尚未阐明。

Some hints on detaching the child process from the calling one (starting the child process in background).

Suppose you want to start a long task from a CGI script. That is, the child process should live longer than the CGI script execution process.

The classical example from the subprocess module documentation is:

import subprocess
import sys

# Some code here

pid = subprocess.Popen([sys.executable, "longtask.py"]) # Call subprocess

# Some more code here

The idea here is that you do not want to wait in the line ‘call subprocess’ until the longtask.py is finished. But it is not clear what happens after the line ‘some more code here’ from the example.

My target platform was FreeBSD, but the development was on Windows, so I faced the problem on Windows first.

On Windows (Windows XP), the parent process will not finish until the longtask.py has finished its work. It is not what you want in a CGI script. The problem is not specific to Python; in the PHP community the problems are the same.

The solution is to pass DETACHED_PROCESS Process Creation Flag to the underlying CreateProcess function in Windows API. If you happen to have installed pywin32, you can import the flag from the win32process module, otherwise you should define it yourself:

DETACHED_PROCESS = 0x00000008

pid = subprocess.Popen([sys.executable, "longtask.py"],
                       creationflags=DETACHED_PROCESS).pid

/* UPD 2015.10.27 @eryksun in a comment below notes, that the semantically correct flag is CREATE_NEW_CONSOLE (0x00000010) */

On FreeBSD we have another problem: when the parent process is finished, it finishes the child processes as well. And that is not what you want in a CGI script either. Some experiments showed that the problem seemed to be in sharing sys.stdout. And the working solution was the following:

pid = subprocess.Popen([sys.executable, "longtask.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)

I have not checked the code on other platforms and do not know the reasons of the behaviour on FreeBSD. If anyone knows, please share your ideas. Googling on starting background processes in Python does not shed any light yet.


回答 4

import os
os.system("your command")

请注意,这很危险,因为未清除命令。我留给你去谷歌搜索有关“操作系统”和“系统”模块的相关文档。有很多函数(exec *和spawn *)将执行类似的操作。

import os
os.system("your command")

Note that this is dangerous, since the command isn’t cleaned. I leave it up to you to google for the relevant documentation on the ‘os’ and ‘sys’ modules. There are a bunch of functions (exec* and spawn*) that will do similar things.


回答 5

我建议你使用模块,而不是使用os.system因为它没有外壳逃避你,因此更加安全。

subprocess.call(['ping', 'localhost'])

I’d recommend using the subprocess module instead of os.system because it does shell escaping for you and is therefore much safer.

subprocess.call(['ping', 'localhost'])

回答 6

import os
cmd = 'ls -al'
os.system(cmd)

如果要返回命令的结果,可以使用os.popen。但是,自2.6版以来,不推荐使用此方法,而支持subprocess模块,其他答案已经很好地涵盖了这一点。

import os
cmd = 'ls -al'
os.system(cmd)

If you want to return the results of the command, you can use os.popen. However, this is deprecated since version 2.6 in favor of the subprocess module, which other answers have covered well.


回答 7

有很多不同的库,可让您使用Python调用外部命令。对于每个库,我都进行了描述并显示了调用外部命令的示例。我用作示例的命令是ls -l(列出所有文件)。如果您想了解有关任何库的更多信息,我已列出并链接了每个库的文档。

资料来源:

这些都是库:

希望这可以帮助您决定使用哪个库:)

子过程

子进程允许您调用外部命令,并将其连接到它们的输入/输出/错误管道(stdin,stdout和stderr)。子进程是运行命令的默认选择,但有时其他模块更好。

subprocess.run(["ls", "-l"]) # Run command
subprocess.run(["ls", "-l"], stdout=subprocess.PIPE) # This will run the command and return any output
subprocess.run(shlex.split("ls -l")) # You can also use the shlex library to split the command

操作系统

os用于“取决于操作系统的功能”。它也可以用于通过os.system和调用外部命令os.popen(注意:还有一个subprocess.popen)。os将始终运行该shell,对于不需要或不知道如何使用的人来说,它是一个简单的选择subprocess.run

os.system("ls -l") # run command
os.popen("ls -l").read() # This will run the command and return any output

SH

sh是一个子进程接口,可让您像调用程序一样调用程序。如果要多次运行命令,这很有用。

sh.ls("-l") # Run command normally
ls_cmd = sh.Command("ls") # Save command as a variable
ls_cmd() # Run command as if it were a function

plumbum是用于“类似脚本”的Python程序的库。您可以像中的函数那样调用程序sh。如果您要在没有外壳的情况下运行管道,则Plumbum很有用。

ls_cmd = plumbum.local("ls -l") # get command
ls_cmd() # run command

期待

pexpect使您可以生成子应用程序,对其进行控制并在其输出中找到模式。对于在Unix上需要tty的命令,这是子过程的更好选择。

pexpect.run("ls -l") # Run command as normal
child = pexpect.spawn('scp foo user@example.com:.') # Spawns child application
child.expect('Password:') # When this is the output
child.sendline('mypassword')

fabric是一个Python 2.5和2.7库。它允许您执行本地和远程Shell命令。Fabric是在安全Shell(SSH)中运行命令的简单替代方案

fabric.operations.local('ls -l') # Run command as normal
fabric.operations.local('ls -l', capture = True) # Run command and receive output

使者

特使被称为“人类子过程”。它用作subprocess模块周围的便利包装。

r = envoy.run("ls -l") # Run command
r.std_out # get output

命令

commands包含的包装函数os.popen,但由于subprocess是更好的选择,它已从Python 3中删除。

该编辑基于JF Sebastian的评论。

There are lots of different libraries which allow you to call external commands with Python. For each library I’ve given a description and shown an example of calling an external command. The command I used as the example is ls -l (list all files). If you want to find out more about any of the libraries I’ve listed and linked the documentation for each of them.

Sources:

These are all the libraries:

Hopefully this will help you make a decision on which library to use :)

subprocess

Subprocess allows you to call external commands and connect them to their input/output/error pipes (stdin, stdout, and stderr). Subprocess is the default choice for running commands, but sometimes other modules are better.

subprocess.run(["ls", "-l"]) # Run command
subprocess.run(["ls", "-l"], stdout=subprocess.PIPE) # This will run the command and return any output
subprocess.run(shlex.split("ls -l")) # You can also use the shlex library to split the command

os

os is used for “operating system dependent functionality”. It can also be used to call external commands with os.system and os.popen (Note: There is also a subprocess.popen). os will always run the shell and is a simple alternative for people who don’t need to, or don’t know how to use subprocess.run.

os.system("ls -l") # run command
os.popen("ls -l").read() # This will run the command and return any output

sh

sh is a subprocess interface which lets you call programs as if they were functions. This is useful if you want to run a command multiple times.

sh.ls("-l") # Run command normally
ls_cmd = sh.Command("ls") # Save command as a variable
ls_cmd() # Run command as if it were a function

plumbum

plumbum is a library for “script-like” Python programs. You can call programs like functions as in sh. Plumbum is useful if you want to run a pipeline without the shell.

ls_cmd = plumbum.local("ls -l") # get command
ls_cmd() # run command

pexpect

pexpect lets you spawn child applications, control them and find patterns in their output. This is a better alternative to subprocess for commands that expect a tty on Unix.

pexpect.run("ls -l") # Run command as normal
child = pexpect.spawn('scp foo user@example.com:.') # Spawns child application
child.expect('Password:') # When this is the output
child.sendline('mypassword')

fabric

fabric is a Python 2.5 and 2.7 library. It allows you to execute local and remote shell commands. Fabric is simple alternative for running commands in a secure shell (SSH)

fabric.operations.local('ls -l') # Run command as normal
fabric.operations.local('ls -l', capture = True) # Run command and receive output

envoy

envoy is known as “subprocess for humans”. It is used as a convenience wrapper around the subprocess module.

r = envoy.run("ls -l") # Run command
r.std_out # get output

commands

commands contains wrapper functions for os.popen, but it has been removed from Python 3 since subprocess is a better alternative.

The edit was based on J.F. Sebastian’s comment.


回答 8

我总是用fabric这样的东西:

from fabric.operations import local
result = local('ls', capture=True)
print "Content:/n%s" % (result, )

但这似乎是一个很好的工具:sh(Python子进程接口)

看一个例子:

from sh import vgdisplay
print vgdisplay()
print vgdisplay('-v')
print vgdisplay(v=True)

I always use fabric for this things like:

from fabric.operations import local
result = local('ls', capture=True)
print "Content:/n%s" % (result, )

But this seem to be a good tool: sh (Python subprocess interface).

Look at an example:

from sh import vgdisplay
print vgdisplay()
print vgdisplay('-v')
print vgdisplay(v=True)

回答 9

还要检查“ pexpect” Python库。

它允许交互式控制外部程序/命令,甚至包括ssh,ftp,telnet等。您可以键入以下内容:

child = pexpect.spawn('ftp 192.168.0.24')

child.expect('(?i)name .*: ')

child.sendline('anonymous')

child.expect('(?i)password')

Check the “pexpect” Python library, too.

It allows for interactive controlling of external programs/commands, even ssh, ftp, telnet, etc. You can just type something like:

child = pexpect.spawn('ftp 192.168.0.24')

child.expect('(?i)name .*: ')

child.sendline('anonymous')

child.expect('(?i)password')

回答 10

与标准库

使用子流程模块(Python 3):

import subprocess
subprocess.run(['ls', '-l'])

这是推荐的标准方式。但是,构造和编写更复杂的任务(管道,输出,输入等)可能很繁琐。

关于Python版本的注意事项:如果您仍在使用Python 2,subprocess.call的工作方式与此类似。

ProTip:shlex.split可以帮助您解析,和其他功能的命令run,以防您不想(或您不能!)以列表形式提供它们:callsubprocess

import shlex
import subprocess
subprocess.run(shlex.split('ls -l'))

具有外部依赖性

如果您不介意外部依赖性,请使用plumbum

from plumbum.cmd import ifconfig
print(ifconfig['wlan0']())

这是最好的subprocess包装纸。它是跨平台的,即可以在Windows和类似Unix的系统上运行。由安装pip install plumbum

另一个受欢迎的图书馆是sh

from sh import ifconfig
print(ifconfig('wlan0'))

但是,已sh放弃Windows支持,因此它不像以前那样出色。由安装pip install sh

With the standard library

Use the subprocess module (Python 3):

import subprocess
subprocess.run(['ls', '-l'])

It is the recommended standard way. However, more complicated tasks (pipes, output, input, etc.) can be tedious to construct and write.

Note on Python version: If you are still using Python 2, subprocess.call works in a similar way.

ProTip: shlex.split can help you to parse the command for run, call, and other subprocess functions in case you don’t want (or you can’t!) provide them in form of lists:

import shlex
import subprocess
subprocess.run(shlex.split('ls -l'))

With external dependencies

If you do not mind external dependencies, use plumbum:

from plumbum.cmd import ifconfig
print(ifconfig['wlan0']())

It is the best subprocess wrapper. It’s cross-platform, i.e. it works on both Windows and Unix-like systems. Install by pip install plumbum.

Another popular library is sh:

from sh import ifconfig
print(ifconfig('wlan0'))

However, sh dropped Windows support, so it’s not as awesome as it used to be. Install by pip install sh.


回答 11

如果您需要从您所呼叫的命令的输出,那么你可以使用subprocess.check_output(Python的2.7+)。

>>> subprocess.check_output(["ls", "-l", "/dev/null"])
'crw-rw-rw- 1 root root 1, 3 Oct 18  2007 /dev/null\n'

还要注意shell参数。

如果shell是True,则将通过Shell执行指定的命令。如果您主要将Python用于大多数系统外壳程序提供的增强控制流,并且仍希望方便地访问其他外壳程序功能(例如外壳程序管道,文件名通配符,环境变量扩展以及〜扩展到用户的家),则这可能很有用。目录。但是请注意,Python本身提供的实现多壳状的功能(尤其是globfnmatchos.walk()os.path.expandvars()os.path.expanduser(),和shutil)。

If you need the output from the command you are calling, then you can use subprocess.check_output (Python 2.7+).

>>> subprocess.check_output(["ls", "-l", "/dev/null"])
'crw-rw-rw- 1 root root 1, 3 Oct 18  2007 /dev/null\n'

Also note the shell parameter.

If shell is True, the specified command will be executed through the shell. This can be useful if you are using Python primarily for the enhanced control flow it offers over most system shells and still want convenient access to other shell features such as shell pipes, filename wildcards, environment variable expansion, and expansion of ~ to a user’s home directory. However, note that Python itself offers implementations of many shell-like features (in particular, glob, fnmatch, os.walk(), os.path.expandvars(), os.path.expanduser(), and shutil).


回答 12

这就是我运行命令的方式。这段代码包含了您非常需要的所有内容

from subprocess import Popen, PIPE
cmd = "ls -l ~/"
p = Popen(cmd , shell=True, stdout=PIPE, stderr=PIPE)
out, err = p.communicate()
print "Return code: ", p.returncode
print out.rstrip(), err.rstrip()

This is how I run my commands. This code has everything you need pretty much

from subprocess import Popen, PIPE
cmd = "ls -l ~/"
p = Popen(cmd , shell=True, stdout=PIPE, stderr=PIPE)
out, err = p.communicate()
print "Return code: ", p.returncode
print out.rstrip(), err.rstrip()

回答 13

更新:

subprocess.run如果您的代码不需要保持与早期Python版本的兼容性,则从python 3.5开始,建议使用此方法。它更加一致,并且提供与Envoy类似的易用性。(管道并不是那么简单。有关如何查看此问题的信息。)

以下是文档中的一些示例。

运行一个过程:

>>> subprocess.run(["ls", "-l"])  # Doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

在失败的跑步上加薪:

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

捕获输出:

>>> subprocess.run(["ls", "-l", "/dev/null"], stdout=subprocess.PIPE)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n')

原始答案:

我建议尝试Envoy。它是子流程的包装,后者旨在替换较旧的模块和功能。特使是人类的子过程。

自述文件中的示例用法:

>>> r = envoy.run('git config', data='data to pipe in', timeout=2)

>>> r.status_code
129
>>> r.std_out
'usage: git config [options]'
>>> r.std_err
''

管道周围的东西:

>>> r = envoy.run('uptime | pbcopy')

>>> r.command
'pbcopy'
>>> r.status_code
0

>>> r.history
[<Response 'uptime'>]

Update:

subprocess.run is the recommended approach as of Python 3.5 if your code does not need to maintain compatibility with earlier Python versions. It’s more consistent and offers similar ease-of-use as Envoy. (Piping isn’t as straightforward though. See this question for how.)

Here’s some examples from the documentation.

Run a process:

>>> subprocess.run(["ls", "-l"])  # Doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

Raise on failed run:

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

Capture output:

>>> subprocess.run(["ls", "-l", "/dev/null"], stdout=subprocess.PIPE)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n')

Original answer:

I recommend trying Envoy. It’s a wrapper for subprocess, which in turn aims to replace the older modules and functions. Envoy is subprocess for humans.

Example usage from the README:

>>> r = envoy.run('git config', data='data to pipe in', timeout=2)

>>> r.status_code
129
>>> r.std_out
'usage: git config [options]'
>>> r.std_err
''

Pipe stuff around too:

>>> r = envoy.run('uptime | pbcopy')

>>> r.command
'pbcopy'
>>> r.status_code
0

>>> r.history
[<Response 'uptime'>]

回答 14

使用子过程

…或一个非常简单的命令:

import os
os.system('cat testfile')

Use subprocess.

…or for a very simple command:

import os
os.system('cat testfile')

回答 15

在Python中调用外部命令

简单,使用subprocess.run,它返回一个CompletedProcess对象:

>>> import subprocess
>>> completed_process = subprocess.run('python --version')
Python 3.6.1 :: Anaconda 4.4.0 (64-bit)
>>> completed_process
CompletedProcess(args='python --version', returncode=0)

为什么?

从Python 3.5开始,文档建议使用subprocess.run

推荐的调用子流程的方法是将run()函数用于它可以处理的所有用例。对于更高级的用例,可以直接使用基础Popen接口。

这是最简单的用法示例-完全按照要求进行:

>>> import subprocess
>>> completed_process = subprocess.run('python --version')
Python 3.6.1 :: Anaconda 4.4.0 (64-bit)
>>> completed_process
CompletedProcess(args='python --version', returncode=0)

run等待命令成功完成,然后返回一个CompletedProcess对象。相反,它可以引发TimeoutExpired(如果您给它提供一个timeout=参数)或CalledProcessError(如果失败并通过check=True)。

从上面的示例可以推断,默认情况下,stdout和stderr都通过管道传递到您自己的stdout和stderr。

我们可以检查返回的对象,并查看给出的命令和返回码:

>>> completed_process.args
'python --version'
>>> completed_process.returncode
0

捕获输出

如果要捕获输出,则可以传递subprocess.PIPE给相应的stderrstdout

>>> cp = subprocess.run('python --version', 
                        stderr=subprocess.PIPE, 
                        stdout=subprocess.PIPE)
>>> cp.stderr
b'Python 3.6.1 :: Anaconda 4.4.0 (64-bit)\r\n'
>>> cp.stdout
b''

(我发现将版本信息放入stderr而不是stdout很有意思,并且有点违反直觉。)

传递命令清单

可以很容易地从手动提供命令字符串(如问题所提示)转变为以编程方式构建的字符串。不要以编程方式构建字符串。这是一个潜在的安全问题。最好假设您不信任输入。

>>> import textwrap
>>> args = ['python', textwrap.__file__]
>>> cp = subprocess.run(args, stdout=subprocess.PIPE)
>>> cp.stdout
b'Hello there.\r\n  This is indented.\r\n'

注意,仅args应按位置传递。

完整签名

这是源中的实际签名,如下所示help(run)

def run(*popenargs, input=None, timeout=None, check=False, **kwargs):

popenargskwargs被给予Popen的构造。input可以是universal_newlines=True将通过管道传输到子进程的stdin 的字节字符串(或unicode,如果指定encoding或)。

该文档描述了timeout=check=True比我更可以:

超时参数传递给Popen.communicate()。如果超时到期,子进程将被终止并等待。子进程终止后,将重新引发TimeoutExpired异常。

如果check为true,并且进程以非零退出代码退出,则将引发CalledProcessError异常。该异常的属性包含参数,退出代码以及stdout和stderr(如果已捕获)。

这个示例check=True比我能想到的更好:

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

扩展签名

这是文档中提供的扩展签名:

subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, 
shell=False, cwd=None, timeout=None, check=False, encoding=None, 
errors=None)

请注意,这表明只应在位置传递args列表。因此,将其余参数作为关键字参数传递。

开普

何时使用Popen代替?我将很难仅根据参数来找到用例。Popen但是,直接使用pollwill 将使您能够访问其方法,包括,“ send_signal”,“ terminate”和“ wait”。

这是来源中Popen给出的签名。我认为这是信息的最精确封装(与相对):help(Popen)

def __init__(self, args, bufsize=-1, executable=None,
             stdin=None, stdout=None, stderr=None,
             preexec_fn=None, close_fds=_PLATFORM_DEFAULT_CLOSE_FDS,
             shell=False, cwd=None, env=None, universal_newlines=False,
             startupinfo=None, creationflags=0,
             restore_signals=True, start_new_session=False,
             pass_fds=(), *, encoding=None, errors=None):

但更多的是信息Popen文档

subprocess.Popen(args, bufsize=-1, executable=None, stdin=None,
                 stdout=None, stderr=None, preexec_fn=None, close_fds=True,
                 shell=False, cwd=None, env=None, universal_newlines=False,
                 startupinfo=None, creationflags=0, restore_signals=True,
                 start_new_session=False, pass_fds=(), *, encoding=None, errors=None)

在新进程中执行子程序。在POSIX上,该类使用类似于os.execvp()的行为来执行子程序。在Windows上,该类使用Windows CreateProcess()函数。Popen的参数如下。

剩下的内容Popen将作为读者的练习。

Calling an external command in Python

Simple, use subprocess.run, which returns a CompletedProcess object:

>>> import subprocess
>>> completed_process = subprocess.run('python --version')
Python 3.6.1 :: Anaconda 4.4.0 (64-bit)
>>> completed_process
CompletedProcess(args='python --version', returncode=0)

Why?

As of Python 3.5, the documentation recommends subprocess.run:

The recommended approach to invoking subprocesses is to use the run() function for all use cases it can handle. For more advanced use cases, the underlying Popen interface can be used directly.

Here’s an example of the simplest possible usage – and it does exactly as asked:

>>> import subprocess
>>> completed_process = subprocess.run('python --version')
Python 3.6.1 :: Anaconda 4.4.0 (64-bit)
>>> completed_process
CompletedProcess(args='python --version', returncode=0)

run waits for the command to successfully finish, then returns a CompletedProcess object. It may instead raise TimeoutExpired (if you give it a timeout= argument) or CalledProcessError (if it fails and you pass check=True).

As you might infer from the above example, stdout and stderr both get piped to your own stdout and stderr by default.

We can inspect the returned object and see the command that was given and the returncode:

>>> completed_process.args
'python --version'
>>> completed_process.returncode
0

Capturing output

If you want to capture the output, you can pass subprocess.PIPE to the appropriate stderr or stdout:

>>> cp = subprocess.run('python --version', 
                        stderr=subprocess.PIPE, 
                        stdout=subprocess.PIPE)
>>> cp.stderr
b'Python 3.6.1 :: Anaconda 4.4.0 (64-bit)\r\n'
>>> cp.stdout
b''

(I find it interesting and slightly counterintuitive that the version info gets put to stderr instead of stdout.)

Pass a command list

One might easily move from manually providing a command string (like the question suggests) to providing a string built programmatically. Don’t build strings programmatically. This is a potential security issue. It’s better to assume you don’t trust the input.

>>> import textwrap
>>> args = ['python', textwrap.__file__]
>>> cp = subprocess.run(args, stdout=subprocess.PIPE)
>>> cp.stdout
b'Hello there.\r\n  This is indented.\r\n'

Note, only args should be passed positionally.

Full Signature

Here’s the actual signature in the source and as shown by help(run):

def run(*popenargs, input=None, timeout=None, check=False, **kwargs):

The popenargs and kwargs are given to the Popen constructor. input can be a string of bytes (or unicode, if specify encoding or universal_newlines=True) that will be piped to the subprocess’s stdin.

The documentation describes timeout= and check=True better than I could:

The timeout argument is passed to Popen.communicate(). If the timeout expires, the child process will be killed and waited for. The TimeoutExpired exception will be re-raised after the child process has terminated.

If check is true, and the process exits with a non-zero exit code, a CalledProcessError exception will be raised. Attributes of that exception hold the arguments, the exit code, and stdout and stderr if they were captured.

and this example for check=True is better than one I could come up with:

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

Expanded Signature

Here’s an expanded signature, as given in the documentation:

subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, 
shell=False, cwd=None, timeout=None, check=False, encoding=None, 
errors=None)

Note that this indicates that only the args list should be passed positionally. So pass the remaining arguments as keyword arguments.

Popen

When use Popen instead? I would struggle to find use-case based on the arguments alone. Direct usage of Popen would, however, give you access to its methods, including poll, ‘send_signal’, ‘terminate’, and ‘wait’.

Here’s the Popen signature as given in the source. I think this is the most precise encapsulation of the information (as opposed to help(Popen)):

def __init__(self, args, bufsize=-1, executable=None,
             stdin=None, stdout=None, stderr=None,
             preexec_fn=None, close_fds=_PLATFORM_DEFAULT_CLOSE_FDS,
             shell=False, cwd=None, env=None, universal_newlines=False,
             startupinfo=None, creationflags=0,
             restore_signals=True, start_new_session=False,
             pass_fds=(), *, encoding=None, errors=None):

But more informative is the Popen documentation:

subprocess.Popen(args, bufsize=-1, executable=None, stdin=None,
                 stdout=None, stderr=None, preexec_fn=None, close_fds=True,
                 shell=False, cwd=None, env=None, universal_newlines=False,
                 startupinfo=None, creationflags=0, restore_signals=True,
                 start_new_session=False, pass_fds=(), *, encoding=None, errors=None)

Execute a child program in a new process. On POSIX, the class uses os.execvp()-like behavior to execute the child program. On Windows, the class uses the Windows CreateProcess() function. The arguments to Popen are as follows.

Understanding the remaining documentation on Popen will be left as an exercise for the reader.


回答 16

os.system可以,但是有点过时。这也不是很安全。相反,请尝试subprocesssubprocess不会直接调用sh,因此比os.system

在此处获取更多信息。

os.system is OK, but kind of dated. It’s also not very secure. Instead, try subprocess. subprocess does not call sh directly and is therefore more secure than os.system.

Get more information here.


回答 17

还有

>>> from plumbum import local
>>> ls = local["ls"]
>>> ls
LocalCommand(<LocalPath /bin/ls>)
>>> ls()
u'build.py\ndist\ndocs\nLICENSE\nplumbum\nREADME.rst\nsetup.py\ntests\ntodo.txt\n'
>>> notepad = local["c:\\windows\\notepad.exe"]
>>> notepad()                                   # Notepad window pops up
u''                                             # Notepad window is closed by user, command returns

There is also Plumbum

>>> from plumbum import local
>>> ls = local["ls"]
>>> ls
LocalCommand(<LocalPath /bin/ls>)
>>> ls()
u'build.py\ndist\ndocs\nLICENSE\nplumbum\nREADME.rst\nsetup.py\ntests\ntodo.txt\n'
>>> notepad = local["c:\\windows\\notepad.exe"]
>>> notepad()                                   # Notepad window pops up
u''                                             # Notepad window is closed by user, command returns

回答 18

采用:

import os

cmd = 'ls -al'

os.system(cmd)

os-此模块提供了使用依赖于操作系统的功能的可移植方式。

对于更多的os功能,这里是文档。

Use:

import os

cmd = 'ls -al'

os.system(cmd)

os – This module provides a portable way of using operating system-dependent functionality.

For the more os functions, here is the documentation.


回答 19

可能很简单:

import os
cmd = "your command"
os.system(cmd)

It can be this simple:

import os
cmd = "your command"
os.system(cmd)

回答 20

我非常喜欢shell_command的简单性。它建立在子流程模块的顶部。

这是文档中的示例:

>>> from shell_command import shell_call
>>> shell_call("ls *.py")
setup.py  shell_command.py  test_shell_command.py
0
>>> shell_call("ls -l *.py")
-rw-r--r-- 1 ncoghlan ncoghlan  391 2011-12-11 12:07 setup.py
-rw-r--r-- 1 ncoghlan ncoghlan 7855 2011-12-11 16:16 shell_command.py
-rwxr-xr-x 1 ncoghlan ncoghlan 8463 2011-12-11 16:17 test_shell_command.py
0

I quite like shell_command for its simplicity. It’s built on top of the subprocess module.

Here’s an example from the documentation:

>>> from shell_command import shell_call
>>> shell_call("ls *.py")
setup.py  shell_command.py  test_shell_command.py
0
>>> shell_call("ls -l *.py")
-rw-r--r-- 1 ncoghlan ncoghlan  391 2011-12-11 12:07 setup.py
-rw-r--r-- 1 ncoghlan ncoghlan 7855 2011-12-11 16:16 shell_command.py
-rwxr-xr-x 1 ncoghlan ncoghlan 8463 2011-12-11 16:17 test_shell_command.py
0

回答 21

这里还有另一个以前没有提到的区别。

subprocess.Popen将<command>作为子进程执行。就我而言,我需要执行文件<a>,该文件需要与另一个程序<b>通信。

我尝试了子流程,执行成功。但是<b>无法与<a>通信。当我从终端运行时,一切都正常。

还有一个:(注意:kwrite的行为与其他应用程序不同。如果在Firefox上尝试以下操作,结果将有所不同。)

如果尝试这样做os.system("kwrite"),程序流将冻结,直到用户关闭kwrite。为了克服这个问题,我改为尝试os.system(konsole -e kwrite)。这个时间程序继续进行,但是kwrite成为了控制台的子进程。

任何人都运行kwrite而不是子进程(即,它必须在系统监视器中显示在树的最左侧)。

There is another difference here which is not mentioned previously.

subprocess.Popen executes the <command> as a subprocess. In my case, I need to execute file <a> which needs to communicate with another program, <b>.

I tried subprocess, and execution was successful. However <b> could not communicate with <a>. Everything is normal when I run both from the terminal.

One more: (NOTE: kwrite behaves different from other applications. If you try the below with Firefox, the results will not be the same.)

If you try os.system("kwrite"), program flow freezes until the user closes kwrite. To overcome that I tried instead os.system(konsole -e kwrite). This time program continued to flow, but kwrite became the subprocess of the console.

Anyone runs the kwrite not being a subprocess (i.e. in the system monitor it must appear at the leftmost edge of the tree).


回答 22

os.system不允许您存储结果,因此,如果要将结果存储在某个列表或其他内容中,则subprocess.call可以使用。

os.system does not allow you to store results, so if you want to store results in some list or something, a subprocess.call works.


回答 23

subprocess.check_call如果您不想测试返回值,则非常方便。任何错误都会引发异常。

subprocess.check_call is convenient if you don’t want to test return values. It throws an exception on any error.


回答 24

我倾向于将进程shlex一起使用(以处理带引号的字符串的转义):

>>> import subprocess, shlex
>>> command = 'ls -l "/your/path/with spaces/"'
>>> call_params = shlex.split(command)
>>> print call_params
["ls", "-l", "/your/path/with spaces/"]
>>> subprocess.call(call_params)

I tend to use subprocess together with shlex (to handle escaping of quoted strings):

>>> import subprocess, shlex
>>> command = 'ls -l "/your/path/with spaces/"'
>>> call_params = shlex.split(command)
>>> print call_params
["ls", "-l", "/your/path/with spaces/"]
>>> subprocess.call(call_params)

回答 25

无耻的插件,我为此写了一个库:P https://github.com/houqp/shell.py

目前,它基本上是popen和shlex的包装。它还支持管道命令,因此您可以在Python中更轻松地链接命令。因此,您可以执行以下操作:

ex('echo hello shell.py') | "awk '{print $2}'"

Shameless plug, I wrote a library for this :P https://github.com/houqp/shell.py

It’s basically a wrapper for popen and shlex for now. It also supports piping commands so you can chain commands easier in Python. So you can do things like:

ex('echo hello shell.py') | "awk '{print $2}'"

回答 26

在Windows中你可以导入subprocess模块,并通过调用运行外部命令subprocess.Popen()subprocess.Popen().communicate()subprocess.Popen().wait()如下:

# Python script to run a command line
import subprocess

def execute(cmd):
    """
        Purpose  : To execute a command and return exit status
        Argument : cmd - command to execute
        Return   : exit_code
    """
    process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    (result, error) = process.communicate()

    rc = process.wait()

    if rc != 0:
        print "Error: failed to execute command:", cmd
        print error
    return result
# def

command = "tasklist | grep python"
print "This process detail: \n", execute(command)

输出:

This process detail:
python.exe                     604 RDP-Tcp#0                  4      5,660 K

In Windows you can just import the subprocess module and run external commands by calling subprocess.Popen(), subprocess.Popen().communicate() and subprocess.Popen().wait() as below:

# Python script to run a command line
import subprocess

def execute(cmd):
    """
        Purpose  : To execute a command and return exit status
        Argument : cmd - command to execute
        Return   : exit_code
    """
    process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    (result, error) = process.communicate()

    rc = process.wait()

    if rc != 0:
        print "Error: failed to execute command:", cmd
        print error
    return result
# def

command = "tasklist | grep python"
print "This process detail: \n", execute(command)

Output:

This process detail:
python.exe                     604 RDP-Tcp#0                  4      5,660 K

回答 27

在Linux下,如果您想调用将独立执行的外部命令(在python脚本终止后将继续运行),则可以使用简单的队列作为任务假脱机程序at命令

任务假脱机程序的示例:

import os
os.system('ts <your-command>')

有关任务后台处理程序(ts)的注意事项:

  1. 您可以使用以下命令设置要运行的并发进程数(“插槽”):

    ts -S <number-of-slots>

  2. 安装ts不需要管理员权限。您可以使用简单的源代码下载并编译它make,然后将其添加到路径中,即可完成操作。

Under Linux, in case you would like to call an external command that will execute independently (will keep running after the python script terminates), you can use a simple queue as task spooler or the at command

An example with task spooler:

import os
os.system('ts <your-command>')

Notes about task spooler (ts):

  1. You could set the number of concurrent processes to be run (“slots”) with:

    ts -S <number-of-slots>

  2. Installing ts doesn’t requires admin privileges. You can download and compile it from source with a simple make, add it to your path and you’re done.


回答 28

您可以使用Popen,然后可以检查过程的状态:

from subprocess import Popen

proc = Popen(['ls', '-l'])
if proc.poll() is None:
    proc.kill()

签出subprocess.Popen

You can use Popen, and then you can check the procedure’s status:

from subprocess import Popen

proc = Popen(['ls', '-l'])
if proc.poll() is None:
    proc.kill()

Check out subprocess.Popen.


回答 29

要从OpenStack Neutron获取网络ID :

#!/usr/bin/python
import os
netid = "nova net-list | awk '/ External / { print $2 }'"
temp = os.popen(netid).read()  /* Here temp also contains new line (\n) */
networkId = temp.rstrip()
print(networkId)

nova net-list的输出

+--------------------------------------+------------+------+
| ID                                   | Label      | CIDR |
+--------------------------------------+------------+------+
| 431c9014-5b5d-4b51-a357-66020ffbb123 | test1      | None |
| 27a74fcd-37c0-4789-9414-9531b7e3f126 | External   | None |
| 5a2712e9-70dc-4b0e-9281-17e02f4684c9 | management | None |
| 7aa697f5-0e60-4c15-b4cc-9cb659698512 | Internal   | None |
+--------------------------------------+------------+------+

打印输出(networkId)

27a74fcd-37c0-4789-9414-9531b7e3f126

To fetch the network id from the OpenStack Neutron:

#!/usr/bin/python
import os
netid = "nova net-list | awk '/ External / { print $2 }'"
temp = os.popen(netid).read()  /* Here temp also contains new line (\n) */
networkId = temp.rstrip()
print(networkId)

Output of nova net-list

+--------------------------------------+------------+------+
| ID                                   | Label      | CIDR |
+--------------------------------------+------------+------+
| 431c9014-5b5d-4b51-a357-66020ffbb123 | test1      | None |
| 27a74fcd-37c0-4789-9414-9531b7e3f126 | External   | None |
| 5a2712e9-70dc-4b0e-9281-17e02f4684c9 | management | None |
| 7aa697f5-0e60-4c15-b4cc-9cb659698512 | Internal   | None |
+--------------------------------------+------------+------+

Output of print(networkId)

27a74fcd-37c0-4789-9414-9531b7e3f126

Gdb-dashboard-Python中GDB的模块化可视化界面

GDB仪表板

GDB仪表板是独立的.gdbinit属性编写的文件。Python API这使得模块化界面能够显示关于正在调试的程序的相关信息。它的主要目标是减少检查当前程序状态所需的GDB命令的数量,从而允许开发人员主要关注控制流

快速入门

只要放好位置就行了.gdbinit在您的主目录中,例如使用:

wget -P ~ https://git.io/.gdbinit

可选安装Pygments要启用语法突出显示,请执行以下操作:

pip install pygments

然后照常调试,每次下级程序停止时仪表板都会自动出现

请记住,尚未重新定义任何gdb命令,相反,所有功能都可以通过Maindashboard命令(请参见help dashboard)

前往wiki学习如何执行最重要的任务

Google-images-download 从“Google Images”下载数百张图片的Python脚本。这是一个随时可以运行的代码!

Google图片下载

Python脚本,用于“搜索”和“下载”数百张谷歌图片到本地硬盘!

文档

免责声明

这个程序可以让你从谷歌下载大量图片。请不要下载或使用任何违反其版权条款的图片。Google Images是一个搜索引擎,它只对图像进行索引,并允许您找到它们。它不生产自己的图像,因此,它没有任何图像的版权。图像的原始创作者拥有版权

在美国发布的图像自动受其所有者的版权保护,即使它们没有明确带有版权警告。除非在“合理使用”的情况下,否则您不得在未经版权所有者许可的情况下复制版权图像,否则您可能会面临遇到律师警告、停止和停止函以及版权诉讼的风险。请在使用前非常小心!此脚本/代码仅用于教育目的