Argument - URL or path

What is the standard practice in Pythonwhen I have a command line application that takes one argument, which

Webpage url

or

HTML file path somewhere on disk

(only one)

enough code?

if "http://" in sys.argv[1]:
  print "URL"
else:
  print "path to file"
+5
source share
3 answers

Depends on what the program should do. If he just prints whether he got the URL, he sys.argv[1].startswith('http://')can do it. If you really have to use the url for something useful, do

from urllib2 import urlopen

try:
    f = urlopen(sys.argv[1])
except ValueError:  # invalid URL
    f = open(sys.argv[1])
+5
source
import urlparse

def is_url(url):
    return urlparse.urlparse(url).scheme != ""
is_url(sys.argv[1])
+14
source

Larsmans , , .

import urllib
import sys

try:
    arg = sys.argv[1]
except IndexError:
    print "Usage: "+sys.argv[0]+" file/URL"
    sys.exit(1)

try:
    site = urllib.urlopen(arg)
except ValueError:
    file = open(arg)
+1

All Articles