简体   繁体   English

将输出重定向到Python脚本中的文件

[英]Redirecting output to file in Python script

I have a Python(Version 2.6.6) script like Below: 我有一个Python(2.6.6版)脚本,如下所示:

import subprocess

id = 834
urllink = "https://xyzm:8443/rest/import-job/" + str(id)
subprocess.call([
    'curl',
    '-k',
    '-u',
    'xxxx:abc',
    '-X',
    'GET',
    urllink
])

It returns some JSON output to the terminal. 它将一些JSON输出返回到终端。 How can I redirect the output to a file, so that I can parse the file and use the same file(data) while executing a POST command? 如何将输出重定向到文件,以便在执行POST命令时可以解析文件并使用相同的文件(数据)?

Any reply would be greatly appreciated. 任何答复将不胜感激。

Thanks, Jee 谢谢吉

The following code will write to a file in python 2.6 (I have it set to write what is contained in your output variable), followed by a read of that same file & then the print command will display the output on the terminal. 以下代码将在python 2.6中写入文件(我将其设置为写入输出变量中包含的内容),然后读取相同的文件,然后print命令将在终端上显示输出。

# Write a file
out_file = open("test.txt", "w")
out_file.write(output)
out_file.close()

# Read a file
in_file = open("test.txt", "r")
text = in_file.read()
in_file.close()

print text

Using PyCurl is easy. 使用PyCurl很容易。

Here's an example to get you started: 这是一个使您入门的示例:

https://github.com/pycurl/pycurl/blob/master/examples/quickstart/get.py https://github.com/pycurl/pycurl/blob/master/examples/quickstart/get.py

For some options (setopt) you could get a hint using the --libcurl option of curl. 对于某些选项(setopt),您可以使用curl的--libcurl选项获得提示。

Thank you very much for taking time to reply. 非常感谢您抽出宝贵的时间回复。

I achieved the goal by using Python requests package without using Linux subprocess module or commands. 我通过使用Python 请求包而不使用Linux子进程模块或命令来实现了目标。

Once again, Thank you all! 再次感谢大家!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM