실행 파일을 만들지 않고 프로세스를 사용하는 쉘에서는 Python2.5 래
-
05-07-2019 - |
문제
그냥 무엇 제목을 말한다:
- 이
subprocess
모듈로 사용할 수 없습니다 이 일을 해야에서 2.4 2.5 - 쉘 프로세스해야 되지 않을 양산을 인수를 전달.
설명(2),다음과 같은 코드를 살펴봅니다:
>>> x=os.system('foo arg')
sh: foo: not found
>>> x=os.popen('foo arg')
sh: foo: not found
>>>
당신이 볼 수 있습니다 os.system
고 os.popen
실행하고 주어진 명령("foo")시스템을 통해 쉘("sh").내가 이것을 원하지 않게 일어나(그렇지 않으면 못생긴'을 발견하지 않'메시지가 출력하는 프로그램 stderr 없이 제어).
마지막으로,내을 통과 할 수 있어야의 인수를 이 프로그램('arg'위의 예에서).
어떻게 하나 이 일에 대해서는 Python2.5 2.4?
해결책
Python 2.4에서 사용할 수있는 하위 프로세스 모듈을 사용해야 할 것입니다.
Popen("/home/user/foo" + " arg")
>>> Popen("foo arg", shell=False)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/subprocess.py", line 595, in __init__
errread, errwrite)
File "/usr/lib/python2.6/subprocess.py", line 1092, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
쉘을 사용하지 않으므로 전체 경로를 포함해야합니다.
http://docs.python.org/library/subprocess.html#replacing-os-system
또는 Subprocess.pipe를 Stderr 및 Stdout에 전달하여 메시지를 억제 할 수도 있습니다. 자세한 내용은 위의 링크를 참조하십시오.
다른 팁
앞에서 설명한 대로,당신은 할 수 있습니다(그리고해야한다)사용하여 하위 프로세스 모듈입니다.
기본적으로, shell
매개변수 False
.이것이 좋고,매우 안전하다.또한,당신은 당신이 필요하지 않을 통과하는 전체 경로를,그냥 통과하는 파일 이름 및 인수 순서로(tuple 또는 목록).
import subprocess
# This works fine
p = subprocess.Popen(["echo","2"])
# These will raise OSError exception:
p = subprocess.Popen("echo 2")
p = subprocess.Popen(["echo 2"])
p = subprocess.Popen(["echa", "2"])
사용할 수도 있습니다 이 두 편의 기능에 이미 정의된 하위 프로세스 모듈:
# Their arguments are the same as the Popen constructor
retcode = subprocess.call(["echo", "2"])
subprocess.check_call(["echo", "2"])
기억 리디렉션할 수 있습니다 stdout
그리고/또는 stderr
하기 PIPE
, 고,따라서 그것은 수 없이 인쇄 화면(그러나는 출력은 여전히 읽을 수 있에 의해 귀하의 프로그램).기본적으로, stdout
고 stderr
모두 None
, 미 리디렉션, 즉,사용하는 것과 동일한 표준출력/stderr 로 python 프로그램입니다.
또한 사용할 수 있습니다 shell=True
와 리디렉션 stdout
.stderr
하며,따라서 메시지가 인쇄됩니다:
# This will work fine, but no output will be printed
p = subprocess.Popen("echo 2", shell=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# This will NOT raise an exception, and the shell error message is redirected to PIPE
p = subprocess.Popen("echa 2", shell=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)