python打乱数组顺序

2017年6月22日 23:44

import random
a = [1, 2, 3, 4, 5];
random.shuffle(a)
print a
#[2, 3, 1, 5, 4]
此生必看的科学实验-水知道答案
为什么观看这部记录片
精神病为什么治不好
百病之源
净土大经科注2014

评论(0) 阅读(2565)

python取文件后缀

2017年6月22日 23:41

#取文件后缀
>>> os.path.splitext("/root/a.py")
('/root/a', '.py')

#取目录与文件名
>>> os.path.split("/root/a.py")
('/root', 'a.py')

此生必看的科学实验-水知道答案
为什么观看这部记录片
精神病为什么治不好
百病之源
净土大经科注2014

评论(0) 阅读(2580)

subprocess.Popen(cmd)包含中文怎么办

2017年4月22日 12:22

在windows中通过subprocess调用cmd命令行,命令中包含中文是很令人头痛的事。
由于cmd控制台用的是gbk编码,而python用的是utf-8。utf-8的字符串,在gbk编码的控制台上运行,当然会运行不了。
假如再要你兼容繁体版的windows,此时更麻烦了。还好python提供了本地化接口
 
  • 本地化
>>> import locale
>>> locale.getdefaultlocale()
('zh_CN', 'cp936')
 
  • 示例
import locale
cmd = cmd.encode(locale.getdefaultlocale()[1])
subprocess.Popen(cmd)
 
净土大经科注2014 百度网盘地址

http://pan.baidu.com/s/1gfaHvwv

评论(2) 阅读(4533)

python获取自己的路径

2017年4月17日 22:51

exe路径

>>> sys.executable
'C:\\Python27\\python.exe'

lib路径

>>> sys.prefix
'C:\\python27'

 

评论(0) 阅读(1811)

windows上subprocess.Popen的参数close_fds=True与管道不能共存

2017年3月21日 21:46

  • 运行命令
subprocess.Popen(cmd, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
 
  • 出现错误
ValueError: close_fds is not supported on Windows platforms if you redirect stdin/stdout/stderr
 
  • 原因
在windows上subprocess.Popen的参数close_fds=True与stdin/stdout/stderr不能共存
  1. close_fds=True表示子进程将不会继承父进程的输入、输出、错误管道。
  2. windows上不能将close_fds设置为True同时重定向子进程的标准输入、输出与错误(stdin, stdout, stderr)
 

评论(138) 阅读(19137)

python多行字符拼接使用小括号

2017年2月02日 21:33

* 多行字符串拼接使用小括号
 
s = ('select *'
     'from atable'
     'where id=888')
print s, type(s)

#输出
select *from atablewhere id=888 <type 'str'>
 
* python遇到未闭合的小括号,自动将多行拼接为一行,相比三个引号和换行符,这种方式不会把换行符、前导空格当作字符。
 

Tags: 拼接 字符
评论(1) 阅读(2207)

32位python的bug:os.system返回码一直为0

2016年9月26日 20:33

32位python在windows上调用命令行(os.system或subprocess.Popen)。执行后,如果返回码太大,python取得的返回值也是0。此时无法判断执行成功还是失败,这个是32位python的bug。
 
以时间同步命令w32tm位例子

在cmd上执行

C:\WINDOWS\system32>w32tm /resync
发生下列错误: 服务尚未启动。 (0x80070426)

C:\WINDOWS\system32>echo %errorlevel%
-2147023834

在64位python上执行

>>> os.system("w32tm /resync")
发生下列错误: 服务尚未启动。 (0x80070426)
-2147023834

在32位python上执行

>>> os.system("w32tm /resync")
发生下列错误: 服务尚未启动。 (0x80070426)
0
注意:此时命令执行错误的返回码也是0。
通常成功返回码才是0,这里执行错误,返回码却是也0。当要判断执行成功还失败时,这里便是个坑。
  • os.system文档
https://docs.python.org/2/library/os.html
 

Tags: popen system python
评论(54) 阅读(3407)

apscheduler提示maximum错误

2015年12月15日 20:59

起因

在tornado中用apscheduler实现计划任务,出现错误提示
 
2015-12-04 19:10:22,227 - apscheduler.scheduler - WARNING - Execution of job "TaskHandle.progress_job (trigger: date[2015-12-04 19:10:22 CST], next run at: 2015-12-04 19:10:22 CST)" skipped: maximum number of running instances reached (1)

分析

缺乏资料,所以根据提示,分析apscheduler源码
  • 记录异常位置
在源码目录下,搜索关键字maxinum,找到记录异常的位置
#apscheduler/schedulers/base.py
if run_times:
    try:
        executor.submit_job(job, run_times)
    except MaxInstancesReachedError:
        self._logger.warning(
            'Execution of job "%s" skipped: maximum number of running instances reached (%d)',
            job, job.max_instances)
    except:
        self._logger.exception('Error submitting job "%s" to executor "%s"', job, job.executor)
  • 异常抛出位置
 
继续看submit_job函数,找到异常抛出位置
#apscheduler/executors/base.py
def submit_job(self, job, run_times):
    """
    Submits job for execution.

    :param Job job: job to execute
    :param list[datetime] run_times: list of datetimes specifying when the job should have been run
    :raises MaxInstancesReachedError: if the maximum number of allowed instances for this job has been reached
    """

    assert self._lock is not None, 'This executor has not been started yet'
    with self._lock:
        if self._instances[job.id] >= job.max_instances:
            raise MaxInstancesReachedError(job)

        self._do_submit_job(job, run_times)
        self._instances[job.id] += 1
  • _instances变量作用
在submit_job(提交任务)时加1,在_run_job_success(任务运行成功)时减1。 当self._instances[job.id]大于job.max_instances抛出异常。
max_instances默认值为1,它表示id相同的任务实例数。

解决

通过设置max_instances参数
sched.add_job(child_job, max_instances=10, trigger=DateTrigger(), id="123")

重现脚本

import time
import tornado.ioloop
from apscheduler.triggers.date import DateTrigger
from apscheduler.schedulers.tornado import TornadoScheduler

sched = TornadoScheduler()

def child_job():
    print "start"
    time.sleep(60)
    print "end"

def main_job():
    sched.add_job(child_job, trigger=DateTrigger(), id="123")

sched.add_job(main_job, 'interval', seconds=5)

sched.start()
tornado.ioloop.IOLoop.instance().start()
  • 输出
job_id: 7279209ab6c2498698f2117bb97e18a1, instances: 0, max_instances: 1
job_id: 123, instances: 0, max_instances: 1
start
job_id: 7279209ab6c2498698f2117bb97e18a1, instances: 0, max_instances: 1
job_id: 123, instances: 1, max_instances: 1
WARNING:apscheduler.scheduler:Execution of job "child_job (trigger: date[2015-12-07 15:27:11 CST], next run at: 2015-12-07 15:27:11 CST)" skipped: maximum number of running instances reached (1)
job_id: 7279209ab6c2498698f2117bb97e18a1, instances: 0, max_instances: 1
 

Tags: tornado;apscheduler
评论(11) 阅读(11636)

python paramiko实现ssh远程登录

2015年11月13日 21:03

  • 介绍
paramiko是python的一个模块,遵循SSH2协议。 paramiko的功能:1、通过ssh执行命令; 2、通过ssh传输文件。
  • 示例
import paramiko

ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname="xxx.xxx.xxx.xxx", port=22, username="xxx", password="xxx")
stdin, stdout, stderr = ssh.exec_command("vmstat 1 1")
content = stdout.readlines()
for r in content:
    print r
ssh.close()
 

Tags: paramiko
评论(79) 阅读(10462)

gettext国际化用法示例

2015年9月09日 16:36

  • 安装gettext
sudo yum install gettext
  • gettext工具
gettext: 进行translate。
 
xgettext: 从程序中抽取调用gettext进行本地化的字符串,生成一份.po结尾的配置文件。
 
msgfmt: 将配置好的本地化配置文件进行转换成gettext使用的格式。
  • 准备demo.py
#encoding=utf-8
import gettext

# demo对应mo文件名,locale为locale目录地址,zh_CN为locale目录下目录名
zh = gettext.translation("demo", "locale", languages=["zh_CN"])
# 激活_()
zh.install(True)
print _("hello world")
  • 生成po文件
 
从程序文件中抽取,使用gettext的字符串,生成po文件
xgettext -L python -o zh_CN.po demo.py
  • 编辑po文件
...
#修改编码为utf-8
"Content-Type: text/plain; charset=utf-8\n"
...

#加上翻译
#: demo.py:6
msgid "hello world"
msgstr "你好,世界"
  • 创建locale目录
mkdir -p locale/zh_CN/LC_MESSAGES
 
* 编译po文件
msgfmt -o ~/locale/zh_CN/LC_MESSAGES/demo.mo zh_CN.po
  • 查看结果
➜  ~  python demo.py
你好,世界
 

Tags: 国际化
评论(35) 阅读(5471)