我要做的是在 python 函数中创建多个输出流,并将它们称为1
, 2
, 3
……:
在test.py
:
def main():
...
print >>fd1, 'words1'
print >>fd2, 'words2'
print >>fd3, 'words3'
...
使用时重定向:
python test.py 1>1.txt 2>2.txt 3>3.txt
这些文件的内容:
1.txt -> words1
2.txt -> words2
3.txt -> words3
问题是,如何创建这些fd1
, fd2
, fd3
?
Added:
我用过这个:
outfiles = {}
for _ in range(3):
fd = os.dup(1)
outfiles[fd] = os.fdopen(fd, 'w')
def main():
for no in outfiles:
print >>outfiles[no], "foo"
print >>outfiles[no], outfiles[no].fileno()
但结果取决于我如何执行这段代码:
eg1:
python test.py
foo
3
foo
4
foo
5
eg2:
python test.py 3>log.txt
foo
4
foo
5
foo
6
eg3:
python test.py 1>log.txt
Nothing printed
所以我想,输出实际上是1
,并且如果文件描述符已在执行中使用(例如:python test.py 3>log.txt
),os.dup(1) 将不再返回它。