所以我有两个python脚本,其中一个是在另一个中调用函数:
First(first.py):
def get_values(number):
....
for x in range(number):
print x
秒(second.py):
import first
....
data = first.get_values(10)
我的目标是将 get_value 的输出保存在 first.py 中,以保存为变量 data 作为列表(即[0 ,1,2,3,...])。有没有办法做到这一点,而不在过程中打印这些值?
提前致谢!
编辑:我无法改变 first.py ,因为其他功能已经依赖于它的当前输出。
答案 0 :(得分:2)
您可以使用redirect_stdout抓取标准输出:
#!/usr/bin/env python
import io
# if python3
# from contextlib import redirect_stdout
# if python2
import sys
from contextlib import contextmanager
# Note: I took this method from someone else's SO answer, but I think
# they took it from someone else...etc.
@contextmanager
def redirect_stdout(new_target):
old_target, sys.stdout = sys.stdout, new_target # replace sys.stdout
try:
yield new_target # run some code with the replaced stdout
finally:
sys.stdout = old_target # restore to the previous value
def get_values(number):
values = tuple(range(number))
for v in values:
print(v)
return values
def main():
saved_stdout = io.StringIO()
with redirect_stdout(saved_stdout):
data = get_values(4)
print(data)
data = get_values(2)
print(data)
main()
输出:
$ python stdout.py
(0, 1, 2, 3)
0
1
(0, 1)
答案 1 :(得分:1)
在first.py中创建一个如下列表:
def get_values(number):
....
return [x for x in range(number)]
然后在second.py中你可以做到
data = first.get_values(10)
答案 2 :(得分:1)
将输出重定向到io流,然后再读取(Python 3.5)。
import sys
import io
stdout = sys.stdout # keep a handle on the real standard output
local_i = io.StringIO()
sys.stdout = local_i # Choose a file-like object to write to
for i in range(10): # this is just an example, you have to call your function here from first.py
print(i)
sys.stdout = stdout# revert to standard output
print("This printing is after the function call. You can process it as you want. This is just for demonstration purpose.")
for i in local_i.getvalue():
if i != '\n':
print(int(i))
对于Python 2:
import sys
import StringIO
stdout = sys.stdout # keep a handle on the real standard output
local_i = StringIO.StringIO()
sys.stdout = local_i # Choose a file-like object to write to
for i in range(10):
print(i)
sys.stdout = stdout# revert to standard output
print(
"This printing is after the function call. You can process it as you want. This is just for demonstration purpose")
for i in local_i.getvalue():
if i != '\n':
print(int(i))
输出:
This printing is after the function call. You can process it as you want. This is just for demonstration purpose.
0
1
2
3
4
5
6
7
8
9