【问题标题】:How to pass a list of strings from python to shell script?如何将字符串列表从 python 传递到 shell 脚本?
【发布时间】:2020-09-29 09:07:54
【问题描述】:

我需要将字符串列表从 python 传递到 shell 脚本。

目标: 在 Shell 脚本中,

1)shell 脚本应该接受作为参数传递的字符串列表。

2)我需要循环该列表并打印循环内的字符串。

我尝试过的:

main.py

import subprocess
ssh_key_path = #KEY_PATH
ip_address = #BASTION_IP
Details = #Somedata
list_1 = ["apple","banana","carrot"]
script = subprocess.call([sh,fruits.sh,ssh_key_path,ip_address,Details,list_1])

fruits.sh

ssh -i $1 ubuntu@$2 -o StrictHostKeyChecking=no << EOF
   printf $3 >/home/Details.txt
   fruits = $4
   for i in $4; do
     echo "$i"
   done
   echo "Success" 
EOF

输出来自 fruits.sh:(预期输出)

apple
banana
carrot
Success

错误: 预期的 str、bytes 或 os.PathLike 对象,而不是列表。

那么,如何将列表传递给shell脚本并在其中执行?

【问题讨论】:

    标签: python bash list shell parameters


    【解决方案1】:

    只需加入空格即可。例如:

    test.py

    import subprocess
    
    fruits = ["apple","banana","carrot"]
    
    subprocess.call(["sh", "test.sh", "hello", " ".join(fruits)])
    

    test.sh

    echo "greeting: $1"
    
    for i in $2
    do
        echo "fruit: $i"
    done
    

    输出:

    greeting: hello
    fruit: apple
    fruit: banana
    fruit: carrot
    

    这里的基本点是您传递一个字符串参数,然后您的 shell 脚本会根据需要拆分它。

    但是如果你不能使用空格作为分隔符,那么你将不得不使用多个参数。例如:

    test.py

    import subprocess
    
    fruits = ["green apple", "yellow banana", "orange carrot"]
    
    subprocess.call(["sh", "./test.sh", "hello"] + fruits)
    

    test.sh

    echo "greeting: $1"
    
    shift
    
    for i in "$@"
    do
        echo "fruit: $i"
    done
    

    输出:

    greeting: hello
    fruit: green apple
    fruit: yellow banana
    fruit: orange carrot
    

    在这里,shell 脚本中的shift 将从参数列表中删除第一个参数,以便"$@" 将循环剩余的参数。 (根据需要多次重复shift。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-28
      • 1970-01-01
      • 2017-08-06
      • 2021-09-20
      • 1970-01-01
      相关资源
      最近更新 更多