首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在jupyter笔记本中运行带有超时的python脚本

在jupyter笔记本中运行带有超时的python脚本
EN

Stack Overflow用户
提问于 2021-01-04 14:07:11
回答 1查看 448关注 0票数 1

我正在执行以下朱庇特笔记本中的代码

代码语言:javascript
复制
import os
import shlex

files = os.listdir("./data/")

for file in files:
    %run -timeout=5 -i solver.py ./data/$file

我得到以下错误:

代码语言:javascript
复制
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
~/Desktop/GitHub/coursera/discrete-optimization/week2/knapsack/solver.py in <module>
      1 for file in files:
----> 2     get_ipython().run_line_magic('run', '-timeout=5 -i solver.py ./data/$file')

~/opt/anaconda3/lib/python3.8/site-packages/IPython/core/interactiveshell.py in run_line_magic(self, magic_name, line, _stack_depth)
   2324                 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
   2325             with self.builtin_trap:
-> 2326                 result = fn(*args, **kwargs)
   2327             return result
   2328 

<decorator-gen-59> in run(self, parameter_s, runner, file_finder)

~/opt/anaconda3/lib/python3.8/site-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
    185     # but it's overkill for just that one bit of state.
    186     def magic_deco(arg):
--> 187         call = lambda f, *a, **k: f(*a, **k)
    188 
    189         if callable(arg):

~/opt/anaconda3/lib/python3.8/site-packages/IPython/core/magics/execution.py in run(self, parameter_s, runner, file_finder)
    687         if "m" in opts:
    688             modulename = opts["m"][0]
--> 689             modpath = find_mod(modulename)
    690             if modpath is None:
    691                 msg = '%r is not a valid modulename on sys.path'%modulename

~/opt/anaconda3/lib/python3.8/site-packages/IPython/utils/module_paths.py in find_mod(module_name)
     60     """
     61     loader = importlib.util.find_spec(module_name)
---> 62     module_path = loader.origin
     63     if module_path is None:
     64         return None

AttributeError: 'NoneType' object has no attribute 'origin'

显然,超时选项不起作用。

为我的代码设置超时选项的正确方法是什么?如果测试用例超过特定时间(例如,5秒),我希望停止它的执行。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-04 14:18:23

你能做到的

代码语言:javascript
复制
import os
import shlex

files = os.listdir("./data/")

for file in files:
    ! timeout 5 python solver.py ./data/$file
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65564043

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档