Argument is URL or path

故事扮演 提交于 2019-12-08 17:28:38

问题


What is the standard practice in Python when I have a command-line application taking one argument which is

URL to a web page

or

path to a HTML file somewhere on disk

(only one)

is sufficient the code?

if "http://" in sys.argv[1]:
  print "URL"
else:
  print "path to file"

回答1:


Depends on what the program must do. If it just prints whether it got a URL, sys.argv[1].startswith('http://') might do. If you must actually 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])



回答2:


import urlparse

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



回答3:


Larsmans might work, but it doesn't check whether the user actually specified an argument or not.

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)


来源:https://stackoverflow.com/questions/7849818/argument-is-url-or-path

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!