繁体   English   中英

使用“从文件导入”功能时,如何在不修改导入文件的情况下修改导入文件以提供所需的输出?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM