繁体   English   中英

从 bash 脚本作为数组访问 python 脚本返回值

[英]Accessing python script return value from bash script as an array

我有一个 bash 命令如下:

($(echo my-profiles --my-profiles pytest))

上面的 bash 命令从 python 脚本返回一个数组,如下所示:

['mock-alchemy', 'pytest-mock', 'pytest-datafixtures', 'pytest-describe', 'pytest-unordered', 'requests-mock']

这个例子的答案中,我访问的返回值如下:

dependencies=($(echo /path/to/my-script.py --my-profiles pytest}))

当我从dependencies访问返回值时,我得到以下结果:

> echo ${dependencies[0]}
my-profiles

我怎样才能得到'mock-alchemy'而不是上述结果?

我的 python 脚本如下:

my-script.py
def main():
    parser = argparse.ArgumentParser(description='My script')
    parser.add_argument('--tox-profiles', dest="profiles", 
                        type=str,
                        default='')
    parsed_args = parser.parse_args()
    dependencies = get_dependencies(args.profiles)

def get_dependencies(profiles):
    return ['mock-alchemy', 'pytest-mock', 'pytest-datafixtures', 'pytest-describe', 'pytest-unordered', 'requests-mock']

($(echo my-profiles --my-profiles pytest))

(... )执行一个子shell。 然后$(... )执行echo 命令echo输出my-profiles --my-profiles pytest 然后$(...)的结果进行分词扩展my-profiles --my-profiles pytest被分成三个词my-profiles --my-profiles pytest 然后拆分的结果就像“重新扫描”一样,变成了新的命令来执行,所以执行了my-profiles 它实际上输出程序的 output 。

这一切都令人费解。 只需运行my-profiles --my-profiles pytestecho在那里做什么?

 dependencies=($(echo my-profiles --my-profiles pytest))

dependencies=(... )是一个数组赋值。 首先将$(...)替换为里面命令的output。 echo my-profiles --my-profiles pytest输出my-profiles --my-profiles pytest 然后结果my-profiles --my-profiles pytest是单词拆分,变成 3 个单词,每个单词分配给一个单独的数组元素。

我怎样才能得到“模拟炼金术”而不是上述结果?

如果您打算在机器上使用它们,您应该以机器可读格式 output 工具中的数据。 因为它们很容易,你可以 output 例如空格分隔的数据。

def get_dependencies(profiles):
    return ' '.join([
       'mock-alchemy', 'pytest-mock', 'pytest-datafixtures', 'pytest-describe', 'pytest-unordered', 'requests-mock'
       ])

# actually print it too!
print(get_dependencies(None))

然后您可以读取 bash 中的空格分隔值:

output=$(my-profiles --my-profiles pytest)
IFS=' ' read -r -a arr <<<"$output"
declare -p arr
echo "${arr[0]}"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM