【问题标题】:How I can pass bash variable inside python command?如何在 python 命令中传递 bash 变量?
【发布时间】:2022-01-08 07:17:45
【问题描述】:

我想在 python 命令中传递变量 server 并从命令中读取 python 命令结果 portStatus 变量。

for server in `echo $dnsServers | awk -F";" '{print $1" "$2" "$3" "$4" "$5" "$6}'`
  do
    python3 -c 'import socket;
    a_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
    host=("$server", 53); 
    portStatus=a_socket.connect_ex(host);'
  done
echo $portStatus


收到此错误:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
socket.gaierror: [Errno -2] Name or service not known
Traceback (most recent call last):
  File "<string>", line 1, in <module>
socket.gaierror: [Errno -2] Name or service not known
Traceback (most recent call last):

【问题讨论】:

    标签: linux sockets networking


    【解决方案1】:

    依靠在 Python 语句中扩展变量不是一个好主意,因为该语句需要以字符串形式给出,其中可以扩展 shell 变量(即使用双引号而不是单引号)并且所有内容都需要正确转义这样外壳就不会解释它不应该解释的东西。这可能非常复杂。

    更简单的方法是将变量作为附加的命令行参数提供,然后使用sys.argv 访问该参数,如下所示:

    for i in a b c d ; do 
        python3 -c 'import sys; print(sys.argv[1]);' $i
    done
    

    要获取单行值,请将 python 代码的结果捕获到 shell 变量中:

    for i in a b c d ; do 
        foo=`python3 -c 'import sys; print("in python: " + sys.argv[1]);' $i`
        echo "in shell: $foo"
    done
    

    结果:

    in shell: in python: a
    in shell: in python: b
    in shell: in python: c
    in shell: in python: d
    

    【讨论】:

      猜你喜欢
      • 2013-07-02
      • 1970-01-01
      • 2019-06-22
      • 2012-10-01
      • 2017-06-15
      • 2012-10-21
      • 1970-01-01
      • 2014-10-06
      • 1970-01-01
      相关资源
      最近更新 更多