先来说我的需求:
用markdown写文档, 图片是在本地的, 上传到segmentfault或者github上时, 要把图片转换为网络的链接, 有一个我用的方法就是上传到 七牛上, 这样不管是在哪里写文档, 直接复制上去就行了, 或者像github一样需要转换为网络地址
这里提供两个我写的脚本
一个是上传, 一个是把本地的图片替换为网络地址
上传
```python
```
# -*- coding: utf-8 -*-
# @Author: xsu19
# @Date: 2016-08-01 20:33:41
# @Last Modified by: xsu
# @Last Modified time: 2016-08-02 17:34:44
from qiniu import Auth, put_file, etag, urlsafe_base64_encode
import qiniu.config
import json
import os
import os.path
# 需要填写你的 Access Key 和 Secret Key
access_key = '*'
secret_key = '*'
# 要上传的空间
bucket_name = '*'
# 公开的http路径
qiniu_path = '*'
# 上传到七牛后保存的文件路径
remote_path = 'pic/phpstorm/'
# 本地要上传的图片路径
local_path = 'image/'
# 上面的请根据实际情况修改
# 构建鉴权对象
q = Auth(access_key, secret_key)
error_file = []
files_url = []
print("uploading...")
for filenames in os.walk(local_path):
for filename in filenames[2]:
key = remote_path + filename
token = q.upload_token(bucket_name, key, 3600)
# print(filename)
localfile = local_path + filename
# 上传
ret, info = put_file(token, key, localfile)
is_hash_same = (ret['key'] == key) and (ret['hash'] == etag(localfile))
if not is_hash_same :
print(filename, "upload failed")
# 把上传失败的记录到error_file中
error_file.append(localfile)
else:
files_url.append(qiniu_path + remote_path + filename)
# error_file not null
if error_file != []:
print(error_file, 'upload failed')
else:
print("uploaded")
```
```
替换
```python
# -*- coding: utf-8 -*-
# @Author: xsu19
# @Date: 2016-08-01 20:33:41
# @Last Modified by: xsu
# @Last Modified time: 2016-11-01 10:16:04
import sys,os
import re
# todo 替换你的地址: 七牛的地址或者github的原始文件地址
addr = ''
if len(sys.argv) == 1:
print("arg is too little")
exit()
if len(sys.argv) > 3:
print("arg is too much")
exit()
if len(sys.argv) == 2:
input_file = sys.argv[1]
output_file = 'md/'+input_file
if len(sys.argv) == 3:
input_file = sys.argv[1]
output_file = sys.argv[2]
if input_file.find('.md') == -1 :
print("choose markdown file pls")
exit()
if not os.path.exists(input_file):
print("input markdown file not exists")
exit()
# 将正则表达式编译成Pattern对象
pattern = re.compile(r'image\\')
replace = addr
# subject = "image\\20160730003958.jpg, image\\20160730003958.jpg"
# result, number = pattern.subn(replace, subject)
print("output file is "+output_file)
if input_file == output_file:
print("input file do not same with output file")
exit()
# 文件操作
i_file = open(input_file, 'r', encoding= 'utf8')
o_file = open(output_file, "w")
while True:
line = i_file.readline()
if not line:
break
# regx
result, number = pattern.subn(replace, line)
if number: # 如果匹配到了
o_file.write(result)
else: # 如果没有匹配到
o_file.write(line)
#文件处理完,关闭
i_file.close()
o_file.close()
```