如何将结果导出到.txt

问题描述 投票:0回答:1

我运行了以下代码,我希望将脚本的输出导出到.txt文件以供以后查看。我怎么能这样做?

import socket, threading


def TCP_connect(ip, port_number, delay, output):
    TCPsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    TCPsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    TCPsock.settimeout(delay)
try:
    TCPsock.connect((ip, port_number))
    output[port_number] = 'Listening'
except:
    output[port_number] = ''



def scan_ports(host_ip, delay):

    threads = []        # To run TCP_connect concurrently
    output = {}         # For printing purposes

# Spawning threads to scan ports
for i in range(10000):
    t = threading.Thread(target=TCP_connect, args=(host_ip, i, delay, output))
    threads.append(t)

# Starting threads
for i in range(10000):
    threads[i].start()

# Locking the script until all threads complete
for i in range(10000):
    threads[i].join()

# Printing listening ports from small to large
for i in range(10000):
    if output[i] == 'Listening':
        print(str(i) + ': ' + output[i])



def main():
host_ip = input("Enter host IP: ")
delay = int(input("How many seconds the socket is going to wait until timeout: "))
scan_ports(host_ip, delay)

if __name__ == "__main__":
    main()

print ("Thank you for scanning")

任何帮助将不胜感激。

python python-3.x export
1个回答
0
投票
with open("your_desired_txt_filename", "a") as myFile:

然后,在要写入文件的部分:

myFile.write(your_content) ## Indent this line with the suitable level of indentation (it will be at least one indentation level  deeper than the `with` clause
© www.soinside.com 2019 - 2024. All rights reserved.