Python:将元组转换为字符串

cit*_*cit 0 python string tuples

鉴于这种 :

import os
import subprocess

def check_server():

    cl = subprocess.Popen(["nmap","10.7.1.71"], stdout=subprocess.PIPE)
    result = cl.communicate()
    print result

check_server()
Run Code Online (Sandbox Code Playgroud)

check_server()返回此元组:

('\nStarting Nmap 4.53 ( http://insecure.org ) at 2010-04-07 07:26 EDT\nInteresting ports on 10.7.1.71:\nNot shown: 1711 closed ports\nPORT   STATE SERVICE\n21/tcp open  ftp\n22/tcp open  ssh\n80/tcp open  http\n\nNmap done: 1 IP address (1 host up) scanned in 0.293 seconds\n', None)
Run Code Online (Sandbox Code Playgroud)

将方法中的第二行更改为

result, err = cl.communicate()
Run Code Online (Sandbox Code Playgroud)

结果check_server()返回:

Starting Nmap 4.53 ( http://insecure.org ) at 2010-04-07 07:27 EDT
Interesting ports on 10.7.1.71:
Not shown: 1711 closed ports
PORT   STATE SERVICE
21/tcp open  ftp
22/tcp open  ssh
80/tcp open  http

Nmap done: 1 IP address (1 host up) scanned in 0.319 seconds
Run Code Online (Sandbox Code Playgroud)

看起来是元组被转换为字符串的情况,并且\n被剥离....但是怎么样?

Mar*_*tos 6

cl.communicate()还在回归一个元组.赋值result, err = ...具有将元组解包为变量result(字符串)和err(整数)的效果.

当你打印元组时,它使用repr(...)每个元素,但是当你打印字符串时,它只打印字符串,因此没有分隔符和\ns.