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

查看:59
本文介绍了参数是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天全站免登陆