python 如何通过subprocess.call调用自定义alias别名

2019-1-20 孤独求学人 Python

为了更好的通过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

评论(0) 浏览(546)

python2 python3中long类型的区别

2018-10-31 孤独求学人 Python

python2 python3中long类型的区别

python2中有long类型

python3中没有long类型,只有int类型

标签: python long

评论(0) 浏览(1419)

'python' engine because the 'c' engine does not support regex separators

2018-10-2 孤独求学人 Python

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

评论(0) 浏览(3355)

RuntimeError: Python is not installed as a framework

2018-9-9 孤独求学人 Python

今天在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

评论(0) 浏览(2054)

从苦逼到牛逼,详解Linux运维工程师的打怪升级之路

2017-10-1 孤独求学人 Linux

运维工程师是从一个呆逼进化为苦逼再成长为牛逼的过程,前提在于你要能忍能干能拼,还要具有敏锐的嗅觉感知前方潮流变化。如:今年大数据,人工智能比较火……(相对表示就是 Python 比较火)

之前写过运维基础篇,发现对很多人收益挺大,接下来也写下关于这4年多的运维实践经验,从事了2年多游戏运维,1年多安全运维,1年大数据运维,相关行业信息不能算非常精通,但是熟悉和熟练还是相对可以的。


初级篇


linux运维人员常用工具拓扑详见:


阅读全文>>

标签: linux rsync sed awk python

评论(0) 浏览(19697)

Mac pip install protobuf 安装失败

2017-6-12 孤独求学人 Mac

Installing collected packages: six, protobuf
  Found 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)

阅读全文>>

标签: protobuf python pip

评论(0) 浏览(4207)

解决mac下安装pymssql问题

2017-6-11 孤独求学人 Mac


mac环境:10.11.6

python:2.7.10

sudo pip install pymssql 后出现下面问题:


creating build/temp.macosx-10.11-intel-2.7

cc -fno-strict-aliasing -fno-common -dynamic -arch i386 -arch x86_64 -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch i386 -arch x86_64 -pipe -I/usr/local/include -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c _mssql.c -o build/temp.macosx-10.11-intel-2.7/_mssql.o -DMSDBLIB
_mssql.c:266:10: fatal error: 'sqlfront.h' file not found
#include "sqlfront.h"
^
1 error generated.
error: command 'cc' failed with exit status 1

阅读全文>>

标签: python pip pymssql

评论(0) 浏览(19345)

error: command 'gcc' failed with exit status 1

2017-5-1 孤独求学人 Python

错误: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

阅读全文>>

标签: linux gcc python pip

评论(0) 浏览(17226)

Python四种逐行读取文件内容的方法

2017-3-27 孤独求学人 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

评论(0) 浏览(13658)

Python 快速实现 FTP 服务器

2017-2-16 孤独求学人 Python

有时当你想快速搭建一个 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

阅读全文>>

标签: python ftp pyftpdlib

评论(0) 浏览(11116)

Powered by emlog 沪ICP备2023034538号-1