【发布时间】:2020-05-16 12:44:18
【问题描述】:
我有运行函数以从 API 检索项目的多处理代码:
import os
import pandas as pd
from multiprocessing import Pool
from datetime import timedelta, date
from external_functions import get_api_item #separate .py file with a function
def date_range(start_date, end_date):
for n in range(int ((end_date - start_date).days)):
yield start_date + timedelta(n)
start_date = date(2020, 1, 29)
end_date = date(2020, 1, 30)
date_list = []
for single_date in date_range(start_date, end_date):
date_list.append(single_date.strftime('%Y-%m-%d'))
if __name__ == '__main__':
global results
p = Pool(20)
results = p.map(get_api_item, date_list)
p.terminate()
p.join()
result = pd.concat(results)
当我从 Jupyter Notebook、Spyder 等运行此代码时,它可以工作。当我从 SSIS 中的 Execute Process 任务执行它时,我收到此错误:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "E:\Python\Anaconda3\lib\multiprocessing\spawn.py", line 105, in spawn_ma
in
exitcode = _main(fd)
File "E:\Python\Anaconda3\lib\multiprocessing\spawn.py", line 114, in _main
prepare(preparation_data)
File "E:\Python\Anaconda3\lib\multiprocessing\spawn.py", line 225, in prepare
_fixup_main_from_path(data['init_main_from_path'])
File "E:\Python\Anaconda3\lib\multiprocessing\spawn.py", line 277, in _fixup_m
ain_from_path
run_name="__mp_main__")
File "E:\Python\Anaconda3\lib\runpy.py", line 263, in run_path
pkg_name=pkg_name, script_name=fname)
File "E:\Python\Anaconda3\lib\runpy.py", line 96, in _run_module_code
mod_name, mod_spec, pkg_name, script_name)
File "E:\Python\Anaconda3\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "<path to api>\api.py", line 29, in <module>
result = pd.concat(results)
NameError: name 'results' is not defined
这告诉我函数本身实际上并没有运行/完成将results 提供给下一行。为什么会这样?
如果我删除 if __name__ == '__main__': 并直接运行它,我会收到此错误:
File "E:\Python\Anaconda3\lib\multiprocessing\spawn.py", line 143, in get_prep
aration_data
_check_not_importing_main()
File "E:\Python\Anaconda3\lib\multiprocessing\spawn.py", line 136, in _check_n
ot_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.
【问题讨论】:
标签: python python-3.x ssis multiprocessing main