Categories
language

for循环给字符数组赋值.踩坑

遇上懵逼bug。

在程序初始化了一个字符数组.然后使用for循环给字符数组赋值(一开始没想起来strcopy).结果赋值之后转化成字符串,程序在有的机器能正常运行,有的机器报错.

debug发现这个字符数组转化成的字符串比原来的多了一截.

原因是:字符数组初始化的时候是有长度,并且是再栈里分配的. 估计不同机器上的初始化出来的字符数组是不同的,可能是重用了.字符串拷贝还是要使用标准函数比较好.

Categories
py

做新旧命令兼容的一种方式

将无法解析的命令
1. catch parse异常.
2. 错误输出直接重定向/dev/null.避免干扰output

#!/usr/bin/env python

import sys
import os
import subprocess
from optparse import OptionParser

class redirect_stdout_stderr(object):
    def __init__(self, stream):
        # Save the old std streams
        self.old_stream = sys.stdout
        self.old_error_stream = sys.stderr
        self.fstream = stream

    def __enter__(self):
        # Change the std streams to your streams when entering
        sys.stdout = self.fstream
        sys.stderr = self.fstream

    def __exit__(self, exc_type, exc_value, exc_traceback):
        # Change the std streams back to the original streams while exiting
        sys.stdout = self.old_stream
        sys.stderr = self.old_error_stream

if __name__ == "__main__":
    usage = "mdfscli [options]"
    parser = OptionParser(usage)
    #需要兼容的旧命令
    parser.add_option("--build-info", action="store_true", dest="cmd_build_info", \
                      default=False, help="Show build information")
    newappcli = ""
    try:
        # parse command line arguments
        with redirect_stdout_stderr(open(os.devnull, 'w')):
            (options, args) = parser.parse_args()
    except:
        newappcli = "/usr/share/yourapp/newappcli %s" % (" ".join(sys.argv[1:]))
    else:
        if options.cmd_build_info:
            newappcli = "/usr/share/yourapp/newappcli --build-info"
        else:
          newappcli = "/usr/share/yourapp/newappcli %s" % (" ".join(sys.argv[1:]))

    cmd = subprocess.Popen(newappcli, shell=True, stdout=sys.stdout, stderr=sys.stderr, close_fds=True)
    sys.exit(cmd.wait())
Categories
py

PYTHONPATH作用

尝试使用命令行执行自己的一个小项目,抛出了异常

(venv) [root@node2 hui-cache-test]# python system-info-data/src/main.py
Traceback (most recent call last):
  File "system-info-data/src/main.py", line 1, in <module>
    from src.iostat.collect_op import *
ModuleNotFoundError: No module named 'src'

Google一番原来是需要配置$PYTHONPATH

export PYTHONPATH=path-to-project-directory:$PYTHONPATH

#export PYTHONPATH=/root/hui-cache-test/system-info-data:$PYTHONPATH