如何将Bash变量作为Python参数传递 [英] How to pass Bash variables as Python arguments

查看:50
本文介绍了如何将Bash变量作为Python参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出是否有可能将存储在Bash变量中的值作为python脚本中的参数值传递.

我们有一个python脚本,可用于在BIND中创建DNS记录,我的任务是清理过时的DNS数据库.到目前为止,我在bash中有这样的东西:

  HOSTNAMES = $(</Users/test/test.txt)ZONE =此处为区域名称"IP = $(</Users/test/iptest.txt)用于$ HOSTNAMES中的主机做python pytest.py --host $ HOSTNAMES --zone $ ZONE --ip $ IP完毕 

不幸的是,我没有测试环境可以在产品上运行它之前对其进行测试,并且我对Python或Bash脚本没有任何经验.我主要只做过Powershell脚本编写,但想知道像我上面的内容是否行得通.

我在这里的论坛上四处逛逛,但没有发现我可以理解的任何东西.这篇文章似乎在某种程度上回答了我的问题,但是我仍然不确定这是如何工作的.如何将Bash变量传递给Python?

解决方案

是的,对我来说似乎很好.

为了进行测试,我整理了一个非常快速的python脚本,称为test.py:

 #!/usr/bin/python导入系统打印'参数数量:',len(sys.argv)#我们知道sys.argv [0]是脚本名称,让我们看一下sys.argv [1]打印sys.argv [1] 

然后,在您的终端中,设置一个变量:

 > testvar ="TESTING" 

尝试您的脚本,将变量传递到脚本中:

 > python test.py $ testvar>参数数量:2>测试 

诚然,我对Python并不精通,但这确实可以实现您想要的功能.就是说,这假设您所引用的Python脚本已经设置好了,可以解析传递给它的参数的名称-您会注意到我的测试脚本没有这样做,它只是吐出了您传递给它的所有内容.

I'm trying to figure out if it is possible to pass values stored in a variable in Bash in as argument values in a python script.

We have a python script that we use to create DNS records in BIND and I've been tasked with cleaning up our outdated DNS database. so far I have something like this in bash:

HOSTNAMES=$(</Users/test/test.txt)

ZONE="zone name here"

IP=$(</Users/test/iptest.txt)

for host in $HOSTNAMES
do
  python pytest.py --host $HOSTNAMES --zone $ZONE --ip $IP
done

Unfortunately, I don't have a test environment where I can test this on before I run it on prod and I don't have any experience with Python or Bash scripting. I've mainly only done Powershell scripting, but was wondering if something like what I have above would work.

I've looked around on the forums here but have not found anything that I could make sense of. This post seems to answer my question somewhat, but I'm still not completely sure how this works. How to pass a Bash variable to Python?

解决方案

Yes, seems to work just fine to me.

To test, I threw together a very quick python script called test.py:

#!/usr/bin/python
import sys

print 'number of arguments: ', len(sys.argv)
#we know sys.argv[0] is the script name, let's look at sys.argv[1]
print sys.argv[1]

Then, in your terminal, set a variable:

>testvar="TESTING"

And try your script, passing the variable into the script:

>python test.py $testvar
>number of arguments: 2
>TESTING

Admittedly I'm not very well-versed in Python, but this did seem to accomplish what you wanted. That said, this assumes the Python script you referenced is already set up to parse the names of the parameters being passed to it - you'll notice my test script does NOT do that, it simply spits out whatever you pass into it.

这篇关于如何将Bash变量作为Python参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆