Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 如何将输入文件中的字符串作为python代码运行?_Python 3.x - Fatal编程技术网

Python 3.x 如何将输入文件中的字符串作为python代码运行?

Python 3.x 如何将输入文件中的字符串作为python代码运行?,python-3.x,Python 3.x,我正在创造一些类似文字冒险游戏的东西。我有一个.yaml文件作为我的输入。这个文件看起来像这样 node_type: action title: Do some stuff info: This does some stuff and things script: 'print("hello world") print(ret_val) foo.bar(True) ret_val = (foo.bar() == True) if (thing):

我正在创造一些类似文字冒险游戏的东西。我有一个.yaml文件作为我的输入。这个文件看起来像这样

node_type: 
  action
title: 
  Do some stuff
info: 
  This does some stuff and things
script:
  'print("hello world")
  print(ret_val)
  foo.bar(True)
  ret_val = (foo.bar() == True)
  if (thing):
      print(thing)
  print(ret_val)
  '
我的最终目标是让python程序运行yaml文件的脚本部分,就像它被复制粘贴到主代码中一样。(我知道我不应该这样运行用户输入的安全原因大约有1000万个,但我是唯一一个编写这些节点的人,也是唯一一个使用这个程序的人,所以我基本上忽略了这个事实…)

目前我的尝试是这样的:我使用pyyaml作为dict加载我的yaml文件

node = yaml.safe_load(file.yaml)
然后我尝试使用exec来运行代码,遇到了很多问题,我无法运行
if
语句,我只是得到了一个语法错误,我无法从代码中获得任何类型的返回值。我尝试了以下方法:

def main()
    ret_val = "test";
    thing = exec(node['script'], globals(),locals())
    print(ret_val)
使用上面的.yaml文件运行时会打印

>> hello world
>> test
>> True
>> test   
出于某种原因,即使我将主变量输入exec,也没有修改任何主变量


我有没有办法解决这些问题,或者有没有更好的方法来解决这些问题?

一种方法是将代码解析出来并保存到一个
.py
文件中,从中可以动态导入代码,例如通过

您可能希望将解析后的代码封装到一个函数中,然后可以轻松调用该函数来调用您的操作。此外,在其中指定一些默认导入也是有意义的