如何安全运行不可靠的代码片段? [英] How to safely run unreliable piece of code?

查看:127
本文介绍了如何安全运行不可靠的代码片段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你正在使用一些不可信任的代码,那么有没有办法安全地运行,而不会失去对脚本的控制?



一个例子可能是一些只能在某些时间工作的功能,可能会随机/壮观地失败,您怎么才能重试,直到它工作?我使用线程模块尝试了一些黑客,但是麻烦地整齐地杀死了一个挂线。

 #!/ usr / bin / env python 

import os
import sys
import random

def unreliable_code():

def ok():
returnit working !!

def fail():
返回它没有工作

def crash():
1/0

def hang():
while True:
pass

def bye():
os._exit(0)

返回random.choice([ok,fail,crash,hang,bye])()


result = None
while result!=it working !!
#???


解决方案

您可以尝试以沙箱


Suppose you are working with some bodgy piece of code which you can't trust, is there a way to run it safely without losing control of your script?

An example might be a function which only works some of the time and might fail randomly/spectacularly, how could you retry until it works? I tried some hacking with using threading module but had trouble to kill a hung thread neatly.

#!/usr/bin/env python

import os
import sys
import random

def unreliable_code():

  def ok():
    return "it worked!!"

  def fail():
    return "it didn't work"

  def crash():
    1/0

  def hang():
    while True: 
      pass

  def bye():
    os._exit(0)

  return random.choice([ok, fail, crash, hang, bye])()


result = None
while result != "it worked!!":
  # ???

解决方案

You can try running it in a sandbox.

这篇关于如何安全运行不可靠的代码片段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆