Python2.7单行打印列表不工作

2024-06-01 07:46:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经尝试了这个page和其他一些谷歌搜索的一切,但我似乎无法让它工作。
注*我查阅了有关打印的帮助来测试outfile.write文件,但在测试中仍然无法正确格式化
我的代码看起来像:

def ipfile():
    global ip_targets
    ip_target_file = raw_input('Place target file location here: ')
    try: ip_holder = open(ip_target_file,'r')
    except IOError:
        os.system('clear')
        print('Either I can\'t read that file, or it\'s not a file')
        os.system('sleep 3')
        return
    ip_targets = ip_holder.readlines()

def inbound_connections():   
    i = 0
    uri_ip_src = ''
    uri_ip_dst = ''
    while i < (len(ip_targets)):
        uri_ip_src_repeater = ('ip.src%3D%3D' + ip_targets[i])
        uri_ip_src = uri_ip_src + '||' + uri_ip_src_repeater
        uri_ip_dst_repeater = ('ip.dst%3D%3D' + ip_targets[i])
        uri_ip_dst = uri_ip_dst + '||' + uri_ip_dst_repeater
        i += 1          
    url = '&expression=' + "(" + (uri_ip_src[2:]) + ")" + "%26(" + (uri_ip_dst[2:]) + ")"
    #Write output to file functions
    outfile=open("jacobi_queries.txt","a")
    outfile.write("Same -> Same Connections " + str(datetime.datetime.now())[:16])
    outfile.write("\n")
    outfile.write(call_moloch + "/sessions?" + timestamp + url + "' 2>/dev/null &")
    outfile.write("\n")
    outfile.close()

代码可以工作(抱歉,我遗漏了一些来自其他函数的变量,但是假设它们可以工作)但是,我的输出有换行符,我似乎找不到我需要在哪里转换“uri\u ip\u src”和“uri\u ip\dst”使其在一行上输出。我的输出如下所示:

Same -> Same Connections 2018-06-05 05:30
nohup firefox 'localhost:8005/sessions?&date=6&expression=(ip.src%3D%3D10.0.2.15
||ip.src%3D%3D10.0.0.1
||ip.src%3D%3D127.0.0.1
)%26(ip.dst%3D%3D10.0.2.15
||ip.dst%3D%3D10.0.0.1
||ip.dst%3D%3D127.0.0.1
)' 2>/dev/null &

有什么想法吗?你知道吗


Tags: 代码ipsrctargetdefuriopenoutfile
1条回答
网友
1楼 · 发布于 2024-06-01 07:46:21

你的问题是:

ip_targets = ip_holder.readlines()

每行末尾都有换行符。在将此字符添加到uri_ip_src_repeater之前,您希望从每个元素的末尾删除此字符。这应该起作用:

ip_targets = [i.rstrip('\n') for i in ip_targets]

但您也可以从源代码中清晰地获取它们,而不必在以下情况之后删除不需要的字符:

ip_targets = ip_holder.read().splitlines() 

相关问题 更多 >