Issue
I am executing the following piece of code in Jupyter Notebook
import os
import shlex
files = os.listdir("./data/")
for file in files:
%run -timeout=5 -i solver.py ./data/$file
I get the following error:
---------------------------------------------------------------------------
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'
Clearly, the timeout option is not working.
What is the correct way to set a timeout option for my code? I want to stop execution for a test case if it reaches beyond a specific time, for example, 5 sec.
Solution
You can do
import os
import shlex
files = os.listdir("./data/")
for file in files:
! timeout 5 python solver.py ./data/$file
Answered By - Pani
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.