[英]How to turn arbitrary number of strings into function arguments in python
我正在從csv接收數據,並希望將其轉換為python函數的參數。 例如,如果csv說
12, foo=20, bar=30
10, foo=17, bar=40, baz=12
我想用f(12, foo=20, bar=30)
和f(10, foo=17, bar=40, baz=12)
兩次調用我的函數。 我無法真正修改功能(我實際上是在使用請求庫,並將此CSV轉換為一系列請求)。 從CSV中提取字符串很容易,但是將它們轉換為適當的函數調用似乎並不容易。
現在,我基本上擁有的是:
with open('request.csv') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
response = requests.get(row[0], row[1], row[2], row[3])
但這不適用於應讀取“ auth = X”或類似內容的參數,也不適用於可變數量的參數。
line1 = '12, foo=20, bar=30'
line2 = '10, foo=17, bar=40, baz=12'
for line in [line1, line2]:
args = line.split(',')
# key named arguments (ignore first, bc it is unnamed)
named_args = {k.strip(): v.strip() for k, v in (x.split('=') for x in args[1:])}
# call your method
method_to_call(args[0], **named_args)
編輯:我在開發環境上測試了代碼,並進行了有針對性的更新。 現在它應該可以正常工作了。
def func(i, foo=0, bar=4):
print(i, foo, bar)
row = '12, foo=20, bar=30'
args, kargs = [], {}
for arg in row.split(','):
arg = arg.strip()
if '=' in arg:
key, value = arg.split('=')
kargs[key.strip()] = value.strip()
else:
args.append(arg)
func(*args, **kargs)
非常危險的解決方案:
def func(i, foo=0, bar=4):
print(i, foo, bar)
row = '12, foo=20, bar=30'
eval('func(%s)' % row)
# Dangerous use:
row = '12, foo=20); sys.exit(0'
eval('func(%s)' % row)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.