【发布时间】:2021-04-15 10:48:05
【问题描述】:
我正在尝试使用os.popen() 编写一个接受文件参数并将其发送到子进程的 Python 程序。它适用于普通文件。但是在使用 bash Process Substitution (short article) 时它不起作用。
为什么os.system() 可以工作,但os.popen() 对于相同的命令会失败(在 Ubuntu 上)?这里是run.py:
#!/usr/bin/env python3
import os
import sys
cmd = "ls -l %s" % sys.argv[1]
os.system(cmd)
pipe = os.popen(cmd)
print(pipe.read(), end="")
输出:
# Both os.system("ls -l file") and os.popen("ls -l file") work great
$ run.py file
-rw-r--r-- 1 peter peter 313080 Apr 15 12:27 file
-rw-r--r-- 1 peter peter 313080 Apr 15 12:27 file
# os.system("ls -l /proc/self/fd/11") works great but os.popen("ls -l /proc/self/fd/11") fails
$ run.py <(cat file)
lr-x------ 1 peter peter 64 Apr 15 12:27 /proc/self/fd/11 -> 'pipe:[171197]'
ls: cannot access '/proc/self/fd/11': No such file or directory
有人知道为什么os.popen("ls -l /proc/self/fd/11") 会这样失败吗?
我创建了一个 Perl 版本,perl-run.pl,与上面的 Python run.pl 版本相似,并且 Perl 的 system() 和 open() 都可以正常工作:
#!/usr/bin/perl -w
use strict;
my $cmd = "ls -l $ARGV[0]";
system($cmd);
open(my $i, $cmd . " |");
print <$i>;
输出:
$ perl-run.pl <(cat file)
lr-x------ 1 peter peter 64 Apr 15 12:27 /proc/self/fd/11 -> 'pipe:[165704]'
lr-x------ 1 peter peter 64 Apr 15 12:27 /proc/self/fd/11 -> pipe:[165704]
【问题讨论】:
标签: python