To redirect the standard output to a file by the source code, add this in the beginning of the Python script:
import sys
sys.stdout = open('/path/to/outputfile', 'a')
Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts
Friday, August 30, 2019
Friday, March 29, 2019
Python: return multiple values from a function
def op(number1, number2):
return number1 + number2, number1 - number2, number1 * number2, number1 / number2
add, sub, mul, div = op(10, 5)
print (add, sub, mul, div)
The result:
(15, 5, 50, 2)
return number1 + number2, number1 - number2, number1 * number2, number1 / number2
add, sub, mul, div = op(10, 5)
print (add, sub, mul, div)
The result:
(15, 5, 50, 2)
Friday, December 9, 2011
Python: a simple HTTP client
1 import httplib
2
3 h = httplib.HTTPConnection('www.python.org')
4 h.request('GET', '')
5 r = h.getresponse()
6
7 rh = r.getheaders()
8 print 'Header:'
9 for i in rh:
10 print i[0], ':', i[1]
11 print '\n'
12
13 rr = r.read()
14 print 'Content:'
15 print rr
16 print '\n'
17
18 h.close()
The httplib module is used to handle the HTTP and HTTPS protocol in Python. Let us look into the code above.
Line 1: Obviously. Import the httplib module.
Line 3: Connect to the HTTP server. If the server is using HTTPS protocol, you use httplib.HTTPSConnection instead.
Line 4: Use the GET method to send the request. You can use the POST method by supplying the first parameter as 'POST' and put your data at the third parameter.
Line 5: Get the response from the server.
Line 7-11: Get and print out the HTTP header of the response.
Line 13-16: Get and print out the content of the response.
Line 18: Close the HTTP connection to the server.
2
3 h = httplib.HTTPConnection('www.python.org')
4 h.request('GET', '')
5 r = h.getresponse()
6
7 rh = r.getheaders()
8 print 'Header:'
9 for i in rh:
10 print i[0], ':', i[1]
11 print '\n'
12
13 rr = r.read()
14 print 'Content:'
15 print rr
16 print '\n'
17
18 h.close()
The httplib module is used to handle the HTTP and HTTPS protocol in Python. Let us look into the code above.
Line 1: Obviously. Import the httplib module.
Line 3: Connect to the HTTP server. If the server is using HTTPS protocol, you use httplib.HTTPSConnection instead.
Line 4: Use the GET method to send the request. You can use the POST method by supplying the first parameter as 'POST' and put your data at the third parameter.
Line 5: Get the response from the server.
Line 7-11: Get and print out the HTTP header of the response.
Line 13-16: Get and print out the content of the response.
Line 18: Close the HTTP connection to the server.
Subscribe to:
Posts (Atom)