简体   繁体   English

使用 if __name__ == '__main__' 时代码不运行

[英]code doesnt run when using if __name__ == '__main__'

When running any code in sublime, pycharm or spyder I always get this message and the code stops.在 sublime、pycharm 或 spyder 中运行任何代码时,我总是收到此消息并且代码停止。 Code I'm currently using: https://imgur.com/a/fNaUPu2我目前正在使用的代码: https://imgur.com/a/fNaUPu2

RuntimeError: An attempt has been made to start a new process before the current process has finished its bootstrapping phase. RuntimeError:在当前进程完成其引导阶段之前,已尝试启动新进程。

    This probably means that you are not using fork to start your
    child processes and you have forgotten to use the proper idiom
    in the main module:

        if __name__ == '__main__':
            freeze_support()
            ...

    The "freeze_support()" line can be omitted if the program
    is not going to be frozen to produce an executable..

When adding if name == ' main ': in front of the code it crashes: https://imgur.com/a/YyUtWDS添加 if name == ' main ' 时:在代码前面它崩溃: https://imgur.com/a/YyUtWDS

But when I run the same code in python cmd it works just fine: https://imgur.com/a/ZYPUrJY但是当我在 python cmd 中运行相同的代码时,它工作得很好: https://imgur.com/a/ZYPUrJY

I have a 5 5600g apu and python 3.10 if that helps如果有帮助,我有 5 5600g apu 和 python 3.10

Any help would be greatly appreciated, Thanks in advance任何帮助将不胜感激,在此先感谢

[Edit]I saw your video and your code doesn't crash, the process just ends. [编辑]我看了你的视频,你的代码没有崩溃,这个过程就结束了。 You can just add sleep to see the browser work.您只需添加睡眠即可查看浏览器的工作情况。

This worked for me:这对我有用:

from multiprocessing import freeze_support
from time import sleep

if __name__ == '__main__':
    freeze_support()
    import undetected_chromedriver as uc
    driver = uc.Chrome()
    driver.get('https://nowsecure.nl')
    sleep(10)

Maybe you can omit freeze_support() in your case.也许你可以在你的情况下省略freeze_support()

And as someone suggests, I would move import undetected_chromedriver as uc to the top, though.正如有人建议的那样,不过,我会将import undetected_chromedriver as uc移到顶部。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM