하위 프로세스 변경 디렉터리
하위 디렉터리 / 수퍼 디렉터리 내에서 스크립트를 실행하고 싶습니다 (먼저이 하위 / 수퍼 디렉터리에 있어야 함). subprocess
내 하위 디렉토리를 입력 할 수 없습니다 .
tducin@localhost:~/Projekty/tests/ve$ python
Python 2.7.4 (default, Sep 26 2013, 03:20:26)
[GCC 4.7.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> import os
>>> os.getcwd()
'/home/tducin/Projekty/tests/ve'
>>> subprocess.call(['cd ..'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/subprocess.py", line 524, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.7/subprocess.py", line 711, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1308, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
Python이 OSError를 던지고 이유를 모르겠습니다. 기존 하위 디렉토리로 이동하든 한 디렉토리 위로 이동하든 상관 없습니다 (위와 같이). 항상 동일한 오류가 발생합니다.
코드에서하려는 것은라는 프로그램을 호출하는 것 cd ..
입니다. 원하는 것은라는 명령을 호출하는 것 cd
입니다.
그러나 cd
쉘 내부입니다. 그래서 당신은 그것을 다음과 같이 부를 수 있습니다.
subprocess.call('cd ..', shell=True) # pointless code! See text below.
그러나 그렇게하는 것은 무의미합니다. 어떤 프로세스도 다른 프로세스의 작업 디렉토리를 변경할 수 없기 때문에 (최소한 UNIX와 유사한 OS에서는 물론 Windows에서도 마찬가지 임)이 호출은 서브 쉘이 디렉토리를 변경하고 즉시 종료되도록합니다.
원하는 것은 하위 프로세스를 실행하기 직전에 작업 디렉토리를 변경하는 명명 된 매개 변수 를 사용 os.chdir()
하거나 사용하여 얻을 수 있습니다 .subprocess
cwd
예를 들어, ls
루트 디렉토리에서 실행하려면 다음 중 하나를 수행 할 수 있습니다.
wd = os.getcwd()
os.chdir("/")
subprocess.Popen("ls")
os.chdir(wd)
또는 단순히
subprocess.Popen("ls", cwd="/")
your_command
다른 디렉토리에서 하위 프로세스로 실행하려면 @wim의 답변에 제안 된cwd
대로 매개 변수를 전달합니다 .
import subprocess
subprocess.check_call(['your_command', 'arg 1', 'arg 2'], cwd=working_dir)
자식 프로세스는 부모의 작업 디렉토리를 변경할 수 없습니다 ( 일반적으로 ). cd ..
하위 프로세스를 사용하여 자식 셸 프로세스에서 실행 하면 부모 Python 스크립트의 작업 디렉터리가 변경되지 않습니다. 즉, @glglgl의 답변에있는 코드 예제가 잘못되었습니다 . cd
쉘 내장 (별도의 실행 파일이 아님)이며 동일한 프로세스 에서만 디렉토리를 변경할 수 있습니다 .
실행 파일의 절대 경로를 사용하고 cwd
kwarg Popen
를 사용하여 작업 디렉토리를 설정 하려고 합니다. 문서를 참조하십시오 .
cwd가 None이 아닌 경우 자식의 현재 디렉토리는 실행되기 전에 cwd로 변경됩니다. 이 디렉토리는 실행 파일을 검색 할 때 고려되지 않으므로 cwd에 상대적인 프로그램 경로를 지정할 수 없습니다.
subprocess.call
subprocess
모듈의 다른 메소드 에는 cwd
매개 변수가 있습니다.
이 매개 변수는 프로세스를 실행할 작업 디렉토리를 결정합니다.
따라서 다음과 같이 할 수 있습니다.
subprocess.call('ls', shell=True, cwd='path/to/wanted/dir/')
문서 subprocess.popen-constructor 확인
이 답변을 기반으로 한 또 다른 옵션 : https://stackoverflow.com/a/29269316/451710
이를 통해 cd
동일한 프로세스에서 여러 명령 (예 :)을 실행할 수 있습니다 .
import subprocess
commands = '''
pwd
cd some-directory
pwd
cd another-directory
pwd
'''
process = subprocess.Popen('/bin/bash', stdin=subprocess.PIPE, stdout=subprocess.PIPE)
out, err = process.communicate(commands.encode('utf-8'))
print(out.decode('utf-8'))
나는 요즘 당신이 할 것이라고 생각합니다.
import subprocess
subprocess.run(["pwd"], cwd="sub-dir")
참고 URL : https://stackoverflow.com/questions/21406887/subprocess-changing-directory
'Development Tip' 카테고리의 다른 글
sqlite의 ALTER COLUMN (0) | 2020.11.06 |
---|---|
코드에서 android : versionName 매니페스트 요소 가져 오기 (0) | 2020.11.06 |
typescript 입력 onchange event.target.value (0) | 2020.11.06 |
iPhone에서 HTML 구문 분석 (0) | 2020.11.06 |
모든 배열이 C #에서 구현하는 인터페이스는 무엇입니까? (0) | 2020.11.06 |