如何将 subprocess.call 的结果打印到 python 脚本中的文件

How to print the result of a subprocess.call to a file in a python script

我有一个 python 脚本,我在其中调用 JIRA API 并从 JIRA 获取一些东西,我想将其写到文件中。

cmd 中的这个命令可以正常工作

curl -D- -u username:password -X GET --data @file.json -H "Content-Type: application/json" http:URL >> output.json

但是,当我尝试在 Python 中执行相同操作时,它没有写入我的文件(直接写入我的 "something is wrong")

#Runs curl script to get component
def write():
    name = 'output.json'

try:
    file= open(name, 'w')
    file.write(subprocess.call('curl -D- -u username:password -X GET --data @file.json -H "Content-Type: application/json" http:URL'))
    file.close()

except:
    print('something is wrong')
    sys.exit(0)
write()

我也试过让它在下面写一个变量的内容。

curler = (subprocess.call('curl -D- -u username:password -X GET --data @file.json -H "Content-Type: application/json" http:URL'))

def write():
    name = 'output.json'

try:
    file = open(name, 'w')
    file.write(curler)
    file.close()

except:
    print('something is wrong')
    sys.exit(0)
write()

我正在使用 Windows 7 和 Python 3

subprocess.call() 接受参数列表,只是 returns 调用进程的退出状态。我认为您正在尝试将标准输出重定向到一个文件:

curl = ['curl', '-D-', '-u', 'username:password', '-X', 'GET', '--data',
        '@file.json', '-H', 'Content-Type: application/json', 'http:URL']
with open('output.json', 'w') as file:
    status = subprocess.call(curl, stdout=file)

1- 你得到异常的原因是因为你将参数传递给子进程的方式。您应该给子进程一个参数列表,而不是一个字符串。假设您想使用 curl:

下载 google.com
subprocess.call(['curl', 'google.com'])

2- subprocess.call returns 退出代码,而不是输出。要将输出重定向到文件:

subprocess.call(['curl', 'google.com'], stdout=open('myFileName', 'w'))