Browse Source

Introduced argparse

Sebastian Lohff 9 years ago
parent
commit
6a2fea1465
1 changed files with 22 additions and 25 deletions
  1. 22
    25
      servefile

+ 22
- 25
servefile View File

@@ -4,6 +4,7 @@
4 4
 # written by seba (seba-geek.de) :)
5 5
 # v0.3
6 6
 
7
+import argparse
7 8
 import BaseHTTPServer
8 9
 import commands
9 10
 import urllib
@@ -82,44 +83,40 @@ class ThreadedHTTPServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer)
82 83
 	pass
83 84
 
84 85
 def main():
85
-	if len(sys.argv) < 2 or len(sys.argv) > 3 or sys.argv[1] in ('-h', '--help'):
86
-		print "Usage: [path to file] <port=8080>"
87
-		return
88
-	
89
-	port = 8080
90
-	if len(sys.argv) == 3:
91
-		try:
92
-			port = int(sys.argv[2])
93
-		except ValueError:
94
-			print "Error: Port should be an int!"
95
-			return
86
+	parser = argparse.ArgumentParser()
87
+	parser.add_argument('filename', metavar='file/directory', type=str)
88
+	parser.add_argument('-p', '--port', type=int, default=8080, \
89
+	                    help='port to listen on')
96 90
 	
91
+	args = parser.parse_args()
92
+		
97 93
 	try:
98
-		testit = open(sys.argv[1], 'r')
94
+		testit = open(args.filename, 'r')
99 95
 		testit.close()
100 96
 		FileHandler.filePath = sys.argv[1]
101
-		FileHandler.fileName = os.path.basename(sys.argv[1])
102
-		FileHandler.fileLength = os.stat(sys.argv[1])[ST_SIZE]
97
+		FileHandler.fileName = os.path.basename(args.filename)
98
+		FileHandler.fileLength = os.stat(args.filename)[ST_SIZE]
103 99
 	except IOError:
104 100
 		print "Error: Could not open file!"
105
-		return
106
-	
107
-	server = ThreadedHTTPServer(('', port), FileHandler)
108
-	print "Serving:", sys.argv[1]
109
-	print "Port: ", port
110
-	print "Ready..."
111
-	server.address_family = 10
101
+		sys.exit(3)
102
+
103
+	server = ThreadedHTTPServer(('', args.port), FileHandler)
104
+	print "Serving \"%s\" under port %d" % (args.filename, args.port)
105
+
112 106
 	# print urls with local network adresses
113
-	print "Some addresses this file will be available under:"
114
-	ips = commands.getoutput(r"/bin/ip addr|sed -n -e 's/.*inet6\? \([0-9.a-fA-F:]\+\)\/.*/\1/ p'|grep -v '^fe80\|^127.0.0.1\|^::1'")
107
+	print "\nSome addresses this file will be available under:"
108
+
109
+	ips = commands.getoutput(r"/bin/ip addr|" + \
110
+	                  "sed -n -e 's/.*inet6\? \([0-9.a-fA-F:]\+\)\/.*/\\1/ p'|" + \
111
+					  "grep -v '^fe80\|^127.0.0.1\|^::1'")
115 112
 	for ip in ips.split("\n"):
116 113
 		if ip.find(":") >= 0:
117 114
 			# ipv6
118 115
 			ip = "[%s]" % ip
119 116
 			# FIXME: When BaseHTTP supports ipv6 properly, delete this line
120 117
 			continue	
121
-		print "http://%s:%d/" % (ip, port)
122
-	
118
+		print "http://%s:%d/" % (ip, args.port)
119
+
123 120
 	try:
124 121
 		server.serve_forever()
125 122
 	except KeyboardInterrupt:

Loading…
Cancel
Save