You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中执行curl命令?含指定curl命令实现需求

Translating Your curl Command to Python

Let's walk through how to replicate this curl command in Python— I'll cover two common approaches, depending on whether you want to use a popular third-party library or stick to built-in tools.

Your original curl command:

curl -H 'Content-Type: application/x-ndjson' -XPOST '192.168.1.149:9200/shakespeare/doc/_bulk?pretty' --data-binary @file.json

This is the most straightforward and readable way, since requests abstracts away a lot of the low-level HTTP stuff. First, make sure you have it installed:

pip install requests

Then here's the equivalent Python code:

import requests

# Define the target URL and headers
url = 'http://192.168.1.149:9200/shakespeare/doc/_bulk?pretty'
headers = {'Content-Type': 'application/x-ndjson'}

# Read the file in binary mode (matches --data-binary)
with open('file.json', 'rb') as f:
    data = f.read()

# Send the POST request
try:
    response = requests.post(url, headers=headers, data=data)
    # Print the pretty-printed response (since we added ?pretty to the URL)
    print(response.text)
except requests.exceptions.RequestException as e:
    print(f"An error occurred: {e}")

Breakdown:

  • headers maps directly to the -H flag in curl
  • requests.post() handles the -XPOST method
  • Reading the file with rb mode ensures we send binary data, just like --data-binary
  • The try/except block catches common issues like network errors or invalid responses

Approach 2: Using Built-in urllib.request (No Extra Installs)

If you can't or don't want to install external libraries, Python's standard library has you covered with urllib:

import urllib.request

url = 'http://192.168.1.149:9200/shakespeare/doc/_bulk?pretty'
headers = {'Content-Type': 'application/x-ndjson'}

# Read the file binary data
with open('file.json', 'rb') as f:
    data = f.read()

# Create the request object
req = urllib.request.Request(url, data=data, headers=headers, method='POST')

try:
    with urllib.request.urlopen(req) as response:
        # Read and decode the response
        print(response.read().decode('utf-8'))
except urllib.error.URLError as e:
    print(f"An error occurred: {e}")

Breakdown:

  • We create a Request object that specifies the URL, data, headers, and method (POST)
  • urlopen() sends the request, and we read/decode the response to get the human-readable output
  • This does the exact same thing as the curl command, just using Python's built-in tools

Either of these should work perfectly for your use case. The requests approach is generally preferred for its simplicity and cleaner syntax, but the urllib method is great for environments where you can't install additional packages.

内容的提问来源于stack exchange,提问作者Prophet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:19:54