LoginSignup
1
2

More than 5 years have passed since last update.

Pythonのサブプロセスを使ったメモ

Posted at

pipeで色々やりたい。意外と手こずった。。

  • encodeに気をつける
  • envを渡す
  • 標準出力を閉じるとかのタイミングの理解
  • subprocess.PIPEを使わずにcommuticateがいいのかも、、 pollとかもある。少し試してうまく使いこなせなかったのでパス。
    def _transrate(trans_opt):
        """
        翻訳
        """
        # import locale
        # enc = locale.getpreferredencoding()
        # env['PYTHONIOENCODING'] = enc
        command0 = '/usr/bin/pbpaste'
        command1 = '/usr/local/bin/trans' + trans_opt
        command2 = '/usr/bin/pbcopy'
        env = os.environ.copy()
        env["PATH"] = "/usr/bin:/usr/local/bin/:" + env['PATH']
        # command0
        process0 = subprocess.Popen(shlex.split(
            command0), stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)
        process0.wait()  # wait()は簡易的な実装
        # command1
        process1 = subprocess.Popen(shlex.split(
            command1), stdin=process0.stdout, stdout=subprocess.PIPE, env=env)
        process1.wait()  # wait()は簡易的な実装
        # Allow ps_process to receive a SIGPIPE if grep_process exits.
        process0.stdout.close()
        # command2
        process2 = subprocess.Popen(shlex.split(
            command2), stdin=process1.stdout, stdout=subprocess.PIPE, env=env)
        process2.wait()  # wait()は簡易的な実装
        # Allow ps_process to receive a SIGPIPE if grep_process exits.
        process1.stdout.close()
        # Allow ps_process to receive a SIGPIPE if grep_process exits.
        process2.stdout.close()

        """
        通知
        """
        process0 = subprocess.Popen(shlex.split(
            command0), stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)
        process0.wait()  # wait()は簡易的な実装
        output = process0.communicate()[0].decode('utf-8')
        process0.stdout.close()
        command3 = '/usr/bin/osascript -e \'display notification "'+output+'" with title "翻訳"\''
        subprocess.Popen(shlex.split(command3), env=env)

    def transrate_j2e():
        """
        翻訳
        """
        _transrate(' -b ja:en')
    def transrate_e2j():
        """
        翻訳
        """
        _transrate(' -b en:ja')

1
2
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
1
2