如何使用选项从 python 执行脚本

how to execute script from python with options

我需要通过 python 执行以下命令 运行。

/work/data/get_info name=Mike home

我收到的错误是 No such file or directory: '/work/data/get_info name=Mike home'。这是不正确的。 get_info 程序确实退出了。 它在 perl 脚本中工作 我试图在 python.

中获得相同的功能

perl 脚本

$ENV{work} = '/work/data';
my $myinfo = "$ENV{work}/bin/get_info";
$info = `$myinfo name=Mike home`;

Info转储信息

我的python脚本

import os, subprocess

os.environ['work'] = '/work/data'
run_info = "{}/bin/get_info name={} {}".format(os.environ['work'],'Mike','home')
p = subprocess.call([run_product_info], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()

我收到一个错误 No such file or directory: '/work/data/get_info name=Mike

Python subprocess.call 认为整个字符串是程序的名称,就好像你像 "/work/data/get_info name=Mike home" 那样用双引号将它作为数组传递。

要么在没有 shell 数组的情况下传递它(如果您确定所有 escaping/quoting 都是正确的,请参阅文档中的警告),要么将每个元素作为单独的数组元素传递。

subprocess.call(['/work/data/bin/get_info', 'name=Mike', 'home'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
subprocess.call('/work/data/bin/get_info name=Mike home', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)

https://docs.python.org/3.7/library/subprocess.html#frequently-used-arguments

args is required for all calls and should be a string, or a sequence of program arguments. Providing a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names). If passing a single string, either shell must be True (see below) or else the string must simply name the program to be executed without specifying any arguments.