[英]How to print the result of a subprocess.call to a file in a python script
I have a python script where I call the JIRA API and getting something from JIRA, which I want to write out to file. 我有一个Python脚本,在其中调用JIRA API并从JIRA中获取一些内容,我想将其写出到文件中。
This command in cmd works fine cmd中的此命令正常工作
curl -D- -u username:password -X GET --data @file.json -H "Content-Type: application/json" http:URL >> output.json
However, when I try to do the same in Python, it is not writing to my file (goes right to my "something is wrong") 但是,当我尝试在Python中执行相同操作时,它没有写入我的文件(正确到我的“某事是错误的”)
#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()
I also tried to just have it write the contents of a variable, below. 我还试图让它在下面写入变量的内容。
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()
I am using Windows 7 and Python 3 我正在使用Windows 7和Python 3
subprocess.call()
takes a list of arguments and just returns the exit status of the process called. subprocess.call()
接受参数列表,仅返回被调用进程的退出状态。 I think you are trying to redirect the standard output to a file: 我认为您正在尝试将标准输出重定向到文件:
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- The reason you're getting an exception is because the way you pass arguments to subprocess. 1-您收到异常的原因是因为您将参数传递给子流程的方式。 You should give subprocess a list of args and not a single string.
您应该给子进程一个args列表,而不是一个字符串。 Say you want to download google.com using curl:
假设您要使用curl下载google.com:
subprocess.call(['curl', 'google.com'])
2- subprocess.call returns the exit code, not the output. 2- subprocess.call返回退出代码,而不是输出。 To redirect the output to a file:
要将输出重定向到文件:
subprocess.call(['curl', 'google.com'], stdout=open('myFileName', 'w'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.