参数是URL或路径

xra*_*alf 9 python argv

Python当我有一个命令行应用程序采用一个参数时,标准做法是什么

网页的URL

要么

磁盘上某处的HTML文件的路径

(只有一个)

代码足够了吗?

if "http://" in sys.argv[1]:
  print "URL"
else:
  print "path to file"
Run Code Online (Sandbox Code Playgroud)

loc*_*jay 16

import urlparse

def is_url(url):
    return urlparse.urlparse(url).scheme != ""
is_url(sys.argv[1])
Run Code Online (Sandbox Code Playgroud)

  • 对于像`c:\ users\user\foo.txt`这样的Windows文件路径,它返回true. (5认同)
  • 最好检查`urlparse(uri).scheme in('http','https',)`因为Windows uri或uri以`file://`开头. (5认同)

Fre*_*Foo 3

取决于程序必须做什么。如果它只是打印是否有 URL,sys.argv[1].startswith('http://')也许可以。如果您实际上必须使用该 URL 来做一些有用的事情,请执行以下操作

from urllib2 import urlopen

try:
    f = urlopen(sys.argv[1])
except ValueError:  # invalid URL
    f = open(sys.argv[1])
Run Code Online (Sandbox Code Playgroud)