Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23131

Trouble executing curl command in Python subprocess

$
0
0

I'm attempting to execute a curl command within a Python script using the subprocess module. However, I'm encountering issues with the execution and receiving inconsistent results. Here's the code snippet I'm using:

# Handler for the "/show_account_info" command@bot.message_handler(commands=['show_account_info'])def show_account_info(message):    try:        with open(f"{message.from_user.id}.txt", "r") as file:            api_key = file.read().strip()        curl_command = f"""        curl -X 'GET' \\'https://api.website.com/v1/system/account' \\          -H 'accept: application/json' \\"-H", f"X-API-Key: {api_key}""""        print(f"Executing curl command: {curl_command}")  # Print the curl command being executed        process = subprocess.Popen(curl_command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)        output, error = process.communicate()        print(output.decode('utf-8'))  # Print the JSON response        if process.returncode != 0:            print(f"Error executing curl command: {error.decode('utf-8')}")  # Print any error message from curl    except FileNotFoundError:        print("Error: API Key not set. Use 'Set API Key' to set your API Key.")    except Exception as e:        print(f"An error occurred: {e}")  # Print any other exception to the console

My terminal shows the command was received by the Telegram API, however, the curl isn't executed properly.

2024-04-22 22:41:43 - INFO - Received message from user user_id: Show Account Information

Other similar CURL commands, it works fine. But for this, it doesn't work and doesn't give me any error information. I can't figure out why it's not consistent. I've looked at the API key and made sure the curl command is written correctly, but I still have this issue.

For example, here's a working CURL command, that retrieves information for the task ID:

    curl_command = ["curl", "-X", "GET",        f"https://api.website.com/v1/task?id={task_id}","-H", "accept: application/json","-H", f"X-API-Key: {api_key}"    ]

Any insights or suggestions would be greatly appreciated. Thank you!

What I tried:I attempted to execute a curl command within my Python script using the subprocess.Popen function.

Expected outcome:I expected the curl command to execute successfully and return the desired output from the API.

Actual result:Curl command executed without any issues ran via terminal, and I received the expected output. However, other times the command failed, showing no error in the console. I'm unsure why this inconsistency is occurring and how to resolve it.


Viewing all articles
Browse latest Browse all 23131

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>