[英]How to use variables from shell script in python script file?
我有一個 shell 腳本,它有一個運行 python 腳本的命令。 我想在 python 腳本中使用來自 shell 腳本的 4 個變量(例如:var1,var2,var3,var4)。 任何建議如何做到這一點?
例如:我想用 shell 腳本中的變量替換"lastTest44"
、 firstTest44
和A-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()
只需使用命令行參數:
外殼腳本
a=1
b=2
python test1.py "$a" "$b"
Python腳本
import sys
var1 = sys.argv[1]
var2 = sys.argv[2]
print var1, var2
您要使用的稱為命令行參數。 這些是在調用您要運行的特定代碼段時指定的參數。
在 Python 中,這些可以通過名為argv
的變量下的sys
模塊訪問。 這是一個包含從調用者傳入的所有參數的數組,其中數組中的每個值都是一個字符串。
例如,假設我正在編寫的代碼接受參數來繪制一個正方形。 這可能需要 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.
需要注意的幾點:
string
類型。 這意味着在這種情況下,在將它們轉換為我想要的正確類型之前,我無法執行任何算術運算。sys.argv
的第一個參數是正在運行的腳本的名稱。 您需要確保從數組sys.argv[1]
的第二個位置開始讀取,而不是像通常那樣從典型的第零個索引開始讀取。這里有一些更詳細的信息,可以引導您更好地處理命令行參數。 不過,要開始使用,這已經足夠了。
我認為這會做你想做的:
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'
我想添加對我的案例有用的內容:
我的文件中有我的變量,該文件來源於 shell 腳本。 需要將變量從同一個文件傳遞給 python。 在我的情況下,我也有 pandas 和 spark 我的預期結果是連接傳遞“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+")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.