【问题标题】:Run multiple threads simultaneously but print one by one python?同时运行多个线程但一一打印python?
【发布时间】:2019-01-19 07:55:15
【问题描述】:

你可能知道我在说什么。所以让我更清楚地解释一下。

例如:- 我有四个线程,它们运行着类似的东西。

th1 = threading.Thread(target=connCheck,  args= (newurl, schemess, 21))
th2 = threading.Thread(target=connCheck,  args=( newurl, schemess, 22))
th3 = threading.Thread(target=connCheck,  args= (newurl, schemess,80))
th4 = threading.Thread(target=connCheck,  args=(newurl, schemess,8080))

(这是扫描端口号为21、22、80、8080的端口的扫描器。)

我像这样运行这些线程:-

th1.start()
th2.start()
th3.start()
th4.start()
th4.join()

注意:- connCheck 是一个函数来判断哪些端口是打开的。

所以在我的终端中,它显示两个端口都以非常糟糕的方式打开但是。有时会这样打印

List of port open:-

[+]21 [+]22 [+]80
[+]8080

有时它会这样打印:-

List of port open:-

[+]21 
[+]22 [+]80
[+]8080

有时它会以其他方式打印。

所以我希望他们以像 Line wise 这样的单一良好方式打印什么。但最重要的是要记住我想同时运行上述所有线程,这样就不会影响扫描速度。

所以我来这里问你。所以请任何人在这里指导我。

谢谢

[编辑]:- 这里是 conncheck 函数:-

try: 

        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(3)

        result = sock.connect_ex((ip, port))

        newip = schemess+ip+slash

        if port == 21:
            if result == 0:

                print "\t [+]" + str(port)
                ftpurls.append(newip)
                dicta(newip, port)


        else:
            if result == 0:


                    print '\t' + str(port)+ '\n'

                    dicta(newip, port)                      


        sock.close()
    except Exception as e:
        print str(e) + '\n'

请忽略dicta函数。

【问题讨论】:

  • 你能发布你的 connCheck 函数吗?
  • 使用队列。让唯一的一个线程(主线程)打印队列中的项目。
  • 检查this answer - 这是multiprocessing 更复杂的情况,但第一个示例(处理输出的主进程/线程)在多线程场景中也可以很好地工作。由于多线程支持共享内存,因此您可以通过共享一些结构而不是返回和收集结果来实现比这更简单的操作。
  • 你可以像这样使用ThreadPoolExecutorwith ThreadPoolExecutor() as t: for data in t.map(connCheck, repeat(newurl), repeat(newurl), list_port,): ...

标签: python multithreading python-multithreading


【解决方案1】:

有几种方法可以做到这一点,使用锁,另一种是使用logging 模块。我一直在使用threading.Lock() 编写多线程代码,但我最近发现logging 更容易使用。

lock = threading.Lock()
with lock:
     print("...")

with lock 在进入时会调用lock.acquire(),在退出时会调用lock.release()。或者您可以手动调用它们。但是请确保在您获得后release它,否则您将面临僵局。

另一种更简单的方法是使用我提到的logginglogging 库是线程安全的,这意味着任何线程都可以同时使用这些函数。使用此模块还允许您将日志写入日志文件。

import logging

logging.basicConfig(format='%(message)s')
logging.info("...")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-09
    • 2021-12-16
    • 1970-01-01
    • 2011-08-01
    • 2018-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多