用python 命令行的os.system运行命令行程序报出错码256

当前位置: →
→ 使用python开发命令行程序的知识点之二
使用python开发命令行程序的知识点之二
& 作者及来源: harrychinese - 博客园 &
&收藏到→_→:
摘要: 使用python开发命令行程序的知识点之二
"使用python开发命令行程序的知识点之二"::
使用python开发命令行程序的知识点之二之前写过一个知识点, 链接是& http://www./harrychinese/archive//python_console_app_dev.html , 这次补充一些. ================================global-variables================================global 变量是一个模块级别的变量, 在一个 中, 如果读取这个变量, 不需要额外做global声明, 如果要赋值, 必须做global声明./questions/423379/using-global-variables-in-a-function-other-than-the-one-that-created-them在多个模块中,如何公用一个全局变量?参考: http://effbot.org/pyfaq/how-do-i-share-global-variables-across-modules.htm具体做法是: 将这个变量(比如 applicationname)放到一个类似config模块中, 在其他模块中,要访问这个变量, 写法是:import config #必须是这种import写法print(config.applicationname)================================line continuationshttp://docs.python-guide.org/en/latest/writing/style/#returning-multiple-values-from-a-function================================相比\拼接, 这个长字符串写法太美了my_very_big_string = (&&& "for a long time i used to go to bed early. sometimes, "&&& "when i had put out my candle, my eyes would close so quickly "&&& "that i had not even time to say &i&m going to sleep.&")from some.deep.module.inside.a.module import (&&& a_nice_function, another_nice_function, yet_another_nice_function)&& &&& &&& &================================logging 相关的几点================================&& &1.& 和logger.error()相比, logger.exception()会打印出traceback2.& windows下, 多进程/线程程序如使用标准库 rotatingfilehandler, 在换文件的时候很可能报错windowserror: [error 32],& 之后的log将写不记录下来. 可以使用concurrentloghandler库中的concurrentrotatingfilehandler类,& 该库下载地址 http://pypi.python.org/pypi/concurrentloghandler/0.8.4. &&& 如果要在windows使用该库, 需要 pywin32 库. &&& 另外, 0.8.4 版的 cloghandler.py 在 line 194 行有个bug, 应该在stream.flush()之前, 检查一下stream是否closed. && &if self.stream.closed==false:&&&&&&& self.stream.flush() 3.& java 使用 log4j, 可以在 log4j.properties 配置文件中来控制 log 的输出. python的 logging 模块也可这样, 示例代码见 http://pypi.python.org/pypi/concurrentloghandler/0.8.4&& &================================&& &uncaught exception为程序加上unhandled exception================================&& &#module name:uncaught_exception.pyimport sysimport loggingimport helperlogger=logging.getlogger(__name__)helper.caw_logging.configurelogger(logger)def my_excepthook(type, value, traceback):&&& msg= 'uncaught exception: %s, %s'%( type, value)&&& logger.exception(msg)sys.excepthook = my_excepthook在我们的程序中, 只需import uncaught_exception模块, 就能增加一个 uncaught exception handler. ================================&& &比如主程序为 application.py, 如何获取这个py的目录名. : 专门弄一个assembly_path.py, 放在和application.py同一个目录下================================module name: assembly_path.pyimport inspect&def getcurrentfilename():&&& '''&&& return the full file name of assembly_path.py&&& '''&&& return inspect.getfile(inspect.currentframe())&& &&& &def getcurrentpath():&&& '''&&& return the full path of assembly_path.py&&& '''&&& fullfilename=getcurrentfilename()&& &(dirname, filename) = os.path.split(fullfilename)&&& return os.path.normpath(dirname)&& &&& &def getcurrentpath_2():&&& return os.path.dirname(os.path.abspath(__file__)) && &&&&& ================================&& &解析ini文件&& &================================[basic]#db url, like sqlite:///c://caw.sqlite.dbsqlalchemy.url=mysql://root:root123@localhost/caw[additional]job_worker_conn_pool_size=10下面是一个解析示例, 可以为解析器设置defaults, 每个default config item的value必须是一个字符串. 我原来使用了一个数值, 此文来自: 马开东博客
转载请注明出处 网址:
结果报类型异常, 提示很隐晦, 好久才搞明白应使用字符串. &#py codedefaultconfigitems={&& &&& &&& &&& &&& &'job_worker_conn_pool_size':'15' && &&& &&& &&& &&& &}&& &&& &parser = safeconfigparser(defaults=defaultconfigitems)parser.read(self.inifile)self.sqlalchemy_url=parser.get('basic', 'sqlalchemy.url')self.job_worker_conn_pool_size=parser.get('additional', 'job_worker_conn_pool_size')&& &================================&& &怎样获取comandline 程序的输出================================首先调用launchcmdline()启动一个进程, 拿到对应的process对象, 然后调用waitresultofcmdprocess()知道该进程结束, 并获取exit code和output输出和error输出. && &def launchcmdline(*popenargs, **kwargs): &&& '''&&& run command line, return pid, exitcode, output, error message together&&& '''&&& #capture cmd output&&& #for windows, shell should be false, but there is a bug& http://bugs.python.org/issue8224, we should set shell=true&&& #for linux, shell=true &&& if iswindows():&&&&&&& shellvalue=true&&& else:&&&&&&& shellvalue=true&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& &&&& process = subprocess.popen(shell=shellvalue, stdout=subprocess.pipe, stderr=subprocess.pipe, *popenargs, **kwargs)&&& return process&& &def waitresultofcmdprocess(process): &&& '''&&& check process result, return exitcode, output, error message together&&& '''&&& output, error = municate()&&& exitcode = process.wait()&&& return (exitcode, output, error)&&&& &================================&& &使用 apscheduler.scheduler.add_interval_job() 来做轮询操作================================apscheduler.scheduler.add_interval_job()会启动另外的线程, 比较适合于频繁启动长任务. 示例:from apscheduler.scheduler import scheduler& &def scanmisfire():&&& pass&& &if __name__=="__main__":& &&& &misfirescheduler=scheduler()&& &sleep_seconds=120& # 2 minute&& &misfirescheduler.add_interval_job(scanmisfire, seconds=sleep_seconds)&& &misfirescheduler.start()&& &&& &&& &#dead loop to prevent program exiting. && &while true:&& &&& &time.sleep(9999)&& &misfirescheduler.shutdown()================================格式化打印db query结果集================================oracle sqlplus 有格式化输出结果集的功能, 如果我们程序也需要有类似的功能, 可以使用prettytable 和 texttable 包.& 当然, 数据不能包含汉字, 否则格式就乱掉. 另外, 如果数据包含回车换行, texttable会好一些. && &================================&& &add code in pythonpath temporarily================================对于一个多模块的程序, 没有将code放在python的site-packages目录中, 运行程序往往会报加载有问题.
是将程序代码放到pythonpath环境变量中, 当然也可以写个batch脚本, 临时性地将code加到pythonpath环境变量中windows下, set save=%pythonpath%set pythonpath=d://trunk/workspace/proj1/srcc:\pythonenv\python27_flask\scripts\python.exe d:\trunk\workspace\proj1\src\myapp.pyset pythonpath=%save%搜索此文相关文章:此文来自: 马开东博客
网址: 站长QQ
使用python开发命令行程序的知识点之二_博客园相关文章
博客园_总排行榜
博客园_最新
博客园_月排行榜
博客园_周排行榜
博客园_日排行榜最近在做那个测试框架的时候发现 Python 的另一个获得系统执行命令的返回值和输出的类。
最开始的时候用 Python 学会了 os.system() 这个方法是很多比如 C,Perl 相似的。
os.system('cat /proc/cpuinfo')
但是这样是无法获得到输出和返回值的,继续 Google,之后学会了 os.popen()。
output&=&os.popen('cat /proc/cpuinfo')
print&output.read()
通过 os.popen() 返回的是 file read 的对象,对其进行读取 read() 的操作可以看到执行的输出。但是怎么读取程序执行的返回值呢,当然咯继续请教伟大的 Google(联想到像我这样的人工作如果离开了 Google,不是成了废物。。。Baidu 忽视)。Google 给我指向了&。
这样通过 commands.getstatusoutput() 一个方法就可以获得到返回值和输出,非常好用。
(status,&output)&=&commands.getstatusoutput('cat
/proc/cpuinfo')
print&status,&output
Python Document 中给的一个例子,很清楚的给出了各方法的返回。
&&&&import&commands
&&&&commands.getstatusoutput('ls /bin/ls')
(0,&'/bin/ls')
&&&&commands.getstatusoutput('cat /bin/junk')
(256,&'cat: /bin/junk: No such file or directory')
&&&&commands.getstatusoutput('/bin/junk')
(256,&'sh: /bin/junk: not found')
&&&&commands.getoutput('ls /bin/ls')
&&&&commands.getstatus('/bin/ls')
'-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls'
&&相关文章推荐
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:427722次
积分:5714
积分:5714
排名:第4100名
原创:44篇
转载:601篇
评论:19条
大牛的博客:
(3)(6)(52)(39)(3)(23)(24)(35)(30)(22)(40)(23)(21)(12)(11)(12)(9)(7)(6)(10)(3)(17)(1)(6)(9)(16)(17)(5)(34)(8)(5)(1)(6)(1)(9)(19)(7)(9)(2)(9)(12)(14)(16)(10)(1)(37)(12)2102人阅读
python(76)
  在中,用于执行系统命令的模块与方法不止一种,这里分享几个常见的Python中执行系统命令的方法:
  os.system
  # 仅仅在一个子终端运行系统命令,而不能获取命令执行后的返回信息
  如果再命令行下执行,结果直接打印出来
  例如:
  代码示例:
  import os
  os.system('ls')
  chk_err_log.py CmdTool.log install_log.txt install_zabbix.sh manage_deploy.sh MegaSAS.log
  os.popen
  该方法不但执行命令还返回执行后的信息对象
  好处在于:将返回的结果赋于一变量,便于程序的处理。
  例如:
  代码示例:
  import os
  tmp = os.popen('ls *.sh').readlines()
  ['install_zabbix.sh\n', 'manage_deploy.sh\n', '_setup.sh\n', '_manage_deploy.sh\n',
'setup.sh\n']
  使用模块subprocess
  使用方法:
  代码示例:
  import subprocess
  subprocess.call ([&cmd&, &arg1&, &arg2&],shell=True)
  优点:运用对线程的控制和监控,将返回的结果赋于一变量,便于程序的处理。
  如果获取返回和输出:
  代码示例:
  !/bin/python
  import subprocess
  p = subprocess.Popen('ls *.sh', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  print p.stdout.readlines()
  for&in p.stdout.readlines():
  print line,
  retval = p.wait()
  使用模块commands模块
  常用的两个方法:getoutput和getstatusoutput
  代码示例:
  import commands
  commands.getoutput('ls *.sh')
  'install_zabbix.sh\nmanage_deploy.sh\nmysql_setup.sh\npython_manage_deploy.sh\nsetup.sh'
  commands.getstatusoutput('ls *.sh')
  (0, 'install_zabbix.sh\nmanage_deploy.sh\nmysql_setup.sh\npython_manage_deploy.sh\nsetup.sh')
  注意:
  当执行命令的参数或返回中包含了中文文字,建议使用subprocess,使用os.popen会出现错误。
(作者:王珏)
&&相关文章推荐
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:349402次
积分:4434
积分:4434
排名:第6110名
原创:56篇
转载:385篇
(1)(2)(2)(4)(1)(10)(5)(2)(3)(1)(11)(6)(7)(8)(4)(2)(7)(4)(6)(2)(13)(46)(10)(11)(14)(10)(30)(28)(7)(17)(23)(13)(27)(52)(13)(7)(8)(1)(1)(4)(1)(4)(1)(1)(1)(3)(7)(1)}

我要回帖

更多关于 python 命令行程序 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信