it-source

Python을 사용하여 cURL 명령을 실행하는 방법은 무엇입니까?

criticalcode 2022. 11. 20. 12:17
반응형

Python을 사용하여 cURL 명령을 실행하는 방법은 무엇입니까?

Python에서 curl 명령어를 실행하고 싶습니다.

보통 단말기에 명령어를 입력하고 리턴 키를 누르면 됩니다.하지만 Python에서는 어떻게 동작하는지는 모릅니다.

이 명령어는 다음과 같습니다.

curl -d @request.json --header "Content-Type: application/json" https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere

이 있습니다.request.json응답을 받기 위해 전송되는 파일입니다.

많이 검색해서 헷갈렸어요.나는 코드를 하나 써보려고 했지만, 완전히 이해할 수 없었고 동작도 하지 않았다.

import pycurl
import StringIO

response = StringIO.StringIO()
c = pycurl.Curl()
c.setopt(c.URL, 'https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere')
c.setopt(c.WRITEFUNCTION, response.write)
c.setopt(c.HTTPHEADER, ['Content-Type: application/json','Accept-Charset: UTF-8'])
c.setopt(c.POSTFIELDS, '@request.json')
c.perform()
c.close()
print response.getvalue()
response.close()

에러 메세지는 다음과 같습니다.Parse Error서버로부터 올바른 응답을 얻는 방법

알기 쉽게 하기 위해 요청 라이브러리를 사용하는 것이 좋습니다.

json 응답 내용의 예는 다음과 같습니다.

import requests
r = requests.get('https://github.com/timeline.json')
r.json()

자세한 내용은 Quickstart 섹션에 많은 작업 예가 나와 있습니다.

편집:

특정 컬 번역의 경우:

import requests
url = 'https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere'
payload = open("request.json")
headers = {'content-type': 'application/json', 'Accept-Charset': 'UTF-8'}
r = requests.post(url, data=payload, headers=headers)

그냥 이 웹사이트를 이용하세요.모든 curl 명령어를 Python, Node.js, PHP, R 또는 Go로 변환합니다.

예:

curl -X POST -H 'Content-type: application/json' --data '{"text":"Hello, World!"}' https://hooks.slack.com/services/asdfasdfasdf

Python에서는 이렇게 됩니다.

import requests

headers = {
    'Content-type': 'application/json',
}

data = '{"text":"Hello, World!"}'

response = requests.post('https://hooks.slack.com/services/asdfasdfasdf', headers=headers, data=data)
curl -d @request.json --header "Content-Type: application/json" https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere

Python 구현은 다음과 같습니다.

import requests

headers = {
    'Content-Type': 'application/json',
}

params = (
    ('key', 'mykeyhere'),
)

data = open('request.json')
response = requests.post('https://www.googleapis.com/qpxExpress/v1/trips/search', headers=headers, params=params, data=data)

#NB. Original query string below. It seems impossible to parse and
#reproduce query strings 100% accurately so the one below is given
#in case the reproduced version is not "correct".
# response = requests.post('https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere', headers=headers, data=data)

링크체크하면 cURL 명령어를 python, php 및 nodejs로 변환하는 데 도움이 됩니다.

import requests
url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere"
data = requests.get(url).json

아마도요?

파일을 송신하려고 하는 경우

files = {'request_file': open('request.json', 'rb')}
r = requests.post(url, files=files)
print r.text, print r.json

아, 고마워 @LukasGraf 이제 나는 그의 원래 코드가 무엇을 하는지 더 잘 이해할 수 있어.

import requests,json
url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere"
my_json_data = json.load(open("request.json"))
req = requests.post(url,data=my_json_data)
print req.text
print 
print req.json # maybe? 

제 대답은 WRT python 2.6.2입니다.

import commands

status, output = commands.getstatusoutput("curl -H \"Content-Type:application/json\" -k -u (few other parameters required) -X GET https://example.org -s")

print output

기밀이기 때문에 필요한 파라미터를 제공하지 못해 죄송합니다.

일부 배경:콘텐츠를 검색하기 위해 뭔가 조치를 취해야 했기 때문에 이 질문을 찾아봤지만 SSL 지원이 불충분한 오래된 버전의 python밖에 없었습니다.구형 MacBook을 사용하시는 분들은 아시겠죠?어쨌든curl셸에서 정상적으로 동작하기 때문에(아마 최신 SSL 지원이 링크되어 있을 것으로 생각됩니다).따라서 를 사용하지 않고 이 작업을 수행할 수 있습니다.requests또는urllib2.

를 사용할 수 있습니다.subprocess실행할 모듈curl취득한 컨텐츠를 입수할 수 있습니다.

import subprocess

// 'response' contains a []byte with the retrieved content.
// use '-s' to keep curl quiet while it does its job, but
// it's useful to omit that while you're still writing code
// so you know if curl is working
response = subprocess.check_output(['curl', '-s', baseURL % page_num])

파이썬 3의subprocessmodule에도 포함되어 있습니다..run()여러 가지 유용한 옵션이 있습니다.python 3를 실제로 실행하고 있는 사람에게 답변을 맡기겠습니다.

사용하고 있다os도서관.

import os

os.system("sh script.sh")

script.sh말 그대로 컬만 들어있어요.

PYTON 3

UNIX(Linux/Mac) 내에서만 기능(!

Python 3에서 cURL을 실행하고 해당 JSON 데이터를 구문 분석합니다.

import shlex
import json
import subprocess

# Make sure that cURL has Silent mode (--silent) activated
# otherwise we receive progress data inside err message later
cURL = r"""curl -X --silent POST http://www.test.testtestest/ -d 'username=test'"""

lCmd = shlex.split(cURL) # Splits cURL into an array

p = subprocess.Popen(lCmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate() # Get the output and the err message

json_data = json.loads(out.decode("utf-8"))

print(json_data) # Display now the data

경우에 따라서는, 이상한 에러가 발생했을 경우는, UNIX 에 다음의 의존 관계를 인스톨 할 필요도 있습니다.

# Dependencies  
sudo apt install libcurl4-openssl-dev libssl-dev
sudo apt install curl

컬을 지원하는 경우 다음과 같은 작업을 수행할 수 있습니다.

import os

os.system("curl -d @request.json --header "Content-Type: application/json" https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere")

이렇게 쓰고 있는데...그리고 이것도 쓸 수 있을 것 같아!

그나저나..모듈 "os"는 python을 설치할 때 자동으로 설치됩니다. soo, 패키지를 설치할 필요가 없습니다.

「 」의 requests에서는 다음과같은 를 얻을 수 .

curl -LH "Accept: text/x-bibliography; style=apa" https://doi.org/10.5438/0000-0C2G

다음과 같이 합니다.

import requests

headers = {
    'Accept': 'text/x-bibliography; style=apa',
}

r = requests.get('https://doi.org/10.5438/0000-0C2G', headers=headers)


print(r.text)

다음은 한 가지 접근법입니다.

Import os
import requests 
Data = os.execute(curl URL)
R= Data.json()

언급URL : https://stackoverflow.com/questions/25491090/how-to-use-python-to-execute-a-curl-command

반응형