Python 传递变量以导入文件


python pass variable to import file

据我了解,在 PHP 中,require_once('filename.php') 函数本质上是获取'filename.php'的内容,并将其内联放置在发生require_once调用的当前文件中。 这使我能够执行以下操作:

$ cat caller.php
#!/usr/bin/php
<?php
$a = 'value of variable a';
require_once('callee.php');
?>
$ cat callee.php
<?php echo $a; ?>
$ ./caller.php
value of variable a

换句话说,变量$a的值被传递给文件callee.php

有没有办法在 Python 中将变量传递给另一个这样的文件? 我已经试过这个,但它不起作用:

$ cat caller.py
#!/usr/bin/env
a = 'value of variable a'
import callee
$ cat callee.py
print a
$ ./caller.py
Traceback (most recent call last):
  File "/tmp/caller.py", line 3, in <module>
    import callee
  File "/tmp/callee.py", line 1, in <module>
    print a
NameError: name 'a' is not defined

我想我可以将变量作为参数传递给 callee.py 中的函数,但如果可能的话,我不想这样做。

试试execfile .

取代

import callee

execfile("callee.py")

import相比,execfile需要更多的异常处理,则应考虑脚本中将会出现异常。虽然我认为 php 也需要它。

好吧,在Python中,它使用命名空间,试试吧

print callee.a

导入被叫方后 这将适用于您的工作。你会发现一个callee.pyc,它是Python中的一个编译文件。