来自thiscommunicate() 的文档:
与进程交互:将数据发送到标准输入。从标准输出读取数据并
stderr,直到到达文件结尾。 等待进程终止。
不要使用shell=True,如果你想在不等待进程停止的情况下进行读写。详情请参考doc。
使用此代码:
import subprocess
result=subprocess.Popen(['perl','Hello.pl'],stdout=subprocess.PIPE)
out,err=result.communicate()
print out
如何从命令行读取一些参数并作为输入传递。例如:perl Hello.pl some_variable_name
你可以使用argparse
Python 代码:
import subprocess
import argparse
parser = argparse.ArgumentParser(description='Test Python Code')
parser.add_argument('first_name', metavar='FIRST_NAME', type=str,
help='Enter the first name')
parser.add_argument('second_name', metavar='SECOND_NAME', type=str,
help='Enter the second name')
# Parse command line arguments
args = parser.parse_args()
result=subprocess.Popen(['perl','Hello.pl',args.first_name,args.second_name],stdout=subprocess.PIPE)
out,err=result.communicate()
print out
Perl 代码:
#!/usr/bin/perl -w
# (1) quit unless we have the correct number of command-line args
$num_args = $#ARGV + 1;
if ($num_args != 2) {
print "\nUsage: name.pl first_name last_name\n";
exit;
}
# (2) we got two command line args, so assume they are the
# first name and last name
$first_name=$ARGV[0];
$last_name=$ARGV[1];
print "First name: $first_name \nSecond name: $last_name\n";
示例输出: