python 如何通过subprocess.call调用自定义alias别名
为了更好的通过Python脚本执行linux命令,通过自定义别名(Alias)进行多个命令组合,然而通过python中如何通过subprocess类库
自定义alias
#alias lt='ls --human-readable --size -1 -S --classify'
alias lt='du -sh * | sort -h'
测试调用的Python代码
from subprocess import call
def test():
call("lt")
if __name__ == "__main__":
test()
直接运行上面的代码提示错误信息如下
Traceback (most recent call last):
File "test_alias.py", line 7, in <module>
test()
File "test_alias.py", line 4, in test
call("lt")
File "/Users/shiwei/anaconda3/lib/python3.7/subprocess.py", line 323, in call
with Popen(*popenargs, **kwargs) as p:
File "/Users/shiwei/anaconda3/lib/python3.7/subprocess.py", line 775, in __init__
restore_signals, start_new_session)
File "/Users/shiwei/anaconda3/lib/python3.7/subprocess.py", line 1522, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'lt': 'lt'
通过错误信息可以看出lt命令被当作了文件或目录提示找不到
如果您需要的别名是在 ~/.bashrc 中定义的,可以通过尝试以下几种方式进行运行:
1)你必须给’shell’关键字:
subprocess.call('command', shell=True)
否则,您给定的命令用于查找可执行文件,而不是传递给 shell,它是扩展别名和函数等内容的 shell。
from subprocess import call
def test():
call("lt", shell=True)
if __name__ == "__main__":
test()
运行此处代码发现报错找不到文件或目录的错误了,但是出现了新的错误,错误信息如下
# /bin/sh: lt: command not found
有错误信息可以看出还是找不到lt命令,不过不报错误了(此处应该有掌声)
2) 默认情况下,subprocess.call 使用’/bin/sh’ shell。如果这是您要调用的 Bash 别名,则需要使用“可执行”关键字 告诉子进程使用 bash 而不是 sh:
subprocess.call('command', shell=True, executable='/bin/bash')
代码如下
from subprocess import call
def test():
call("lt", shell=True, executable='/bin/bash')
if __name__ == "__main__":
test()
通过执行代码发现,报错的错误同上,还是提示lt找到
3) 但是,/bin/bash 除非作为“交互式”shell(使用“-i”)启动,否则不会获取 ~/.bashrc。不幸的是,您不能传递 executable=’/bin/bash -i’,因为它认为整个值是可执行文件的名称。因此,如果您的别名是在用户的正常交互式启动中定义的,例如在 .bashrc 中,您必须使用以下替代形式调用命令:
subprocess.call(['/bin/bash', '-i', '-c', 命令])
# i.e. shell=False (the default)
from subprocess import call
def test():
call(['/bin/bash', '-i', '-c', 'lt'])
if __name__ == "__main__":
test()
正常执行,成功调用了alias命令
标签: python subprocess alias
python2 python3中long类型的区别
python2 python3中long类型的区别
python2中有long类型
python3中没有long类型,只有int类型
'python' engine because the 'c' engine does not support regex separators
moveielens.py:17: ParserWarning: Falling back to the 'python' engine because the 'c' engine does not support regex separators (separators > 1 char and different from '\s+' are interpreted as regex); you can avoid this warning by specifying engine='python'.user = pd.read_table(path1, sep='::', header=None, names=unames)
pandas.read_table()函数,读取文件数据时,由于分隔符为'::',弹出如下警告
警告:ParserWarning: Falling back to the 'python' engine because the 'c' engine does not support regex separators (separators > 1 char and different from '\s+' are interpreted as regex)
解决方法:增加函数的引擎参数engine='python',如下:
user = pd.read_table(path1, sep='::', header=None, names=unames, engine='python')
标签: python pandas re read_table
RuntimeError: Python is not installed as a framework
今天在mac上,python virtualenv 虚拟环境下运行matplotlib example的时候提示如下报错:python animation/animated_histogram.py
Traceback (most recent call last):
File "animation/animated_histogram.py", line 11, in <module>
import matplotlib.pyplot as plt
File "/Users/shiwei/Documents/python_project/study_matplotlib/lib/python3.5/site-packages/matplotlib/pyplot.py", line 115, in <module>
_backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()
File "/Users/shiwei/Documents/python_project/study_matplotlib/lib/python3.5/site-packages/matplotlib/backends/__init__.py", line 62, in pylab_setup
[backend_name], 0)
File "/Users/shiwei/Documents/python_project/study_matplotlib/lib/python3.5/site-packages/matplotlib/backends/backend_macosx.py", line 17, in <module>
from matplotlib.backends import _macosx
RuntimeError: Python is not installed as a framework. The Mac OS X backend will not be able to function correctly if Python is not installed as a framework. See the Python documentation for more information on installing Python as a framework on Mac OS X. Please either reinstall Python as a framework, or try one of the other backends. If you are using (Ana)Conda please install python.app and replace the use of 'python' with 'pythonw'. See 'Working with Matplotlib on OSX' in the Matplotlib FAQ for more information.
标签: python matplotlib RuntimeError
从苦逼到牛逼,详解Linux运维工程师的打怪升级之路
运维工程师是从一个呆逼进化为苦逼再成长为牛逼的过程,前提在于你要能忍能干能拼,还要具有敏锐的嗅觉感知前方潮流变化。如:今年大数据,人工智能比较火……(相对表示就是 Python 比较火)
之前写过运维基础篇,发现对很多人收益挺大,接下来也写下关于这4年多的运维实践经验,从事了2年多游戏运维,1年多安全运维,1年大数据运维,相关行业信息不能算非常精通,但是熟悉和熟练还是相对可以的。
linux运维人员常用工具拓扑详见:
标签: linux rsync sed awk python
Mac pip install protobuf 安装失败
Installing collected packages: six, protobufFound existing installation: six 1.4.1
DEPRECATION: Uninstalling a distutils installed project (six) has been deprecated and will be removed in a future version. This is due to the fact that uninstalling a distutils project will only partially uninstall the project.
Uninstalling six-1.4.1:
Exception:
Traceback (most recent call last):
File "/Users/xiaodu/Library/Python/2.7/lib/python/site-packages/pip/basecommand.py", line 215, in main
status = self.run(options, args)
File "/Users/xiaodu/Library/Python/2.7/lib/python/site-packages/pip/commands/install.py", line 342, in run
prefix=options.prefix_path,
File "/Users/xiaodu/Library/Python/2.7/lib/python/site-packages/pip/req/req_set.py", line 778, in install
requirement.uninstall(auto_confirm=True)
解决mac下安装pymssql问题
mac环境:10.11.6
python:2.7.10
sudo pip install pymssql 后出现下面问题:
creating build/temp.macosx-10.11-intel-2.7
error: command 'gcc' failed with exit status 1
错误:error: command 'gcc' failed with exit status 1在 centons 使用pip安装Python模块出现error: command 'gcc' failed with exit status 1 ,明明装了gcc的,怎么会不行呢,然后发觉是failed不是not found,这说明这个错误个gcc没多大关系,应该是缺少某些功能模块,然后谷歌了一下,先后安装了python-devel,libffi-devel后还是不行,最后发觉要安装openssl-devel才行
可如下命令行安装:
yum install gcc libffi-devel python-devel openssl-devel
Python四种逐行读取文件内容的方法
下面是四种Python逐行读取文件内容的方法, 并分析了各种方法的优缺点及应用场景,以下代码在python3中测试通过, python2中运行部分代码已注释,稍加修改即可。方法一:readline函数
#-*- coding: UTF-8 -*-
f = open("./code.txt") # 返回一个文件对象
line = f.readline() # 调用文件的 readline()方法
while line:
#print line, # 在 Python 2中,后面跟 ',' 将忽略换行符
print(line, end = '') # 在 Python 3中使用
line = f.readline()
f.close()
优点:节省内存,不需要一次性把文件内容放入内存中
缺点:速度相对较慢
标签: python open fileinput readline readlines
Python 快速实现 FTP 服务器
有时当你想快速搭建一个 FTP 服务器来临时实现文件上传下载时,这是特别有用的。我们这里利用 Python 的 Pyftpdlib 模块可以快速的实现一个 FTP 服务器的功能。首先安装 Pyftpdlib 模块
$ sudo pip install pyftpdlib
The directory '/Users/xiaodu/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/Users/xiaodu/Library/Caches/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Collecting pyftpdlib
Installing collected packages: pyftpdlib
Successfully installed pyftpdlib-1.5.3
热门日志
分类
- shell(3)
- ssdb(1)
- Mac(7)
- C(1)
- memcache(1)
- Python(30)
- Vim(8)
- sed(2)
- ansible(3)
- awk(4)
- about(1)
- Django(4)
- git(7)
- bat(4)
- svn(0)
- docker(1)
- Tornado(1)
- go(1)
- 架构(17)
- Vue(1)
- Html(6)
- Java(8)
- Mysql(34)
- Ajax(2)
- Jsp(1)
- Struts(8)
- Linux(71)
- JavaScript(39)
- Staruml(0)
- Mouth(1)
- Php(102)
- Windows(8)
- Message(12)
- Lua(10)
- Compute(1)
- Redis(7)
- Nginx(11)
- Jquery(1)
- Apache(1)
- cocos2d-x(8)
最新日志
- MySQL 中的 distinct 和 group by 哪个效率更高
- MYSQL SQL 使用binary导致索引失效的问题分析与总结
- 架构设计中如何高效的实现接口幂等,通用的设计方案和解决方式
- nginx 如何在配置文件给静态文件添加缓存
- php serialize_precision 介绍
- Docker 那些事
- 欢迎您关注“刘善海价值分享”微信公众号!
- Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
- Linux vim/vi下backspace(退格键)出现^? 或^H
- python 如何通过subprocess.call调用自定义alias别名