![](/img/trans.png)
[英]How to import variables from a file which can be used in another file which is imported in the same file without importing the file again
[英]when using from file import function, how can the importing file be modified to give a desired output without modifying the imported file?
文件1
def multiply():
x = raw_input('enter the number')
y = x*4
文件2
from file1 import multiply
我如何在运行file2
时不执行用户输入的情况下使x = 4
的值并因此得到结果(4*4) = 16
?
尽管有hackey方式,但是有一种简单的方法可以实现您想要的。 我建议反对。 从根本上来说,这是一个糟糕的设计选择,但在这里是:
def multiply():
x = int(raw_input())
print x * 4
import sys
import io
def force_stdin(f, force_input):
stdin = sys.stdin
sys.stdin = io.StringIO(unicode(force_input))
f()
sys.stdin = stdin
force_stdin(multiply, '4')
输出:
16
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.