2013-07-17 5 views
0

몇 마디로 달성하려는 것은 디렉토리 변경 및 쉘에서 스크립트 호출입니다.파이썬 하위 프로세스 호출

지금까지 매우 좋은 디렉토리를 os.chdir()으로 변경했습니다.

그러나 주어진 작업의 두 번째 부분을 구문하는 방법을 이해할 수 없었습니다. 특히, 내가 호출하고자하는 명령은 /path-to-dir-of-the-script/script<inputfile.txt>outfile.txt이고 내 눈에는 적어도 문제는 입력 파일 (그리고 분명히 존재하지 않지만 출력 파일은 분명히 스크립트에 의해 생성 될 것입니다)이 두 가지 다른 것입니다 디렉토리.

다음과 같이 (lsprint은 디버깅과 감독 목적을위한 것입니다.) 다양한 수정과 함께 항상 오류가 발생합니다. 구문 에러 또는 두 개의 파일을 찾을 수있는 시스템 등 어느

import subprocess 
import os 
import sys 

subprocess.call(["ls"]) #read the contents of the current dir 
print 
os.dir('/path-to-dir') 
subprocess.call(["ls"]) 
print 
in_file = open(infile.txt) #i am not sure if declaring my files is a necessity. 
out_file = open (outfile.txt) 
com = /path-to-dir-of-the-script/script 
process = subprocess.call([com], stdin=infile.txt, stdout=outfile.txt) 

이 생성 그것의 마지막 구현 : NameError: name

is not defined INFILE 내 접근 방식에서 하나 이상의 오류가 (이 확신 양식을 제외하고 내 구문) 나는 아마 더 공부해야합니다. 지금까지 나는 Popen 예제와 2 개 또는 3 개의 관련 질문 here, herehere을 포함하는 doc을 살펴 보았습니다. 내가 나 자신 분명 몇 가지 메모 이루어지지 않은 경우

는 :

스크립트 파일은 같은 수준에 있지 않습니다. 이 명령은 유효하고 오류가없는 경우 완벽하게 작동합니다. 파일을 이동 시키거나 스크립트를 동일한 레벨로 이동 시키면 작동하지 않습니다.

제안 사항 당신은 다른 작업 디렉토리의 예와 스크립트를 실행 cwd 인수를 사용할 수

com = "/path-to-dir-of-the-script/script" 

가 :

subprocess.check_call(["ls"]) # read the contents of the current dir 
subprocess.check_call(["ls"], cwd="/path-to-dir") 

bash는 명령을 에뮬레이트하기

답변

1

사용은 예를 들어 파이썬에서 문자열을 만들 인용한다 :

$ /path-to-dir-of-the-script/script <inputfile.txt> outfile.txt 

subprocess 모듈을 사용하는 경우 :

import subprocess 

with open("inputfile.txt", "rb") as infile, open("outfile.txt", "wb") as outfile: 
    subprocess.check_call(["/path-to-dir-of-the-script/script"], 
          stdin=infile, stdout=outfile) 
+0

'subprocess' 모듈을 사용하여 제안한 두 번째 방법이 더 마음에 듭니다. 그것은 나를 위해 더 간단하고 외관상으로는 중대한 일한다! 감사 –

관련 문제