简体   繁体   English

subprocess.call()格式问题

[英]subprocess.call() formatting issue

I am very new to subprocess , and I have a hard debugging it without any error code. 我对subprocesssubprocess ,并且很难调试它,没有任何错误代码。

I'm trying to automatically call an API which respond to : 我正在尝试自动调用响应的API:

http -f POST https://api-adresse.data.gouv.fr/search/csv/ columns=voie columns=ville data@path/to/file.csv > response_file.csv

I've tried various combination with subprocess.call , but I only manage to get "1" as an error code. 我尝试了与subprocess.call各种组合,但我只能设法将“ 1”作为错误代码。 What is the correct way to format this call, knowing that the answer from the API has to go in a csv file, and that I send a csv (path after the @data)? 知道该API的答案必须放在一个csv文件中并且我发送一个csv(@data之后的路径)的情况下,格式化此调用的正确方法是什么?

EDIT: Here are my attempts : 编辑:这是我的尝试:

ret = subprocess.call(cmd,shell=True)
ret = subprocess.call(cmd.split(),shell=True)
ret = subprocess.call([cmd],shell=True)
  • The same with shell = False , and with stdout = myFileHandler (open inside a with open(file,"w") as myFileHandler:) 与shell = False和stdout = myFileHandler相同(在内部以open(file,“ w”)作为myFileHandler打开:)

EDIT2 : still curious about the answer, but I managed to go around with Request, as @spectras suggested EDIT2:仍然对答案感到好奇,但我设法解决了Request,如@spectras建议

file_path =  "PATH/TO/OUTPUT/FILE.csv"
url = "https://api-adresse.data.gouv.fr/search/csv/"
files = {'data': open('PATH/TO/CSV/FILE.csv','rb')}
values = {'columns': 'Adresse', 'columns': 'Ville', 'postcode': 'CP'}
r = requests.post(url, files=files, data=values)
with open(file_path, "w") as myFh:
   myFh.write(r.content)

Since you are attempting to send a form, may I suggest you do it straight from python? 由于您正在尝试发送表单,因此我建议您直接从python进行发送吗?

import requests

with open('path/to/file', 'rb') as fd:
    payload = fd.read()

r = requests.post(
    'https://api-adresse.data.gouv.fr/search/csv/',
    data=(
        ('columns', 'voie'),
        ('columns', 'ville'),
    ),
    files={
        'data': ('filename.csv', payload, 'text/csv'),
    }
)
if r.status_code not in requests.codes.ok:
    r.raise_for_status()

with open('response_file.csv', 'wb') as result:
    result.write(r.content)

This uses the ubiquitous python-requests module, and especially the form file upload part of the documentation. 这使用了无处不在的python-requests模块,尤其是文档的表单文件上传部分。

It's untested. 未经测试。 Basically, I opened httpie documentation and converted your command line arguments into python-requests api arguments. 基本上,我打开了httpie文档,并将您的命令行参数转换为python-requests api参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM