Содержание
- Multiprocessing runtime error freeze_support() in Windows 64 bit #7485
- Comments
- Issue description
- Code example
- System Info
- The «freeze_support()» line can be omitted if the program is not going to be frozen to produce an executable. #1
- Comments
- Как исправить «ошибку CX_Freeze Python в основном сценарии»?
- Удаление Raptr или PlayTV
- Удаление из программ и компонентов
- Использование программы удаления
- Переустановка скриптов cx_Freeze (если применимо)
- Удаление папки AppData игры
- Запуск сканирования DISM и SFC
Multiprocessing runtime error freeze_support() in Windows 64 bit #7485
If you have a question or would like help and support, please ask at our
forums.
If you are submitting a feature request, please preface the title with [feature request].
If you are submitting a bug report, please fill in the following details.
Issue description
When I run the examples of mnist using python main.py as mentioned in the examples here:
(https://github.com/pytorch/examples/tree/master/mnist)
getting this error:
Traceback (most recent call last):
File «», line 1, in
File «C:Anacondalibmultiprocessingspawn.py», line 105, in spawn_main
exitcode = _main(fd)
File «C:Anacondalibmultiprocessingspawn.py», line 114, in _main
prepare(preparation_data)
File «C:Anacondalibmultiprocessingspawn.py», line 225, in prepare
_fixup_main_from_path(data[‘init_main_from_path’])
File «C:Anacondalibmultiprocessingspawn.py», line 277, in _fixup_main_from_path
run_name=»mp_main«)
File «C:Anacondalibrunpy.py», line 263, in run_path
pkg_name=pkg_name, script_name=fname)
File «C:Anacondalibrunpy.py», line 96, in _run_module_code
mod_name, mod_spec, pkg_name, script_name)
File «C:Anacondalibrunpy.py», line 85, in _run_code
exec(code, run_globals)
File «C:Usersbanidenotebooksexamples-mastermnistmain.py», line 106, in
train(epoch)
File «C:Usersbanidenotebooksexamples-mastermnistmain.py», line 75, in train
for batch_idx, (data, target) in enumerate(train_loader):
File «C:Anacondalibsite-packagestorchutilsdatadataloader.py», line 451, in iter
return _DataLoaderIter(self)
File «C:Anacondalibsite-packagestorchutilsdatadataloader.py», line 239, in init
w.start()
File «C:Anacondalibmultiprocessingprocess.py», line 105, in start
self._popen = self._Popen(self)
File «C:Anacondalibmultiprocessingcontext.py», line 223, in _Popen
return _default_context.get_context().Process._Popen(process_obj)
File «C:Anacondalibmultiprocessingcontext.py», line 322, in _Popen
return Popen(process_obj)
File «C:Anacondalibmultiprocessingpopen_spawn_win32.py», line 33, in init
prep_data = spawn.get_preparation_data(process_obj._name)
File «C:Anacondalibmultiprocessingspawn.py», line 143, in get_preparation_data
_check_not_importing_main()
File «C:Anacondalibmultiprocessingspawn.py», line 136, in _check_not_importing_main
is not going to be frozen to produce an executable.»’)
RuntimeError:
An attempt has been made to start a new process before the
current process has finished its bootstrapping phase.
Code example
Please try to provide a minimal example to repro the bug.
Error messages and stack traces are also helpful.
System Info
Please copy and paste the output from our
environment collection script
(or fill out the checklist below manually).
You can get the script and run it with:
PyTorch version: 0.4.0
Is debug build: No
CUDA used to build PyTorch: 9.0
OS: Microsoft Windows Server 2016 Datacenter
GCC version: Could not collect
CMake version: version 3.11.1
Python version: 3.6
Is CUDA available: Yes
CUDA runtime version: 9.0.176
GPU models and configuration: GPU 0: Tesla K80
Nvidia driver version: 386.07
cuDNN version: Could not collect
Versions of relevant libraries:
[pip3] numpy (1.14.2)
[pip3] numpydoc (0.7.0)
[pip3] torch (0.4.0)
[pip3] torchvision (0.2.1)
[conda] cuda90 1.0 0 pytorch
[conda] pytorch 0.4.0 py36_cuda90_cudnn7he774522_1 [cuda90] pytorch
[conda] torchvision 0.2.1
The text was updated successfully, but these errors were encountered:
Read the windows doc please.
This has been open with the examples now, as the fix has to be in there.
pytorch/examples#352
Hello, thanks a lot for your reply.
I have carefully read that but still face the same problem.
Actually I am trying to run UCF101_CRNN.py of https://github.com/HHTseng/video-classification/tree/master/CRNN, and I added these at the begining of UCF101_CRNN.py:
def run():
torch.multiprocessing.freeze_support()
print(‘loop’)
if name == ‘main‘:
run()
But still face the same problem. Actually I am quite upset about this because I have tried a lot to fix this problem but still failed. Could you please kindly help me fix this?
Источник
The «freeze_support()» line can be omitted if the program is not going to be frozen to produce an executable. #1
:UserscaocaoAnaconda3python.exe D:/work/work11/SingleGAN-master/train.py —dataroot datasets/apple2orange —checkpoints_dir checkpoints —display_id 3 —name base_apple2orange —mode base —loadSize 143 —fineSize 138 —input_nc 3 —niter 100 —niter_decay 100 —lambda_ide 1 —display_port 8097 —batchSize 1 —ngf 64 —ndf 64
———— Options ————-
batchSize: 1
c_gan_mode: lsgan
c_num: 0
checkpoints_dir: checkpoints
continue_train: False
d_num: 2
dataroot: datasets/apple2orange
display_freq: 400
display_id: 3
display_port: 8097
display_winsize: 256
e_blocks: 6
fineSize: 138
gpu: 0
init_type: xavier
input_nc: 3
isTrain: True
is_flip: 1
lambda_c: 0.5
lambda_cyc: 10.0
lambda_ide: 1.0
lambda_kl: 0.01
loadSize: 143
lr: 0.0002
mode: base
nThreads: 4
name: base_apple2orange
ndf: 64
nef: 64
ngf: 64
niter: 100
niter_decay: 100
no_html: False
norm: instance
output_nc: 3
print_freq: 200
save_epoch_freq: 5
save_latest_freq: 10000
up_type: Trp
update_html_freq: 4000
which_epoch: latest
————— End —————-
Start preprocessing dataset.
Finished preprocessing dataset.
create web directory checkpointsbase_apple2orange2018_10_18_15_52_57web.
D:workwork11SingleGAN-mastermodelsmodel.py:46: UserWarning: nn.init.xavier_normal is now deprecated in favor of nn.init.xavier_normal_.
init.xavier_normal(m.weight.data, gain=math.sqrt(2))
D:workwork11SingleGAN-mastermodelsmodel.py:56: UserWarning: nn.init.constant is now deprecated in favor of nn.init.constant_.
init.constant(m.bias.data, 0.0)
———— Options ————-
batchSize: 1
c_gan_mode: lsgan
c_num: 0
checkpoints_dir: checkpoints
continue_train: False
d_num: 2
dataroot: datasets/apple2orange
display_freq: 400
display_id: 3
display_port: 8097
display_winsize: 256
e_blocks: 6
fineSize: 138
gpu: 0
init_type: xavier
input_nc: 3
isTrain: True
is_flip: 1
lambda_c: 0.5
lambda_cyc: 10.0
lambda_ide: 1.0
lambda_kl: 0.01
loadSize: 143
lr: 0.0002
mode: base
nThreads: 4
name: base_apple2orange
ndf: 64
nef: 64
ngf: 64
niter: 100
niter_decay: 100
no_html: False
norm: instance
output_nc: 3
print_freq: 200
save_epoch_freq: 5
save_latest_freq: 10000
up_type: Trp
update_html_freq: 4000
which_epoch: latest
————— End —————-
Start preprocessing dataset.
Finished preprocessing dataset.
create web directory checkpointsbase_apple2orange2018_10_18_15_53_02web.
D:workwork11SingleGAN-mastermodelsmodel.py:46: UserWarning: nn.init.xavier_normal is now deprecated in favor of nn.init.xavier_normal_.
init.xavier_normal(m.weight.data, gain=math.sqrt(2))
D:workwork11SingleGAN-mastermodelsmodel.py:56: UserWarning: nn.init.constant is now deprecated in favor of nn.init.constant_.
init.constant(m.bias.data, 0.0)
Traceback (most recent call last):
File «», line 1, in
Traceback (most recent call last):
File «D:/work/work11/SingleGAN-master/train.py», line 24, in
for i, data in enumerate(data_loader):
File «C:UserscaocaoAnaconda3libsite-packagestorchutilsdatadataloader.py», line 451, in iter
return _DataLoaderIter(self)
File «C:UserscaocaoAnaconda3libsite-packagestorchutilsdatadataloader.py», line 239, in init
w.start()
File «C:UserscaocaoAnaconda3libmultiprocessingprocess.py», line 105, in start
File «C:UserscaocaoAnaconda3libmultiprocessingspawn.py», line 106, in spawn_main
self._popen = self._Popen(self)
File «C:UserscaocaoAnaconda3libmultiprocessingcontext.py», line 212, in _Popen
exitcode = _main(fd)
File «C:UserscaocaoAnaconda3libmultiprocessingspawn.py», line 115, in _main
return _default_context.get_context().Process._Popen(process_obj)
File «C:UserscaocaoAnaconda3libmultiprocessingcontext.py», line 313, in _Popen
prepare(preparation_data)
File «C:UserscaocaoAnaconda3libmultiprocessingspawn.py», line 226, in prepare
return Popen(process_obj)
_fixup_main_from_path(data[‘init_main_from_path’])
File «C:UserscaocaoAnaconda3libmultiprocessingpopen_spawn_win32.py», line 66, in init
File «C:UserscaocaoAnaconda3libmultiprocessingspawn.py», line 278, in _fixup_main_from_path
reduction.dump(process_obj, to_child)
File «C:UserscaocaoAnaconda3libmultiprocessingreduction.py», line 59, in dump
run_name=»mp_main«)
File «C:UserscaocaoAnaconda3librunpy.py», line 254, in run_path
ForkingPickler(file, protocol).dump(obj)
BrokenPipeError: [Errno 32] Broken pipe
pkg_name=pkg_name, script_name=fname)
File «C:UserscaocaoAnaconda3librunpy.py», line 96, in _run_module_code
mod_name, mod_spec, pkg_name, script_name)
File «C:UserscaocaoAnaconda3librunpy.py», line 85, in _run_code
exec(code, run_globals)
File «D:workwork11SingleGAN-mastertrain.py», line 24, in
for i, data in enumerate(data_loader):
File «C:UserscaocaoAnaconda3libsite-packagestorchutilsdatadataloader.py», line 451, in iter
return _DataLoaderIter(self)
File «C:UserscaocaoAnaconda3libsite-packagestorchutilsdatadataloader.py», line 239, in init
w.start()
File «C:UserscaocaoAnaconda3libmultiprocessingprocess.py», line 105, in start
self._popen = self._Popen(self)
File «C:UserscaocaoAnaconda3libmultiprocessingcontext.py», line 212, in _Popen
return _default_context.get_context().Process._Popen(process_obj)
File «C:UserscaocaoAnaconda3libmultiprocessingcontext.py», line 313, in _Popen
return Popen(process_obj)
File «C:UserscaocaoAnaconda3libmultiprocessingpopen_spawn_win32.py», line 34, in init
prep_data = spawn.get_preparation_data(process_obj._name)
File «C:UserscaocaoAnaconda3libmultiprocessingspawn.py», line 144, in get_preparation_data
_check_not_importing_main()
File «C:UserscaocaoAnaconda3libmultiprocessingspawn.py», line 137, in _check_not_importing_main
is not going to be frozen to produce an executable.»’)
RuntimeError:
An attempt has been made to start a new process before the
current process has finished its bootstrapping phase.
Process finished with exit code 1
The text was updated successfully, but these errors were encountered:
You may use if __name__ == ‘__main__:’ to solve this problem in Windows (reference) or run this code in Linux.
Great work! Thank you !
from multiprocessing.pool import Pool
from multiprocessing import freeze_support
import requests
from timer import timer
def fetch(session, url):
with session.get(url) as response:
print(response.json()[‘uuid’])
@Timer(1, 1)
def main():
with Pool() as pool:
with requests.Session() as session:
pool.starmap(fetch, [(session, URL) for _ in range(100)])
if name == ‘main‘:
#freeze_support()
main()
Источник
Как исправить «ошибку CX_Freeze Python в основном сценарии»?
Некоторые пользователи Windows сообщают, что они видят ошибку запуска « CX_Freeze Python Error в основном сценарии» при каждом запуске системы. В большинстве случаев проблема возникает после удаления сторонней программы. Как оказалось, проблема не связана с ОС, поскольку она встречается в Windows 7, Windows 8.1 и Windows 10.
В подавляющем большинстве случаев, когда сообщается об этой проблеме, она в конечном итоге вызвана плохо написанным приложением Phyton (скорее всего, Raptr или PlayTV). Если этот сценарий применим, вы сможете решить проблему, удалив проблемное приложение – вы можете сделать это обычным образом (с помощью программ и компонентов) или с помощью мощного стороннего деинсталлятора.
Однако, если вы столкнулись с этой проблемой в игре (запущенной из Steam), возможно, вы столкнулись с ошибкой, вызванной серией временных файлов. в папке AppData. В этом случае очистка содержимого папки AppData и переустановка игры должны решить проблему.
Если вы видите ошибку при попытке запустить проект Phyton, который вы создали локально , скорее всего, проблема возникла из-за отсутствия исправления в установке cx_freeze . В этом случае вы можете решить проблему, удалив весь пакет cx_freeze из окна CMD, а затем переустановив последнюю версию.
Если все остальное не поможет, ваша последняя надежда на решение проблемы без сброс каждого компонента Windows – это запуск нескольких утилит (DISM и SFC), предназначенных для исправления большинства случаев повреждения системных файлов.
Удаление Raptr или PlayTV
Как бы то ни было. Оказывается, один из наиболее распространенных случаев, которые в конечном итоге приводят к ошибке запуска ‘ CX_Freeze Python Error in Main Script’ , – это программный продукт, который был написан несогласованно с использованием Python – в большинстве случаев затронут пользователи подтвердили, что проблема была вызвана либо Raptr, либо PlayTV.
Если этот сценарий применим, вы сможете решить проблему, принудительно удалив программу, которая, как вы подозреваете, может быть ответственна за ошибка запуска.
Когда дело доходит до этого, вы можете пойти традиционным путем (используя Программы и компоненты , чтобы выполнить удаление), или вы можете использовать мощный сторонний деинсталлятор, чтобы завершить работу. Начните с обычного подхода и переходите ко второму руководству только в случае сбоя первого.
Удаление из программ и компонентов
- Нажмите Клавиша Windows + R , чтобы открыть диалоговое окно Выполнить . Затем введите ‘appwiz.cpl’ в текстовое поле и нажмите Enter , чтобы открыть меню Программы и компоненты . .
- Как только вы попадете в меню Программы и функции , прокрутите список установленных приложений вниз и найдите PlayTV, Raptr или любую другую программу, которую вы подозреваете. может вызывать ошибку запуска ‘ Ошибка CX_Freeze Python в основном сценарии’ .
- После того, как вы найдете проблемное приложение, щелкните его правой кнопкой мыши и выберите Удалить из появившегося контекстного меню.
- В строке запроса на удаление следуйте на экране появится запрос на завершение удаления, затем перезагрузите компьютер и посмотрите, будет ли проблема решена при следующем запуске системы.
Если та же проблема все еще возникает, переместите ниже и начните со сторонней программы удаления.
Использование программы удаления
- Откройте браузер по умолчанию и перейдите по этой ссылке ( здесь ), чтобы загрузить и установить последнюю бесплатную версию Revo Uninsta. ller. Попав туда, нажмите кнопку Загрузить , чтобы начать процесс.
Примечание : держитесь подальше от портативной версии Revo, поскольку она не так эффективна, как версия InstallShield.
После полной загрузки исполняемого файла установки дважды щелкните по нему и следуйте инструкциям на экране, чтобы завершить установку.
Примечание. Если вам будет предложено окно UAC (Контроль учетных записей пользователей) , нажмите Да , чтобы предоставить доступ администратора.
Примечание. Если у вас установлены оба приложения, выполните этот шаг и те, что ниже, с обоими.
In если та же проблема все еще возникает, перейдите к следующему потенциальному исправлению ниже.
Переустановка скриптов cx_Freeze (если применимо)
Если вы столкнулись с ‘ Ошибка CX_Freeze Python в основном скрипте’ ошибка запуска при попытке запустить исполняемый файл вашего проекта Python, построенного с использованием cx_freeze, скорее всего, проблема возникает из-за отсутствия патча в установке cx_freeze , которую вы используете.
Если этот сценарий применим, вы сможете решить проблему, удалив весь пакет cx_freeze из окна CMD и переустановив последнюю версию через официальные каналы.
Здесь несколько пошаговых руководств, которые проведут вас через весь процесс:
- Нажмите клавишу Windows + R , чтобы открыть диалоговое окно Выполнить . В текстовом поле введите ‘cmd’ и нажмите Enter , чтобы открыть терминал командной строки .
- В терминале командной строки введите следующую команду и нажмите Enter , чтобы эффективно удалить весь пакет cx_freeze:
- После того, как пакет будет готов к удалению, вам будет предложено подтвердить свой выбор. Для этого нажмите клавишу Y , а затем снова Enter , чтобы завершить удаление пакета cx_freeze .
- Затем откройте браузер по умолчанию и используйте его для доступа к этой ссылке ( здесь ). Оказавшись внутри, вы должны увидеть список неофициальных двоичных файлов Windows для пакетов расширений Python .
- Прокрутите список двоичных файлов до cx_Freeze и найдите версию, связанную с используемой версией Python. Как только вам удастся найти его, нажмите на совместимую версию и дождитесь завершения загрузки.
- После завершения загрузки перейдите к месту загрузки, щелкните исполняемый файл правой кнопкой мыши и выберите Запуск от имени администратора в появившемся контекстном меню.
- На экране установки выберите свою версию Python и следуйте инструкциям на экране для завершения установка.
- После завершения установки и установки новой версии cx_freeze перестройте свой Python проект еще раз и посмотрите, решена ли проблема.
Если та же проблема все еще возникает или этот метод неприменим, перейдите к следующему потенциальному исправлению ниже.
Удаление папки AppData игры
Если вы видите « Ошибка CX_Freeze Python в основном сценарии » при попытке запустите игру, созданную на Python, возможно, вы имеете дело с поврежденными временными данными, присутствующими в папке AppData.
Несколько затронутых пользователей, которые также столкнулись с этой проблемой, подтвердили, что наконец-то смогли чтобы устранить ошибку и нормально играть в игру после доступа к папке AppData игры, очистив временные файлы игры и затем переустановив игру.
Если этот сценарий применим, следуйте инструкциям ниже, чтобы исправить ошибку «Ошибка CX_Freeze Python в основном сценарии» при попытке запустить игру:
- Нажмите клавишу Windows + R , чтобы открыть откройте диалоговое окно Выполнить . Затем введите “% appdata %” и нажмите Enter , чтобы открыть папку AppData (которая по умолчанию скрыта). .
- Как только вы окажетесь в папке AppData, вернитесь назад, нажав стрелку назад и нажмите Local.
Примечание. По умолчанию команда% appdata % автоматически открывает папку Roaming в Appdata.
Если вы все еще видите « Ошибка CX_Freeze Python в основном сценарии» или это потенциальное исправление не применимо, перейдите к следующему потенциальному исправлению. ниже.
Запуск сканирования DISM и SFC
В случае, если ни один из вышеперечисленных методов исправления не позволил вам решить проблему, ваш компьютер, вероятно, имеет дело с каким-либо типом системы повреждение файла, которое не может быть решено обычным способом. Скорее всего, ошибка запуска ‘ CX_Freeze Python Error in Main Script’ возникает из-за плохо написанной программы, которая не удалялась должным образом (даже если пользователь следовал обычным каналам).
Если этот сценарий применим, вы сможете решить проблему с помощью пары встроенных утилит (DISM и SFC), чтобы определить и исправить экземпляры поврежденных системных файлов, которые вызывают эта проблема.
SFC (Проверка системных файлов) – это полностью локальный инструмент, который работает, используя локально сохраненный кеш для замены поврежденных экземпляров работоспособными копиями. С другой стороны, инструмент DISM (Развертывание и развертывание обслуживания образов) требует стабильного подключения к Интернету, поскольку он полагается на подкомпонент Центра обновления Windows для получения исправных файлов, необходимых для замены поврежденных эквивалентов.
Поскольку эти два инструмента дополняют друг друга, мы рекомендуем пользователям запускать оба сканирования в быстрой последовательности, чтобы максимизировать ваши шансы решить проблему с повреждением системных файлов, которая вызывает ‘ CX_Freeze Ошибка Python в основном сценарии ‘.
Чтобы выполнить сканирование SFC, следуйте пошаговым инструкциям здесь . После завершения операции перезагрузите компьютер и продолжите сканирование DISM после завершения следующей последовательности запуска.
После выполнения обоих сканирований выполните окончательный перезапуск машины и посмотрите, перестает ли появляться ошибка запуска.
Источник
You may encounter one among a number of common errors when using the multiprocessing.Process class in Python.
These errors are typically easy to identify and often involve a quick fix.
In this tutorial, you will discover the common errors when creating child processes in Python and how to fix each in turn.
Let’s get started.
The multiprocessing module and multiprocessing.Process class provide a flexible and powerful approach to concurrency using child processes.
When you are getting started with multiprocessing in Python, you may encounter one of many common errors.
These errors are typically made because of bugs introduced by copy-and-pasting code, or from a slight misunderstanding in how new child processes work.
We will take a closer look at some of the more common errors made when creating new child processes; they are:
- Error 1: RuntimeError Starting New Processes
- Error 2: print() Does Not Work In Child Processes
- Error 3: Adding Attributes to Classes that Extend Process
Do you have an error using the multiprocessing module?
Let me know in the comments so I can recommend a fix and add the case to this tutorial.
Error 1: RuntimeError Starting New Processes
It is common to get a RuntimeError when starting a new Process in Python.
The content of the error often looks as follows:
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. |
This will happen on Windows and MacOS where the default start method is ‘spawn‘. It may also happen when you configure your program to use the ‘spawn‘ start method on other platforms.
This is a common error and is easy to fix.
The fix involves checking if the code is running in the top-level environment and only then, attempt to start a new process.
This is a best practice.
The idiom for this fix, as stated in the message of the RuntimeError, is to use an if-statement and check if the name of the module is equal to the string ‘__main__‘.
For example:
... # check for top-level environment if __name__ == ‘__main__’: # … |
This is called “protecting the entry point” of the program.
Recall, that __name__ is a variable that refers to the name of the module executing the current code.
Also, recall that ‘__main__‘ is the name of the top-level environment used to execute a Python program.
Using an if-statement to check if the module is the top-level environment and only starting child processes within that block will resolve the RuntimeError.
It means that if the Python file is imported, then the code protected by the if-statement will not run. It will only run when the Python file is run directly, e.g. is the top-level environment.
The if-statement idiom is required, even if the entry point of the program calls a function that itself starts a child process.
You can learn more about this common error in the tutorial:
- Fix RuntimeError When Spawning a Child Process
Confused by the multiprocessing module API?
Download my FREE PDF cheat sheet
Error 2: print() Does Not Work In Child Processes
Printing to standard out (stdout) with the built-in print() function may not work property from child processes.
For example, you may print output messages for the user or debug messages from a child process and they may never appear, or may only appear when the child process is terminated.
For example:
... # report a message from a child process print(‘Hello from the child process’) |
This is a very common situation and the cause is well understood and easy to workaround.
The print() function is a built-in function for displaying messages on standard output or stdout.
When you call print() from a child process created using the ‘spawn‘ start method, the message will not appear.
This is because the messages are block buffered by default and the buffer is not flushed by default after every message. This is unlike the main process that is interactive and will flush messages after each line, e.g. line buffered.
Instead, the buffered messages are only flushed occasionally, such as when the child process terminates and the buffer is garbage collected.
We can flush stdout automatically with each call to print().
This can be achieved by setting the ‘flush‘ argument to True.
For example:
... # report a message from a child process print(‘Hello from the child process’, flush=True) |
An alternate approach is to call the flush() function on the sys.stdout object directly.
For example:
... # report a message from a child process print(‘Hello from the child process’) # flush output sys.stdout.flush() |
The problem with the print() function only occurs when using the ‘spawn‘ start method.
You can change the start method to ‘fork‘ which will cause print() to work as expected.
Note, the ‘fork‘ start method is not supported on Windows at the time of writing.
You can set the start method via the multiprocessing.set_start_method() function.
For example:
... # set the start method to fork set_start_method(‘fork’) |
You can learn more about process start methods in the tutorial:
- Multiprocessing Start Methods
You can learn more about fixing print() from child processes in the tutorial:
- How to print() from a Child Process in Python
Free Python Multiprocessing Course
Download my multiprocessing API cheat sheet and as a bonus you will get FREE access to my 7-day email course.
Discover how to use the Python multiprocessing module including how to create and start child processes and how to use a mutex locks and semaphores.
Learn more
Error 3: Adding Attributes to Classes that Extend Process
Python provides the ability to create and manage new processes via the multiprocessing.Process class.
We can extend this class and override the run() function in order to run code in a new child process.
You can learn more about extending the the multiprocessing.Process class in the tutorial:
- How to Extend the Process Class in Python
Extending the multiprocessing.Process and adding attributes that are shared among multiple processes will fail with an error.
For example, if we define a new class that extends the multiprocessing.Process class that sets an attribute on the class instance from the run() method executed in a new child process, then this attribute will not be accessible by other processes, such as the parent process.
This is the case even if both parent and child processes share access to the “same” object.
This is because class instance variables are not shared among processes by default. Instead, instance variables added to the multiprocessing.Process are private to the process that added them.
Each process operates on a serialized copy of the object and any changes made to that object are local to that process only, by default.
If you set class attributes in the child process and try to access them in the parent process or another process, you will get an error.
For example:
Traceback (most recent call last): … AttributeError: ‘CustomProcess’ object has no attribute ‘data’ |
This error occurred because the child process operates on a copy of the class instance that is different from the copy of the class instance used in the parent process.
Instance variable attributes can be shared between processes via the multiprocessing.Value and multiprocessing.Array classes.
These classes explicitly define data attributes designed to be shared between processes in a process-safe manner.
Shared variables mean that changes made in one process are always propagated and made available to other processes.
An instance of the multiprocessing.Value can be defined in the constructor of a custom class as a shared instance variable.
The constructor of the multiprocessing.Value class requires that we specify the data type and an initial value.
The data type can be specified using ctype “type” or a typecode.
Typecodes are familiar and easy to use, for example ‘i’ for a signed integer or ‘f’ for a single floating-point value.
For example, we can define a multiprocessing.Value shared memory variable that holds a signed integer and is initialized to the value zero.
... # initialize an integer shared variable data = multiprocessing.Value(‘i’, 0) |
This can be initialized in the constructor of the class that extends the multiprocessing.Process class.
We can change the value of the shared data variable via the “value” attribute.
For example:
... # change the value of the shared variable data.value = 100 |
We can access the value of the shared data variable via the same “value” attribute.
For example:
... # access the shared variable value = data.value |
The propagation of changes to the shared variable and mutual exclusion locking of the shared variable is all performed automatically behind the scenes.
You can learn more about this error and how to fix in the tutorial:
- Shared Process Class Attributes in Python
Further Reading
This section provides additional resources that you may find helpful.
Books
- Python Multiprocessing Jump-Start, Jason Brownlee, 2022 (my book!).
- Multiprocessing API Interview Questions
- Multiprocessing Module API Cheat Sheet
I would also recommend specific chapters in the books:
- Effective Python, Brett Slatkin, 2019.
- See: Chapter 7: Concurrency and Parallelism
- High Performance Python, Ian Ozsvald and Micha Gorelick, 2020.
- See: Chapter 9: The multiprocessing Module
- Python in a Nutshell, Alex Martelli, et al., 2017.
- See: Chapter: 14: Threads and Processes
Guides
- Python Multiprocessing: The Complete Guide
APIs
- multiprocessing — Process-based parallelism
- PEP 371 — Addition of the multiprocessing package
Takeaways
You now know about the common errors when using multiprocessing in Python.
Do you have any questions?
Ask your questions in the comments below and I will do my best to answer.
Photo by Rachael Annabelle on Unsplash
Пытаюсь сделать мультипроцессное приложение для ускорения работы моего скрипта, начал с простого примера:
Python | ||
|
Приведенный выше пример прекрасно работает, но я хочу запускать подпроцессы из функции, которую буду вызывать из некоторого места, поэтому пишу так:
Python | ||
|
а функцию main() вызываю из другого файла. В результате получаю ошибку:
Кликните здесь для просмотра всего текста
Traceback (most recent call last):
File «<string>», line 1, in <module>
File «C:UsersuserweatherAppDataLocalProgramsPytho nPython36-32libmultiprocessingspawn.py», line 105, in spawn_main
exitcode = _main(fd)
File «C:UsersuserweatherAppDataLocalProgramsPytho nPython36-32libmultiprocessingspawn.py», line 114, in _main
prepare(preparation_data)
File «C:UsersuserweatherAppDataLocalProgramsPytho nPython36-32libmultiprocessingspawn.py», line 225, in prepare
_fixup_main_from_path(data[‘init_main_from_path’])
File «C:UsersuserweatherAppDataLocalProgramsPytho nPython36-32libmultiprocessingspawn.py», line 277, in _fixup_main_from_path
run_name=»__mp_main__»)
File «C:UsersuserweatherAppDataLocalProgramsPytho nPython36-32librunpy.py», line 263, in run_path
pkg_name=pkg_name, script_name=fname)
File «C:UsersuserweatherAppDataLocalProgramsPytho nPython36-32librunpy.py», line 96, in _run_module_code
mod_name, mod_spec, pkg_name, script_name)
File «C:UsersuserweatherAppDataLocalProgramsPytho nPython36-32librunpy.py», line 85, in _run_code
exec(code, run_globals)
File «C:UsersuserweatherDesktopProjectsPython03_ Paralleltest.py», line 3, in <module>
mainn.main()
File «C:UsersuserweatherDesktopProjectsPython03_ Parallelmainn.py», line 16, in main
p1.start()
File «C:UsersuserweatherAppDataLocalProgramsPytho nPython36-32libmultiprocessingprocess.py», line 105, in start
self._popen = self._Popen(self)
File «C:UsersuserweatherAppDataLocalProgramsPytho nPython36-32libmultiprocessingcontext.py», line 223, in _Popen
return _default_context.get_context().Process._Popen(proc ess_obj)
File «C:UsersuserweatherAppDataLocalProgramsPytho nPython36-32libmultiprocessingcontext.py», line 322, in _Popen
return Popen(process_obj)
File «C:UsersuserweatherAppDataLocalProgramsPytho nPython36-32libmultiprocessingpopen_spawn_win32.py», line 33, in __init__
prep_data = spawn.get_preparation_data(process_obj._name)
File «C:UsersuserweatherAppDataLocalProgramsPytho nPython36-32libmultiprocessingspawn.py», line 143, in get_preparation_data
_check_not_importing_main()
File «C:UsersuserweatherAppDataLocalProgramsPytho nPython36-32libmultiprocessingspawn.py», line 136, in _check_not_importing_main
is not going to be frozen to produce an executable.»’)
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.
Traceback (most recent call last):
File «<string>», line 1, in <module>
File «C:UsersuserweatherAppDataLocalProgramsPytho nPython36-32libmultiprocessingspawn.py», line 105, in spawn_main
exitcode = _main(fd)
File «C:UsersuserweatherAppDataLocalProgramsPytho nPython36-32libmultiprocessingspawn.py», line 114, in _main
prepare(preparation_data)
File «C:UsersuserweatherAppDataLocalProgramsPytho nPython36-32libmultiprocessingspawn.py», line 225, in prepare
_fixup_main_from_path(data[‘init_main_from_path’])
File «C:UsersuserweatherAppDataLocalProgramsPytho nPython36-32libmultiprocessingspawn.py», line 277, in _fixup_main_from_path
run_name=»__mp_main__»)
File «C:UsersuserweatherAppDataLocalProgramsPytho nPython36-32librunpy.py», line 263, in run_path
pkg_name=pkg_name, script_name=fname)
File «C:UsersuserweatherAppDataLocalProgramsPytho nPython36-32librunpy.py», line 96, in _run_module_code
mod_name, mod_spec, pkg_name, script_name)
File «C:UsersuserweatherAppDataLocalProgramsPytho nPython36-32librunpy.py», line 85, in _run_code
exec(code, run_globals)
File «C:UsersuserweatherDesktopProjectsPython03_ Paralleltest.py», line 3, in <module>
mainn.main()
File «C:UsersuserweatherDesktopProjectsPython03_ Parallelmainn.py», line 16, in main
p1.start()
File «C:UsersuserweatherAppDataLocalProgramsPytho nPython36-32libmultiprocessingprocess.py», line 105, in start
self._popen = self._Popen(self)
File «C:UsersuserweatherAppDataLocalProgramsPytho nPython36-32libmultiprocessingcontext.py», line 223, in _Popen
return _default_context.get_context().Process._Popen(proc ess_obj)
File «C:UsersuserweatherAppDataLocalProgramsPytho nPython36-32libmultiprocessingcontext.py», line 322, in _Popen
return Popen(process_obj)
File «C:UsersuserweatherAppDataLocalProgramsPytho nPython36-32libmultiprocessingpopen_spawn_win32.py», line 33, in __init__
prep_data = spawn.get_preparation_data(process_obj._name)
File «C:UsersuserweatherAppDataLocalProgramsPytho nPython36-32libmultiprocessingspawn.py», line 143, in get_preparation_data
_check_not_importing_main()
File «C:UsersuserweatherAppDataLocalProgramsPytho nPython36-32libmultiprocessingspawn.py», line 136, in _check_not_importing_main
is not going to be frozen to produce an executable.»’)
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.
Скажите, как реализовать задуманное, чтобы вызов подпроцессов осуществлялся в рамках функции (или даже метода класса).
__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь