#195 virtualenv 的使用

2017-04-04

安装

pip install virtualenvwrapper

把以下内容加入 ~/.bashrc~/.zshrc 等 Shell 初始化代码中:

export WORKON_HOME="~/.virtualenvs"
export VIRTUALENVWRAPPER_PYTHON="/usr/bin/python3"
source virtualenvwrapper.sh
  1. source virtualenvwrapper_lazy.sh 也可以,只是不会自动补全了。
  2. 这两个脚本默认会放到 /usr/local/bin/ 目录,或者 ~/.local/bin/ 目录,所以可以直接 source 加载。

简单使用

# 创建并进入虚拟环境
mkvirtualenv myproject

# 进入指定虚拟环境
workon myproject

# 退出虚拟环境
deactivate

# 列出虚拟环境
workon

# 删除虚拟环境
rmvirtualenv myproject

其他命令

virtualenvwrapper

virtualenvwrapper is a set of extensions to Ian Bicking's virtualenv
tool.  The extensions include wrappers for creating and deleting
virtual environments and otherwise managing your development workflow,
making it easier to work on more than one project at a time without
introducing conflicts in their dependencies.

For more information please refer to the documentation:

    http://virtualenvwrapper.readthedocs.org/en/latest/command_ref.html

Commands available:

  add2virtualenv: add directory to the import path

  allvirtualenv: run a command in all virtualenvs

  cdproject: change directory to the active project

  cdsitepackages: change to the site-packages directory

  cdvirtualenv: change to the $VIRTUAL_ENV directory

  cpvirtualenv: duplicate the named virtualenv to make a new one

  lssitepackages: list contents of the site-packages directory

  lsvirtualenv: list virtualenvs

  mkproject: create a new project directory and its associated virtualenv

  mktmpenv: create a temporary virtualenv

  mkvirtualenv: Create a new virtualenv in $WORKON_HOME

  rmvirtualenv: Remove a virtualenv

  setvirtualenvproject: associate a project directory with a virtualenv

  showvirtualenv: show details of a single virtualenv

  toggleglobalsitepackages: turn access to global site-packages on/off

  virtualenvwrapper: show this help message

  wipeenv: remove all packages installed in the current virtualenv

  workon: list or change working virtualenvs

#194 MySQL 技巧

2017-04-02

安装之后初始化

忘记密码

改密码

查看版本

  1. mysql 命令行登录的时候显示的欢迎信息
  2. select @@version
  3. select version()
  4. SHOW VARIABLES WHERE variable_name LIKE 'version%';
  5. status

导出数据为 JSON

导出数据为 CSV

#193 Linux 文件属性(stat)

2017-03-29
  • atime:access time,访问时间
  • mtime:change time,修改时间,内容修改
  • ctime:modify time,变更时间,内容修改,或者元数据修改
  • crtime:create time / birth time,创建时间,部分文件系统支持(Ext4,btrfs,xfs)
[root@localhost]# stat abc.txt
  File: `abc.txt'
  Size: 11214           Blocks: 24         IO Block: 4096   regular file
Device: fc10h/64528d    Inode: 3153180     Links: 1
Access: (0644/-rw-r--r--)  Uid: (    0/    root)   Gid: (    0/    root)
Access: 2016-07-09 19:35:42.321279859 +0800
Modify: 2016-07-09 19:35:42.321279859 +0800
Change: 2016-07-09 19:35:42.321279859 +0800
[root@localhost]# cat abc.txt > /dev/null
[root@localhost]# stat abc.txt
  File: `abc.txt'
  Size: 11214           Blocks: 24         IO Block: 4096   regular file
Device: fc10h/64528d    Inode: 3153180     Links: 1
Access: (0644/-rw-r--r--)  Uid: (    0/    root)   Gid: (    0/    root)
Access: 2016-07-09 19:35:42.321279859 +0800
Modify: 2016-07-09 19:35:42.321279859 +0800
Change: 2016-07-09 19:35:42.321279859 +0800
[root@localhost]# mount
/dev/vda1 on / type ext4 (rw,noatime,errors=remount-ro)
proc on /proc type proc (rw)
sysfs on /sys type sysfs (rw)
devpts on /dev/pts type devpts (rw,gid=5,mode=620)
tmpfs on /dev/shm type tmpfs (rw)
/dev/vdb on /data type ext4 (rw,noatime)
none on /proc/sys/fs/binfmt_misc type binfmt_misc (rw)

重点是 noatime 选项,表示文件系统忽略 atime 的变更,因为频繁的 atime 变更对性能有影响。

#192 Linux 常用压缩命令 CheatSheet

2017-03-22

rar

rar a xxx.rar files...
rar e xxx.rar ./

rar a -p123456 xxx.rar files...
rar e -p123456 xxx.rar ./

rar a -v20m xxx.rar files...

tar

常用的参数说明(grep "^ \-[a-zA-Z0-9]" <(tar --help) | sort):

  • vf 分别表示输出详细信息、指定压缩包名称
  • x 解压
  • c 压缩
  • t 列出压缩包里面的文件列表
  • 压缩文件类型(Linux 下最常用的两种):
  • z:gz
  • j:bz2
# To extract an uncompressed archive:
tar -xvf /path/to/foo.tar

# To create an uncompressed archive:
tar -cvf /path/to/foo.tar /path/to/foo/

# To extract a .gz archive:
tar -xzvf /path/to/foo.tgz

# To create a .gz archive:
tar -czvf /path/to/foo.tgz /path/to/foo/

# To list the content of an .gz archive:
tar -ztvf /path/to/foo.tgz

# To extract a .bz2 archive:
tar -xjvf /path/to/foo.tgz

# To create a .bz2 archive:
tar -cjvf /path/to/foo.tgz /path/to/foo/

# To list the content of an .bz2 archive:
tar -jtvf /path/to/foo.tgz

# To create a .gz archive and exclude all jpg,gif,... from the tgz
tar czvf /path/to/foo.tgz --exclude=\*.{jpg,gif,png,wmv,flv,tar.gz,zip} /path/to/foo/

# To use parallel (multi-threaded) implementation of compression algorithms:
tar -z ... -> tar -Ipigz ...
tar -j ... -> tar -Ipbzip2 ...
tar -J ... -> tar -Ipixz ...

zip

# Create zip file
zip archive.zip file1 directory/

# To list, test and extract zip archives, see unzip
cheat unzip

# Extract archive
unzip archive.zip

# Windows 下创建的压缩包放到 Ubuntu 下解压可能会有编码问题
unzip archive.zip -O gbk

# Test integrity of archive
unzip -tq archive.zip

# List files and directories in a file
unzip -l archive.zip

7z

sudo apt install p7zip-full
dpkg -L p7zip-full p7zip | grep bin/
# /usr/bin/7z
# /usr/bin/7za
# /usr/bin/7zr
# /usr/bin/p7zip

文档中说是支持 7z,xz,tar,gz,zip,bz2,iso,rpm,deb 等等等等格式,不过没用过。

# 压缩
7z a  xxxx.7z files...
# 解压
7z e  xxxx.7z
# 查看文件列表
7z l  xxxx.7z

参考

  1. man
  2. --help
  3. cheat / tldr

#191 使用 git-daemon

2017-03-15

有时需要临时分享一个仓库给朋友,我们可以用 SSH 协议:

git clone ssh://markjour@192.168.64.234/home/markjour/Projects/Mine/lego

其实 git-daemon 是一个更好的方法。

#190 logging 时间格式

2017-03-12
import logging
LOG_LEVEL = logging.DEBUG
LOG_FORMAT = '%(asctime)s %(levelname)s %(message)s'
logging.basicConfig(level=LOG_LEVEL, format=LOG_FORMAT)
logging.info('hello world')

默认时间格式是 yyyy-mm-dd hh:mm:ss,xxx,如果我们要改这个格式可以用 datefmt 参数,遵循 time.strftime 的格式化参数格式。

问题有一个,毫秒从哪里来?

方法一:使用 msecs 占位符

最简单的办法:在格式字符串中使用 msecs 占位符,比如:

import logging
LOG_LEVEL = logging.DEBUG
LOG_FORMAT = '%(asctime)s.%(msecs)03d %(levelname)s %(message)s'
LOG_DATEFMT = '%H:%M:%S'
logging.basicConfig(level=LOG_LEVEL, format=LOG_FORMAT, datefmt=LOG_DATEFMT)
logging.info('hello world')

方法二:改用 datetime 对象

import logging
from datetime import datetime

class MyFormatter(logging.Formatter):
    converter = datetime.fromtimestamp

    def formatTime(self, record, datefmt=None):
        ct = self.converter(record.created)
        if datefmt:
            # s = time.strftime(datefmt, ct)
            s = ct.strftime(datefmt)
        else:
            # t = time.strftime("%Y-%m-%d %H:%M:%S", ct)
            t = ct.strftime("%Y-%m-%d %H:%M:%S")
            s = "%s,%03d" % (t, record.msecs)
        return s

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
console = logging.StreamHandler()
logger.addHandler(console)
formatter = MyFormatter(fmt='%(asctime)s %(levelname)s %(message)s', datefmt='%H:%M:%S.%f')
console.setFormatter(formatter)
logging.info('hello world')

#189 dc 计算器

2017-02-26

dc, desk caclulator,使用的是逆波兰式表达方法,而不是熟悉的代数标记法。

只是一些简单的用法,复杂的指令就不研究了:

# 1 + 2 + 3 + 4 + 5
dc -e "1 2 + 3 + 4 + 5 + p"

# 4 ** 3
dc -e "4 3 ^ p"

就是数在前面,操作符在后面,最后 p 输出。

# 加 减 乘 除 取余
+ - * / %
# 乘方 开方
^ v
# 用后面的数除以前面的数
~
# 清除结果
c
# 设置精度为 3
3k

如果进入 bc 交互模式,按 q 退出。

dc -e "3k 1 2 / p 2 / p"
.500
.250

#188 MySQL 增加或修改注释

2017-02-19

表注释

SELECT TABLE_COMMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA = '5mzb' AND TABLE_NAME = 'user';
ALTER TABLE `user` COMMENT = '用户';

字段注释

SELECT COLUMN_NAME, COLUMN_COMMENT FROM `information_schema`.`COLUMNS`
WHERE TABLE_SCHEMA = 'sendcloud' AND TABLE_NAME = 'user_info' ORDER BY ORDINAL_POSITION;
ALTER TABLE `user`
CHANGE COLUMN `create_time`
`create_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间' AFTER `expire_time`;
ALTER TABLE `user`
MODIFY COLUMN
`create_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间' AFTER `expire_time`;

好傻 X 啊,只改个备注,却必须要把字段声明带上,增加出错的可能。

#187 JS: split 方法

2017-02-12
"ni wo ta".split(" ");
// [ 'ni', 'wo', 'ta' ]

"ni wo ta".split(" ", 1);
// [ 'ni' ]
"ni wo ta".split(" ", 2);
// [ 'ni', 'wo' ]
"ni wo ta".split(" ", 3);
// [ 'ni', 'wo', 'ta' ]
"ni wo ta".split(" ", 4);
// [ 'ni', 'wo', 'ta' ]

"ni wo ta".split(":");
// [ 'ni wo ta' ]
"ni wo ta".split(":", 1);
// [ 'ni wo ta' ]
"ni wo ta".split(":", 2);
// [ 'ni wo ta' ]

如果要一刀将字符串切两半:

var line = "a : b : c";
var part1 = line.split(":", 1)[0];
if (a !== line) {
  var a = part1.trim();
  var b = line.substr(part1.length + 1).trim();
  console.log([a, b]);
}
var line = "a : b : c";
var index = line.indexOf(":");
if (index != -1) {
  var a = line.substr(0, index).trim();
  var b = line.substr(index + 1).trim();
  console.log([a, b]);
}

参考资料与拓展阅读

#186 为旧版本 CentOS 设置更新源

2017-02-08

总有些时候需要操作一些老旧的 CentOS 版本,如果需要更新就比较麻烦了,因为绝大部分更新源都不对老版本提供服务了。
这时我们只好使用 CentOS Vault,从官方接受这最后的支持,慢慢的下载更新。