参数是 URL 或路径 [英] Argument is URL or path

查看:27
本文介绍了参数是 URL 或路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

网页网址

磁盘上某处 HTML 文件的路径

path to a HTML file somewhere on disk

(只有一个)

代码够吗?

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

推荐答案

取决于程序必须做什么.如果它只是打印它是否有一个 URL,sys.argv[1].startswith('http://') 可能会做.如果您确实必须将 URL 用于有用的东西,请执行

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])

这篇关于参数是 URL 或路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆