我正在尝试使用通过我的python文件使用命令行工作的api。我之前导入了各种python文件,但是这个文件导致了一些问题,因为我无法通过我的文件传递命令行参数......
api调用是这样的:
python bin/pythonapi.py -K 72387bc9236d73-13c1-4r1g-83c8-26329b981147 --samples -j -r '{"query":{"operator":"all","children":[{"field":"alias.ip_address","operator":"contains","value":"192.168.1.60"}]},"scope":"private","size":50,"from":0,"sort":{"sha256":{"order":"asc"}}}'
API调用正常。但是当我尝试使用我的文件调用它时,它不起作用给我一个跟踪调用说:
TypeError: main() takes 0 positional arguments but 1 was given
我知道这意味着main()函数在这里没有参数,但是API调用是如何工作的?
用于调用此API的Python文件的代码是:
import os, sys
sys.path.append('/root/CARS/test/python-master/bin')
import pythonapi as panaf
sys.argv = '-K 72387bc9236d73-13c1-4r1g-83c8-26329b981147 --samples -j -r \'{"query":{"operator":"all","children":[{"field":"alias.ip_address","operator":"contains","value":"192.168.1.60"}]},"scope":"private","size":50,"from":0,"sort":{"sha256":{"order":"asc"}}}\''.split()
sys.argv = ['pythonapi.py'] + sys.argv
response = panaf.main()
print(response)
result = json.loads(response.text)
print(result)
我想传递通过Python文件调用API所需的参数。我希望这是可能的,只是因为我不知道正确的方式......
如果有人能告诉我我做错了什么,如何解决这个问题会很棒。提前谢谢。
修改-1: 在提出一些建议之后,我的代码稍作修改。但是出现了一个新的追溯电话:
Expecting value: line 1 column 1 (char 0): '{"query":{"operator":"all","children":[{"field":"alias.ip_address","operator":"contains","value":"192.168.1.60"}]},"scope":"private","size":50,"from":0,"sort":{"sha256":{"order":"asc"}}}'
出于某种原因,它说我传递的json参数是错误的。是这样,还是整个逻辑都错了?
答案 0 :(得分:1)
您面临的问题是:
sys.argv = '-K 72387bc9236d73-13c1-4r1g-83c8-26329b981147 --samples -j -r \'{"query":{"operator":"all","children":[{"field":"alias.ip_address","operator":"contains","value":"192.168.1.60"}]},"scope":"private","size":50,"from":0,"sort":{"sha256":{"order":"asc"}}}\''.split()
,提供
['-K',
'72387bc9236d73-13c1-4r1g-83c8-26329b981147',
'--samples',
'-j',
'-r',
'\'{"query":{"operator":"all","children":[{"field":"alias.ip_address","operator":"contains","value":"192.168.1.60"}]},"scope":"private","size":50,"from":0,"sort":{"sha256":{"order":"asc"}}}\'']
你的json参数中有'\'
导致问题。
你不需要逃避-r。
的单引号这是你可以做的。
sys.argv = '-K 72387bc9236d73-13c1-4r1g-83c8-26329b981147 --samples -j -r {"query":{"operator":"all","children":[{"field":"alias.ip_address","operator":"contains","value":"192.168.1.60"}]},"scope":"private","size":50,"from":0,"sort":{"sha256":{"order":"asc"}}}'.split()
会导致:列表中没有'\'
['-K',
'72387bc9236d73-13c1-4r1g-83c8-26329b981147',
'--samples',
'-j',
'-r',
'{"query":{"operator":"all","children":[{"field":"alias.ip_address","operator":"contains","value":"192.168.1.60"}]},"scope":"private","size":50,"from":0,"sort":{"sha256":{"order":"asc"}}}']
希望这有帮助