0
0

More than 3 years have passed since last update.

[04] subprocessの代替パッケージ「sh」を使ってみる ... sudo を使う

Last updated at Posted at 2021-08-04
本シリーズのトップページ
https://qiita.com/robozushi10/items/fabde36bb9a312347bc7

はじめに

一般的に Python で Linux コマンドを使う場合は subprocess を使うこと多い.
が、標準パッケージでは無いものの subprocess の代替である「sh」(amoffat/sh) も便利である.1

個人的な考えではあるが、「sh2」は標準パッケージでは無いので、職場などで使い込むと
他者の迷惑になり兼ねない。しかし、適度に使う分には subprocess よりも速く実装できて
好都合なので書き残しておく.

前項では sh.find を使ったが、探索権限が無いディレクトリにアクセスすると例外が発生してしまう.
そこで、本項では「「sh」で sudo の使用する方法」を記す.

この実装方法であれば シェルスクリプトに近い感覚で実装できるので、
subprocess よりも速く実装できるのではないかと思う.

セットアップ

pip 等で sh をインストールする.
詳細は本項末尾の「参考情報」に記した.

使用例

004.py ... パスワードを毎回入力する

公式ドキュメントsh.contrib.sudo による実装方法にする.

なお、sudo のたびにパスワードを毎回入力する必要がある.

コード

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys; sys.dont_write_bytecode = True
import os
import traceback
import sh

if __name__ == '__main__':
  T = '{0}/work/'.format(os.environ['HOME'])
  for d in sh.contrib.sudo.find(T, '-maxdepth', '4', '-type', 'd', '-name', '.git'):
    try:
      absp = os.path.abspath(d).rstrip()
      print(absp)
    except:
      traceback.print_exc(file=sys.stdout)

 

実行結果

[sudo] password for foo: 🈲🈲パスワード入力する🈲🈲
/home/foo/work/wiki/02_software/xx/.git
/home/foo/work/wiki/02_software/git-lfs/.git
/home/foo/work/wiki/02_software/git-lfs2/.git
/home/foo/work/wiki/02_software/xx2/.git
/home/foo/work/LOCAL_GITLAB/fluentd/.git
/home/foo/work/fluentd/.git

参考情報

項目 URL 一言
Pypi sh https://pypi.org/project/sh/
公式ドキュメント - トップページ https://amoffat.github.io/sh/
公式ドキュメント - API逆引き https://amoffat.github.io/sh/reference.html
チュートリアル https://amoffat.github.io/sh/tutorials ここで実現したい機能を検索しながら使うことが多い
もた日記 https://wonderwall.hatenablog.com/entry/2017/07/30/083000

検討環境

DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=18.04
DISTRIB_CODENAME=bionic
DISTRIB_DESCRIPTION="Ubuntu 18.04.4 LTS"

 

以上


  1. 私は職場で別の方が使用していて知った 

  2. パッケージ名が「sh」だと検索し辛い.. 

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0