subprocess
python3
crontab
stringOperation

Python3 + subprocess > crontabの設定を読取り、実行するスクリプト > string not in ... | string.lower() | subprocess.getoutput()

動作環境
GeForce GTX 1070 (8GB)
ASRock Z170M Pro4S [Intel Z170chipset]
Ubuntu 16.04 LTS desktop amd64
TensorFlow v1.2.1
cuDNN v5.1 for Linux
CUDA v8.0
Python 3.5.2
IPython 6.0.0 -- An enhanced Interactive Python.
gcc (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609
GNU bash, version 4.3.48(1)-release (x86_64-pc-linux-gnu)
scipy v0.19.1
geopandas v0.3.0
MATLAB R2017b (Home Edition)
ADDA v.1.3b6

Crontab

$crontab -u yasokada -l
...
# 
# For more information see the manual pages of crontab(5) and cron(8)
# 
# m h  dom mon dow   command
35 23 * * * /home/yasokada/BACKUP_TOOL_180128/yasokada_back_180128_exec

処理内容

  • crontab設定のコマンドを読取る
    • # m h dom mon dow commandの次の行だけ読取る
  • 読取ったコマンドを実行する

code v0.1

run_crontab_command_180128.py
# from subprocess import getoutput
import subprocess as sb
import sys

'''
v0.1 Jan. 28, 2018
  - add [SHELL]
  - add main()
  - add find_command()
  - add [CMD]
  - add [USER]
'''

# tested on Python 3.5.2
# tested on Ubuntu 16.04.3 LTS
# coding rule:PEP8

USER = "yasokada"
CMD = "crontab -u %s -l" % USER
SHELL = "bash -x"


def find_command():
    lists = sb.getoutput(CMD).split('\n')
    hasRead_m_h_line = False
    for elem in lists:
        if "m h  dom" in elem:
            hasRead_m_h_line = True
            continue
        # print(elem)
        if hasRead_m_h_line:
            return elem.split(' ')[-1]
    return None


def main():
    # 1. get command written in crontab
    cron_cmd = find_command()
    if cron_cmd is None:
        sys.exit(-1)

    # 2. confirm to execute command
    print('\ncommand is')
    print(cron_cmd)
    #
    wrk = input('Run[y/N]?')
    if len(wrk) == 0 or 'y' not in wrk.lower():
        print('Canceled')
        return

    # 3. execute command with bash
    run_cmd = '%s %s' % (SHELL, cron_cmd)
    sb.call(run_cmd.split())


if __name__ == '__main__':
    main()

run
$ python3 run_crontab_command_180128.py 
command is
/home/yasokada/BACKUP_TOOL_180128/yasokada_back_180128_exec
Run[y/N]?
...

'y'か'Y'を入力するとコマンドが実行される。

備考

  • 一つのコマンドしか実行しない
  • こちらのcodeを実行するより、crontab -l 実行してコピペしたコマンドを実行するほうが早い
  • Pythonの勉強のつもりで実装してみた

学んだ事項

(復習分も含む)

リンク

(追記 2018/01/29)

https://docs.python.jp/3/library/subprocess.html#subprocess.getoutput
https://docs.python.jp/3/library/subprocess.html
https://docs.python.jp/3/library/string.html