命令行参数 - 在 运行 Python 代码时设置超时限制
Command Line Arguments - Set Timeout Limit when Running Python Code
我有一个 bash 文件,我在其中的 for 循环中多次执行 python 代码。我想设置一个超时时间,这样如果 python 代码花费的时间超过一定时间,那么我们将进入下一次迭代。
如何在编译和 运行 python 文件时将超时添加到我的 bash 代码行?
这是我用于 运行 python 代码的当前行:
python hw.py
我想要这样的东西:
python hw.py timeout=120
假设您希望将参数解析为 Python 脚本。
尝试 argparse:
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--timeout', help='timeout of script',action = 'store')
args = parser.parse_args()
将args.timeout
解析为您需要的脚本。
from time import time
start = time()
for loop: # the for loop you mentioned
if (time() - start) > timeout:
break
您可以在bash
中使用timeout
命令:
timeout 120 python hw.py
如果执行时间超过 120 秒,python 进程将终止。
我有一个 bash 文件,我在其中的 for 循环中多次执行 python 代码。我想设置一个超时时间,这样如果 python 代码花费的时间超过一定时间,那么我们将进入下一次迭代。 如何在编译和 运行 python 文件时将超时添加到我的 bash 代码行? 这是我用于 运行 python 代码的当前行:
python hw.py
我想要这样的东西:
python hw.py timeout=120
假设您希望将参数解析为 Python 脚本。
尝试 argparse:
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--timeout', help='timeout of script',action = 'store')
args = parser.parse_args()
将args.timeout
解析为您需要的脚本。
from time import time
start = time()
for loop: # the for loop you mentioned
if (time() - start) > timeout:
break
您可以在bash
中使用timeout
命令:
timeout 120 python hw.py
如果执行时间超过 120 秒,python 进程将终止。