하위 디렉터리 / 수퍼 디렉터리 내에서 스크립트를 실행하고 싶습니다 (먼저이 하위 / 수퍼 디렉터리에 있어야 함). 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
파이썬은 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/')
답변
이 답변을 기반으로 한 또 다른 옵션 : 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")
답변
cd 기능 (shell = True 가정)을 원하고 Python 스크립트 측면에서 디렉토리를 변경하려는 경우이 코드를 사용하면 ‘cd’명령이 작동 할 수 있습니다.
import subprocess
import os
def cd(cmd):
#cmd is expected to be something like "cd [place]"
cmd = cmd + " && pwd" # add the pwd command to run after, this will get our directory after running cd
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) # run our new command
out = p.stdout.read()
err = p.stderr.read()
# read our output
if out != "":
print(out)
os.chdir(out[0:len(out) - 1]) # if we did get a directory, go to there while ignoring the newline
if err != "":
print(err) # if that directory doesn't exist, bash/sh/whatever env will complain for us, so we can just use that
return