Python:将一个文本数组附加到另​​一个文本数组会添加一个 "u"?

Python: Appending one text array to another adds a "u"?

对于真正知道如何使用 Python 的人来说,这应该是一个非常容易回答的问题(显然那不是我)。我正在使用 Python 2.7.9,我从这个网站找到了一些示例代码:

http://pythonicprose.blogspot.com/2010/04/python-tkinter-frontend-example-to-ping.html

但是当我 运行 模块时,回复文本不是 ping 时间,它是:

Ping 请求找不到主机 www.google.com。请检查名称并重试。

所以我添加了一些打印语句,发现应该传递给命令行的字符串正在添加一个 "u",如下所示:

www.google.com

['ping', '-n', '1']
['ping', '-n', '1', u'www.google.com\n']

那么你是如何介于“1”和 'www.google.com\n' 之间的,又如何摆脱它呢?我认为它是某种转义字符,但我不知道它被添加到哪里。

from Tkinter import *
from subprocess import PIPE, Popen

class App:
    def __init__(self, master):
        frame = Frame(master)
        frame.grid()

        # create and position widgets

        self.label = Label(frame, text="Enter IP Address or Server Name:")
        self.label.grid(row=0, column=0, sticky=W)

        self.textbox = Text(frame, height=1, width=40)
        self.textbox.grid(row=1, column=0, columnspan=2, sticky=W)
        self.textbox.insert(END, "www.google.com")

        self.resultsBox = Text(frame, height=10, width=60)
        self.resultsBox.grid(row=3, column=0, columnspan=3, sticky=W)

        self.hi_there = Button(frame, text="Ping",
                               width=10, command=self.doPing)
        self.hi_there.grid(row=1, column=2, sticky=W)

    def doPing(self):
        # reset result box
        self.resultsBox.delete(1.0, END)
        # get text

        texttext = self.textbox.get(1.0, END)
        exelist = ['ping', '-n', '1']
        exelist.append(texttext)
        # Execute command (these ping commands are windows specific).
        # In Linux you would use the '-c' to specify count.

        exe = Popen(exelist, shell=False, stdout=PIPE, stderr=PIPE)
        out, err = exe.communicate()
        while out:
            self.resultsBox.insert(END, out)
            out, err = exe.communicate()

root = Tk()
app = App(root)
root.mainloop()

根据您的处理方式,最后一个字符串似乎是一个 unicode 字符串。如果你想让每个人都成为 ASCII 字符串,你可以在所有 class 成员上使用 str:

In [1]: a = u'i am unicode'

In [2]: b = 'i am ascii\n'

In [3]: x = [a, b]

In [4]: print x
[u'i am unicode', 'i am ascii\n']

In [5]: print [ str (s) for s in x ]
['i am unicode', 'i am ascii\n']

"u"只是表示字符串"www.google.com\n"是Unicode字符串,对你的程序应该没有任何影响。

问题更有可能是您尝试 ping "www.google.com\n" 而不是 "www.google.com"(注意那里有一个新行)。

尝试在尝试 ping 之前从您的输入中去除空格。即:exelist.append(texttext) 变为 exelist.append(texttext.strip()).