ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • tempfile / subprocess
    python/기본 2022. 5. 2. 14:04
    import tempfile
    # 임시 디렉토리에서 압축을 푼다든지로 응용될 수 있음
    
    with tempfile.TemporaryFile(mode='w+') as t:
        t.write('hello')
        t.seek(0)
        print(t.read())  # hello
    
    with tempfile.NamedTemporaryFile(delete=False) as t:
        print(t.name)
        with open(t.name, 'w+') as f:
            f.write('test\n')
            f.seek(0)
            print(f.read())
    
    with tempfile.TemporaryDirectory() as td:
        print(td)
    
    ####################################################################
    import subprocess
    
    # 과거 방식: os.system('ls')
    r = subprocess.run(['ls', '-al'])
    print(r.returncode)
    
    # 야래 pipe 는 동작 하지 않음
    subprocess.run(['ls', '-al', '|', 'grep', 'test'])
    
    # pipe 를 사용하고 싶다면 ..
    p1 = subprocess.Popen(['ls', '-al'], stdout = subprocess.PIPE)
    p2 = subprocess.Popen(['grep', 'test'], stdin=p1.stdout, stdout=subprocess.PIPE)
    p1.stdout.close()
    output = p2.communicate()[0]
    print(output)

    'python > 기본' 카테고리의 다른 글

    requirements.txt 자동 생성하기  (0) 2022.05.31
    datetime / time  (0) 2022.05.02
    tar / zip  (0) 2022.05.02
    os, pathlib, glob, shutil  (0) 2022.05.01
    Template, Csv  (0) 2022.05.01

    댓글

Designed by Tistory.