programing

하위 프로세스 디렉터리 변경

kingscode 2023. 6. 10. 16:00
반응형

하위 프로세스 디렉터리 변경

하위 디렉터리/슈퍼 디렉터리 내에서 스크립트를 실행하려고 합니다(이 하위/슈퍼 디렉터리 내에 먼저 있어야 합니다).구할 수가 없습니다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에서는 변경할 수 없기 때문에) 이 호출은 하위 셸에서 dir를 변경하고 즉시 종료합니다.

고객이 원하는 것을 통해 달성할 수 있습니다.os.chdir() 는그와함께와 .subprocess parameter 명매 변수개된cwd하위 프로세스를 실행하기 직전에 작업 디렉토리를 변경합니다.

를 들어, 예들어를 하려면 다을실니다를 실행합니다.ls루트 디렉터리에서, 당신은 할 수 있습니다.

wd = os.getcwd()
os.chdir("/")
subprocess.Popen("ls")
os.chdir(wd)

아니면 간단히

subprocess.Popen("ls", cwd="/")

실행하기your_command다른 디렉토리의 하위 프로세스로, 통과cwd@parameter의 답변에 제시된 바와 같이 매개변수:

import subprocess

subprocess.check_call(['your_command', 'arg 1', 'arg 2'], cwd=working_dir)

하위 프로세스는 일반적으로 상위 프로세스의 작업 디렉토리를 변경할 수 없습니다.입니다.cd ..하위 프로세스를 사용하는 하위 프로세스에서는 부모 파이썬 스크립트의 작업 디렉터리를 변경하지 않습니다. 즉, @glgl's 답변의 코드 예제가 잘못되었습니다. cd별도의 실행 파일이 아닌 내장된 셸로, 동일한 프로세스에서만 디렉터리를 변경할 수 있습니다.

subprocess.call의 기타 subprocess에 " "가 있습니다.cwd매개 변수

이 매개 변수는 프로세스를 실행할 작업 디렉터리를 결정합니다.

따라서 다음과 같은 작업을 수행할 수 있습니다.

subprocess.call('ls', shell=True, cwd='path/to/wanted/dir/')

docs 하위 프로세스.popen-constructor를 확인하십시오.

파일에 하고 실행파대절경사용다사경용우는려하음을 하려고 합니다.cwd의 결점.Popen작업 디렉토리를 설정합니다.문서를 참조하십시오.

cwd가 None이 아닌 경우 실행되기 전에 자식의 현재 디렉터리가 cwd로 변경됩니다.실행 파일을 검색할 때 이 디렉터리가 고려되지 않으므로 cwd에 대한 프로그램 경로를 지정할 수 없습니다.

요즘에는 다음과 같은 일을 할 것입니다.

import subprocess

subprocess.run(["pwd"], cwd="sub-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'))

그냥 쓰기os.chdir
예:

>>> import os
>>> import subprocess
>>> # Lets Just Say WE want To List The User Folders
>>> os.chdir("/home/")
>>> subprocess.run("ls")
user1 user2 user3 user4

만약 당신이 cd 기능(syslog 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

디렉터리를 변경해야 하는 경우 명령을 실행하여 std 출력도 가져옵니다.

import os
import logging as log
from subprocess import check_output, CalledProcessError, STDOUT
log.basicConfig(level=log.DEBUG)

def cmd_std_output(cd_dir_path, cmd):
    cmd_to_list = cmd.split(" ")
    try:
        if cd_dir_path:
            os.chdir(os.path.abspath(cd_dir_path))
        output = check_output(cmd_to_list, stderr=STDOUT).decode()
        return output
    except CalledProcessError as e:
        log.error('e: {}'.format(e))
def get_last_commit_cc_cluster():
    cd_dir_path = "/repos/cc_manager/cc_cluster"
    cmd = "git log --name-status HEAD^..HEAD --date=iso"
    result = cmd_std_output(cd_dir_path, cmd)
    return result

log.debug("Output: {}".format(get_last_commit_cc_cluster()))

Output: "commit 3b3daaaaaaaa2bb0fc4f1953af149fa3921e\nAuthor: user1<user1@email.com>\nDate:   2020-04-23 09:58:49 +0200\n\n

언급URL : https://stackoverflow.com/questions/21406887/subprocess-changing-directory

반응형