Skip to content

RuntimeError: if __name__ == '__main__' #1242

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
fmbitts opened this issue Mar 11, 2025 · 4 comments · Fixed by #1258
Closed

RuntimeError: if __name__ == '__main__' #1242

fmbitts opened this issue Mar 11, 2025 · 4 comments · Fixed by #1258

Comments

@fmbitts
Copy link

fmbitts commented Mar 11, 2025

Expected behavior

Show my optimization, but does not finish due to this runtime error.

Code sample

class HiLoStrategy(Strategy):
    n = 5
    def init(self):
        high = self.data.High
        low = self.data.Low
        self.smahigh = self.I(SMA, high,self.n)
        self.smalow = self.I(SMA, low, self.n)
    def next(self):
        close = self.data.Close
       
        
        if crossover(close,self.smahigh):
            if self.position.is_short:
                self.position.close()
                self.buy()
            elif not self.position:
                self.buy()
           
        elif close < self.smalow:
            if self.position.is_long:
                self.position.close()
                self.sell()
            elif not self.position:
                self.sell()    
                
        
bt = Backtest(milho, HiLoStrategy, cash = 10000)
stats = bt.run()
#print(stats)
#bt.plot()

#%%
stats, heatmap = bt.optimize(
    n = range(1,100,1),
    maximize='Equity Final [$]',
    max_tries= 100,
    return_heatmap= True,
    method='grid')  # Try setting this to 1 to disable multiprocessing

print(stats)

Actual behavior

RuntimeError: 
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        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.

        To fix this issue, refer to the "Safe importing of main module"
        section in https://docs.python.org/3/library/multiprocessing.html
        
Traceback (most recent call last):
  File "<string>", line 1, in <module>
    from multiprocessing.spawn import spawn_main; spawn_main(tracker_fd=7, pipe_handle=44)
                                                  ~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/homebrew/Cellar/[email protected]/3.13.1/Frameworks/Python.framework/Versions/3.13/lib/python3.13/multiprocessing/spawn.py", line 122, in spawn_main
    exitcode = _main(fd, parent_sentinel)
  File "/opt/homebrew/Cellar/[email protected]/3.13.1/Frameworks/Python.framework/Versions/3.13/lib/python3.13/multiprocessing/spawn.py", line 131, in _main
    prepare(preparation_data)
    ~~~~~~~^^^^^^^^^^^^^^^^^^
  File "/opt/homebrew/Cellar/[email protected]/3.13.1/Frameworks/Python.framework/Versions/3.13/lib/python3.13/multiprocessing/spawn.py", line 246, in prepare
    _fixup_main_from_path(data['init_main_from_path'])
    ~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/opt/homebrew/Cellar/[email protected]/3.13.1/Frameworks/Python.framework/Versions/3.13/lib/python3.13/multiprocessing/spawn.py", line 297, in _fixup_main_from_path
    main_content = runpy.run_path(main_path,
                                  run_name="__mp_main__")
  File "<frozen runpy>", line 287, in run_path
  File "<frozen runpy>", line 98, in _run_module_code
  File "<frozen runpy>", line 88, in _run_code
  File "/Users/fernando/Documents/Dev/Milho/Hilo60_bt.py", line 67, in <module>
    stats, heatmap = bt.optimize(
                     ~~~~~~~~~~~^
        n = range(1,100,1),
        ^^^^^^^^^^^^^^^^^^^
    ...<2 lines>...
        return_heatmap= True,
        ^^^^^^^^^^^^^^^^^^^^^
        method='grid')  # Try setting this to 1 to disable multiprocessing
        ^^^^^^^^^^^^^^
  File "/Users/fernando/Documents/Dev/Milho/.venv/lib/python3.13/site-packages/backtesting/backtesting.py", line 1630, in optimize
    output = _optimize_grid()
  File "/Users/fernando/Documents/Dev/Milho/.venv/lib/python3.13/site-packages/backtesting/backtesting.py", line 1513, in _optimize_grid
    with mp.Pool() as pool, \
         ~~~~~~~^^
  File "/opt/homebrew/Cellar/[email protected]/3.13.1/Frameworks/Python.framework/Versions/3.13/lib/python3.13/multiprocessing/context.py", line 119, in Pool
    return Pool(processes, initializer, initargs, maxtasksperchild,
                context=self.get_context())
  File "/opt/homebrew/Cellar/[email protected]/3.13.1/Frameworks/Python.framework/Versions/3.13/lib/python3.13/multiprocessing/pool.py", line 215, in __init__
    self._repopulate_pool()
    ~~~~~~~~~~~~~~~~~~~~~^^
  File "/opt/homebrew/Cellar/[email protected]/3.13.1/Frameworks/Python.framework/Versions/3.13/lib/python3.13/multiprocessing/pool.py", line 306, in _repopulate_pool
    return self._repopulate_pool_static(self._ctx, self.Process,
           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^
                                        self._processes,
                                        ^^^^^^^^^^^^^^^^
    ...<3 lines>...
                                        self._maxtasksperchild,
                                        ^^^^^^^^^^^^^^^^^^^^^^^
                                        self._wrap_exception)
                                        ^^^^^^^^^^^^^^^^^^^^^
  File "/opt/homebrew/Cellar/[email protected]/3.13.1/Frameworks/Python.framework/Versions/3.13/lib/python3.13/multiprocessing/pool.py", line 329, in _repopulate_pool_static
    w.start()
    ~~~~~~~^^
  File "/opt/homebrew/Cellar/[email protected]/3.13.1/Frameworks/Python.framework/Versions/3.13/lib/python3.13/multiprocessing/process.py", line 121, in start
    self._popen = self._Popen(self)
                  ~~~~~~~~~~~^^^^^^
  File "/opt/homebrew/Cellar/[email protected]/3.13.1/Frameworks/Python.framework/Versions/3.13/lib/python3.13/multiprocessing/context.py", line 289, in _Popen
    return Popen(process_obj)
  File "/opt/homebrew/Cellar/[email protected]/3.13.1/Frameworks/Python.framework/Versions/3.13/lib/python3.13/multiprocessing/popen_spawn_posix.py", line 32, in __init__
    super().__init__(process_obj)
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^
  File "/opt/homebrew/Cellar/[email protected]/3.13.1/Frameworks/Python.framework/Versions/3.13/lib/python3.13/multiprocessing/popen_fork.py", line 20, in __init__
    self._launch(process_obj)
    ~~~~~~~~~~~~^^^^^^^^^^^^^
  File "/opt/homebrew/Cellar/[email protected]/3.13.1/Frameworks/Python.framework/Versions/3.13/lib/python3.13/multiprocessing/popen_spawn_posix.py", line 42, in _launch
    prep_data = spawn.get_preparation_data(process_obj._name)
  File "/opt/homebrew/Cellar/[email protected]/3.13.1/Frameworks/Python.framework/Versions/3.13/lib/python3.13/multiprocessing/spawn.py", line 164, in get_preparation_data
    _check_not_importing_main()
    ~~~~~~~~~~~~~~~~~~~~~~~~~^^
  File "/opt/homebrew/Cellar/[email protected]/3.13.1/Frameworks/Python.framework/Versions/3.13/lib/python3.13/multiprocessing/spawn.py", line 140, in _check_not_importing_main
    raise RuntimeError('''
    ...<16 lines>...
    ''')
RuntimeError: 
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        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.

        To fix this issue, refer to the "Safe importing of main module"
        section in https://docs.python.org/3/library/multiprocessing.html
        
Traceback (most recent call last):
  File "/Users/fernando/Documents/Dev/Milho/Hilo60_bt.py", line 67, in <module>
    stats, heatmap = bt.optimize(
                     ~~~~~~~~~~~^
        n = range(1,100,1),
        ^^^^^^^^^^^^^^^^^^^
    ...<2 lines>...
        return_heatmap= True,
        ^^^^^^^^^^^^^^^^^^^^^
        method='grid')  # Try setting this to 1 to disable multiprocessing
        ^^^^^^^^^^^^^^
  File "/Users/fernando/Documents/Dev/Milho/.venv/lib/python3.13/site-packages/backtesting/backtesting.py", line 1630, in optimize
    output = _optimize_grid()
  File "/Users/fernando/Documents/Dev/Milho/.venv/lib/python3.13/site-packages/backtesting/backtesting.py", line 1514, in _optimize_grid
    SharedMemoryManager() as smm:
    ~~~~~~~~~~~~~~~~~~~^^
  File "/opt/homebrew/Cellar/[email protected]/3.13.1/Frameworks/Python.framework/Versions/3.13/lib/python3.13/multiprocessing/managers.py", line 647, in __enter__
    self.start()
    ~~~~~~~~~~^^
  File "/opt/homebrew/Cellar/[email protected]/3.13.1/Frameworks/Python.framework/Versions/3.13/lib/python3.13/multiprocessing/managers.py", line 569, in start
    self._address = reader.recv()
                    ~~~~~~~~~~~^^
  File "/opt/homebrew/Cellar/[email protected]/3.13.1/Frameworks/Python.framework/Versions/3.13/lib/python3.13/multiprocessing/connection.py", line 250, in recv
    buf = self._recv_bytes()
  File "/opt/homebrew/Cellar/[email protected]/3.13.1/Frameworks/Python.framework/Versions/3.13/lib/python3.13/multiprocessing/connection.py", line 430, in _recv_bytes
    buf = self._recv(4)
  File "/opt/homebrew/Cellar/[email protected]/3.13.1/Frameworks/Python.framework/Versions/3.13/lib/python3.13/multiprocessing/connection.py", line 399, in _recv
    raise EOFError
EOFError

Additional info, steps to reproduce, full crash traceback, screenshots

No response

Software versions

  • Backtesting version: 0.6.2
  • bokeh.__version__: 3.6.3
  • OS: MacOS 15.4 Beta (24E5222f)
@kernc
Copy link
Owner

kernc commented Mar 11, 2025

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()
        ...

You are missing a if __name__ == '__main__' guard, running the optimization in global module scope. As the optimization uses multiprocessing, this same module is loaded by each of the worker processes, and executing the optimization line of the module again spawns new workers and ... recursively blows up.
See https://docs.python.org/3/library/__main__.html#name-main

In Python 3.13, you can try env var PYTHON_CPU_COUNT=1 to maybe fix it to a single process?

@kernc kernc changed the title Short title loaded with keywords RuntimeError: if __name__ == '__main__' Mar 11, 2025
@fmbitts
Copy link
Author

fmbitts commented Mar 12, 2025

I did both and still have some problems. Looks like is python 3.13. Which version should I go back to make sure will work?
UPDATE: I got working on python 3.9.6.
Thanks for the help.

@fmbitts fmbitts closed this as completed Mar 12, 2025
@kernc
Copy link
Owner

kernc commented Mar 12, 2025

I did both and still have some problems.

Can you elaborate on the issues you experienced?

if __name__ == '__main__' guard is the accepted idiomatic approach that should work. See Safe importing of main module: https://docs.python.org/3/library/multiprocessing.html#the-spawn-and-forkserver-start-methods
Reverting to an old, soon-to-be-EOL'd version of Python is not a solution!

@webspiderc
Copy link

webspiderc commented Mar 15, 2025

I have came across the same error on running Multiple Time Frame.ipynb with both backtesting 0.6.2 and 0.6.3. and it runs fine with 0.6.1

I am not sure where should I put the if name == 'main' line to have the error be fixed.

Or should I just used [PYTHON_CPU_COUNT=1] env setting to avoid the issue.

If I want to really want to use multi threads to speed up the optimisation, any suggestion ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants