Skip to main content
 首页 » 编程设计

Python 将 curl 与子进程一起使用,将输出写入文件

2024年12月31日9mayingbao

如果我在 Git Bash 中使用以下命令,它工作正常。 curl 的输出被写入文件 output.txt

curl -k --silent "https://gitlab.myurl.com/api/v4/groups?page=1&per_page=1&simple=yes&private_token=mytoken&all?page=1&per_page=1" > output.txt 

Python 代码:

import subprocess, shlex 
command = shlex.split("curl -k --silent https://gitlab.myurl.com/api/v4/groups?page=1&per_page=1&simple=yes&private_token=mytoken&all?page=1&per_page=1 > output.txt") 
subprocess.Popen(command) 

Python 代码在我的文件“output.txt”中什么也不写。 如何在 output.txt 中写入或直接在 Python 中获取输出?

请您参考如下方法:

您不能直接对子进程使用重定向,因为它是一个 shell 特性。使用check_output:

import subprocess 
command = ["curl", "-k", "--silent", "https://gitlab.myurl.com/api/v4/groups?page=1&per_page=1&simple=yes&private_token=mytoken&all?page=1&per_page=1"] 
output = subprocess.check_output(command)