Python:“执行打开(外部.py).read(),locals(),同时允许它操作主脚本中的对象

2024-03-28 22:58:40 发布

您现在位置:Python中文网/ 问答频道 /正文

背景

我使用Python2.7中可怕的exec open,从我的主脚本(main_file.py)中执行另外两个Python文件(file1.py和{})。在

我是一个新手程序员,我这样做是因为外部文件位于驱动器的其他位置。main_file.py旁边的许多不同的Python脚本同时访问file1.py和{}中的内容。所以当我更新这两个时,所有访问它们的脚本都将从更新中受益。它们包含应用于所有Python脚本的列表和通用规则。在

在我把一个新函数newFunction()引入main_file.py之前,一切都很好。newFunction()从主脚本的另一个函数topFunction()内部调用。在


错误

exec open(file2.py).read()

SyntaxError: unqualified exec is not allowed in function 'topFunction()' because it contains a nested function with free variables.

错误消息实际上指向下面的第2步:

  1. topFunction()第一个调用newFunction()
  2. topFunction()想要exec open(file2.py)

更复杂的是,newFunction()file1.py访问以前执行到main_file.py中的列表变量。而且,一旦从file1.py执行了这些列表,file2.py也引用了main_file.py中的那些列表。在


尝试解决

所以,我找到了一些东西,至少可以让脚本运行,没有错误消息。在

exec open(file2.py).read() in globals(), locals()

这个实际上将执行file2.py中的代码,然后继续运行剩下的在main_file.py中运行的代码。 但问题是file2.py将无法操纵main_file.py中本机的变量(对象)。在

我不能让file2.py设置myString = "pancakes",然后让{}设置为print myString。在

在引入newFunction()之前,这是可能的,当时我只使用了exec open(file2.py).read()。在


问题

有没有一种方法可以让类似的东西正常工作,这样外部执行的脚本也可以影响主脚本中使用的变量?在

exec open(file2.py).read() in globals(), locals()

Tags: 文件inpy脚本列表readmain错误
1条回答
网友
1楼 · 发布于 2024-03-28 22:58:40

引用docs

This function is similar to the exec statement, but parses a file instead of a string. It is different from the import statement in that it does not use the module administration — it reads the file unconditionally and does not create a new module. [1]

The arguments are a file name and two optional dictionaries. The file is parsed and evaluated as a sequence of Python statements (similarly to a module) using the globals and locals dictionaries as global and local namespace. If provided, locals can be any mapping object. Remember that at module level, globals and locals are the same dictionary. If two separate objects are passed as globals and locals, the code will be executed as if it were embedded in a class definition.

所以你应该试试这个:

execfile('file1.py')
execfile('file2.py')

相关问题 更多 >