Popen.terminate()関数を使用できるため、Python 2.6 のバージョンのサブプロセスを使用したいと考えていますが、Python 2.5 に行き詰まっています。私の 2.5 コードで新しいバージョンのモジュールを使用する合理的なクリーンな方法はありますか? ある種のfrom __future__ import subprocess_module
?
6 に答える
この質問には既に回答があることは知っていますが、その価値があるためsubprocess.py
、Python 2.3 で Python 2.6 に同梱されている を使用しましたが、問題なく動作しました。ファイルの上部にあるコメントを読むと、次のように書かれています。
# This module should remain compatible with Python 2.2, see PEP 291.
それを行うための素晴らしい方法は本当にありません。subprocess は(C ではなく) python で実装されているため、モジュールをどこかにコピーして使用することができます (もちろん、2.6 の良さを使用しないことを願っています)。
一方、サブプロセスが主張することを単純に実装し、* nix で SIGTERM を送信し、Windows で TerminateProcess を呼び出す関数を作成することもできます。次の実装は、Linux および Win XP VM でテスト済みです。python Windows 拡張機能が必要です。
import sys
def terminate(process):
"""
Kills a process, useful on 2.5 where subprocess.Popens don't have a
terminate method.
Used here because we're stuck on 2.5 and don't have Popen.terminate
goodness.
"""
def terminate_win(process):
import win32process
return win32process.TerminateProcess(process._handle, -1)
def terminate_nix(process):
import os
import signal
return os.kill(process.pid, signal.SIGTERM)
terminate_default = terminate_nix
handlers = {
"win32": terminate_win,
"linux2": terminate_nix
}
return handlers.get(sys.platform, terminate_default)(process)
terminate
そうすれば、モジュール全体ではなく、コードのみを維持する必要があります。
Python 2.5でのpython 2.6 subprocess.pyの使用に関するKamil Kisielの提案に従いましたが、完全に機能しました。簡単にするために、easy_install および/または buildout に含めることができる distutils パッケージを作成しました。
Python 2.5 プロジェクトで Python 2.6 のサブプロセスを使用するには:
easy_install taras.python26
あなたのコードで
from taras.python26 import subprocess
ビルドアウト中
[buildout]
parts = subprocess26
[subprocess26]
recipe = zc.recipe.egg
eggs = taras.python26
これはあなたの質問に直接答えるものではありませんが、知っておく価値はあります。
からのインポートは__future__
実際にはコンパイラ オプションのみを変更するため、with をステートメントに変換したり、文字列リテラルを str ではなく Unicode に変換したりできますが、Python 標準ライブラリのモジュールの機能や機能を変更することはできません。
http://code.activestate.com/recipes/347462/から直接取得した、Windowsでプロセスを終了するいくつかの方法を次に示し ます。
# Create a process that won't end on its own
import subprocess
process = subprocess.Popen(['python.exe', '-c', 'while 1: pass'])
# Kill the process using pywin32
import win32api
win32api.TerminateProcess(int(process._handle), -1)
# Kill the process using ctypes
import ctypes
ctypes.windll.kernel32.TerminateProcess(int(process._handle), -1)
# Kill the proces using pywin32 and pid
import win32api
PROCESS_TERMINATE = 1
handle = win32api.OpenProcess(PROCESS_TERMINATE, False, process.pid)
win32api.TerminateProcess(handle, -1)
win32api.CloseHandle(handle)
# Kill the proces using ctypes and pid
import ctypes
PROCESS_TERMINATE = 1
handle = ctypes.windll.kernel32.OpenProcess(PROCESS_TERMINATE, False, process.pid)
ctypes.windll.kernel32.TerminateProcess(handle, -1)
ctypes.windll.kernel32.CloseHandle(handle)
Python はオープン ソースです。その pthread 関数を 2.6 から自由に取得して、独自のコードに移動したり、独自のコードを実装するための参照として使用したりできます。
明らかな理由から、新しいバージョンの一部をインポートできる Python のハイブリッドを持つ方法はありません。