gpt4 book ai didi

python - 将列表作为变量从bash脚本传递给python脚本

转载 作者:行者123 更新时间:2023-12-04 16:18:22 27 4
gpt4 key购买 nike

我有一个像下面这样的python脚本。

# Import necessary libraries and functions
import sys
import traceback

y = '2020'
querysting = "select {} from table where Year={}".format(col_list,y)
df = pd.read_sql(querystring,db)


if __name__ == '__main__':
if len(sys.argv) != 8:
print('Invalid number of args......')
print('Usage: file.py Input_path Output_path')
exit()
_, col_list, FinalDB, final_table, host, dsl_tbl_name, username, password = tuple(sys.argv)

data_load(col_list, FinalDB, final_table, host, tbl_name, username, password)

现在我在 shell 脚本中调用这个 python 脚本,如下所示
#!/bin/bash

col_list='id, name, address, phone_number'
FinalDB='abc'
final_table='xyz'
host='xxxxxx.xxxx'
tbl_name='test'
username='USER'
password='test_pass'


python python_script.py ${col_list} ${FinalDB} ${final_table} ${host} ${tbl_name} ${username} ${password}

现在,当我运行这个 bash 脚本时,我得到了 Invalid number of args......错误

我很确定这与 col_list 有关。传递给 python 的变量脚本。

因为如果我只是通过 select * 而不是在列表中包含列在查询和删除 col_list变量然后我没有收到任何错误

我在这里做错了什么,我该如何解决这个问题。

最佳答案

问题来自于您如何传递包含来自 Bash 的空格的变量。至 Python .

你可能注意到:

In shell scripts command line arguments are separated by whitespace, unless the arguments are quoted.



让我们来个简单的 Python脚本:

python_script.py:
import sys

if __name__ == '__main__':
print(sys.arv)

然后在您的终端中:
$> export var1="hello"
$> python python_script.py $var1
['python_script.py', 'hello']

然而:
$> export var1="hello, hi"
$> python python_script.py $var1
['python_script.py', 'hello,', 'hi'] # Note Here: Two args were passed
$> export var1="hello,hi"
$> python python_script.py $var1
['python_script.py', 'hello,hi'] # One arg passed

因此,解决您的问题的方法是通过您的 Bash args 作为字符串,即使有空格,就像这个例子:
$> export var1="hello, hi, hola"
$> python python_script.py "$var1"
['python_script.py', 'hello, hi, hola']

有关更多信息,请参阅此 article

关于python - 将列表作为变量从bash脚本传递给python脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61859812/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com