【问题标题】:run perl command in python file在 python 文件中运行 perl 命令
【发布时间】:2018-09-05 11:39:54
【问题描述】:
import subprocess
result=subprocess.Popen(['perl','Hello.pl'],stdout=subprocess.PIPE,shell=True)
out,err=result.communicate()
print out

这是我的程序,我正在尝试在 python 文件中运行 perl 程序。我正在使用 python 2.6v

在运行此文件时,它没有提供任何内容。

我是 python 新手。

谁能帮忙?

【问题讨论】:

  • “它什么也没给”是什么意思?

标签: python shell perl


【解决方案1】:

来自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";

示例输出:

【讨论】:

  • 如何从命令行读取一些参数并作为输入传递。例如:perl Hello.pl
  • @Aakashk.u:我已经编辑了答案以包含您所问的内容,尽管它“超出了原始问题的范围”。如果它达到目的或对您有帮助,请“将答案标记为已接受”。
猜你喜欢
  • 2014-02-15
  • 2013-04-16
  • 1970-01-01
  • 1970-01-01
  • 2017-05-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-19
  • 1970-01-01
相关资源
最近更新 更多