如何在python脚本文件中使用shell脚本中的变量?

时间:2014-06-05 01:22:54

标签: python bash

我有一个shell脚本,它有一个运行python脚本的命令。我想要在shell脚本中使用4个变量(例如:var1,var2,var3,var4)在python脚本中使用。有什么建议怎么做?

例如:我想用shell脚本中的变量替换"lastTest44"firstTest44A-S00000582

driver.find_element_by_id("findKey_input").clear() 
driver.find_element_by_id("findKey_input").send_keys("lastTest44") 
driver.find_element_by_id("ST_View_lastTest44, firstTest44").click() 
driver.find_element_by_link_text("A-S00000582").click() 

4 个答案:

答案 0 :(得分:4)

只需使用命令行参数:

Shell脚本

a=1
b=2
python test1.py "$a" "$b"

Python脚本

import sys
var1 = sys.argv[1]
var2 = sys.argv[2]
print var1, var2

答案 1 :(得分:0)

您要使用的内容称为命令行参数。这些是在调用您要运行的特定代码时指定的参数。

在Python中,可以通过名为sys的变量下的argv模块访问这些内容。这是从调用者传入的所有参数的数组,其中数组中的每个值都是一个字符串。

例如,假设我正在编写的代码采用参数来绘制正方形。这可能需要4个参数 - 一个x坐标,y坐标,一个宽度和一个高度。这个的Python代码可能如下所示:

import sys
x = sys.argv[1]
y = sys.argv[2]
width = sys.argv[3]
height = sys.argv[4]

# Some more code follows.

有几点需要注意:

  1. 每个参数都是string类型。这意味着在这种情况下,在将它们转换为我想要的正确类型之前,我无法执行任何算术。
  2. sys.argv中的第一个参数是正在运行的脚本的名称。您需要确保从数组sys.argv[1]中的第二个位置开始读取,而不是像通常那样从典型的第零个索引开始读取。
  3. There is some more detailed information here,它可以引导您更好地处理命令行参数。但是要开始,这样就可以了。

答案 2 :(得分:0)

我认为这会做你想做的事情:

2014-06-05 09:37:57 [tmp]$ export VAR1="a"
2014-06-05 09:38:01 [tmp]$ export VAR2="b"
2014-06-05 09:38:05 [tmp]$ export VAR3="c"
2014-06-05 09:38:08 [tmp]$ export VAR4="d"
2014-06-05 09:38:12 [tmp]$ python
Python 2.7.3 (default, Feb 27 2014, 19:58:35) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from os import environ
>>> environ['VAR1']
'a'
>>> environ['VAR2']
'b'
>>> environ['VAR3']
'c'
>>> environ['VAR4']
'd'
>>> environ['VAR5']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/UserDict.py", line 23, in __getitem__
    raise KeyError(key)
KeyError: 'VAR5'

请记住捕获KeyError并相应地做出响应或使用get方法(来自dict类)并指定当密钥不存在时使用的默认值:

>>> environ.get('VAR5', 'not present')
'not present'

更多: https://docs.python.org/2/library/os.html

答案 3 :(得分:0)

我想补充适用于我的情况的

我的变量在文件中,该文件是从Shell脚本获取的。 需要将变量从同一文件传递给python。 我也有熊猫和火花 我的预期结果是连接实现“ tocsv”的路径

**Shell**:
. path/to/variable/source file # sourcing the variables
python path/to/file/extract.py "$OUTBOUND_PATH"


**Python**:
import sys
import pandas as pd
#If spark session is involved import the sparksession as well

outbound_path=sys.argv[1] #argument is collected from the file passed through shell
file_name="/report.csv"

geo.topandas().tocsv(outbound_path+file_name,mode="w+")