Đầu ra quy trình con chụp Python

Tất cả các ví dụ sử dụng Python 3. 5 trở lên (trừ khi được ghi chú) và cho rằng bạn đang chạy Linux hoặc hệ điều hành dựa trên unix

Tất cả các ví dụ có thể được tìm thấy trên sổ ghi chép Jupyter này

gọi () ví dụ

Sử dụng

subprocess.call("ls -lha", shell=True)
# returns 0 (the return code)
1 thay thế trên Python v3. 5+

Khi bạn truyền một loạt các lệnh và tham số

subprocess.call("ls -lha", shell=True)
# returns 0 (the return code)
2 trả về mã trả về của quy trình được gọi

import subprocess

subprocess.call(["ls", "-lha"])
# >>> 0 (the return code)

quy trình con. call() không đưa ra một ngoại lệ nếu các lỗi quá trình cơ bản

import subprocess

# no Python Exception is thrown!
subprocess.call(["./bash-script-with-bad-syntax"])
# >>> 127

call() ví dụ với shell=True

Sử dụng

subprocess.call("ls -lha", shell=True)
# returns 0 (the return code)
1 thay thế trên Python v3. 5+

Nếu

subprocess.call("ls -lha", shell=True)
# returns 0 (the return code)
4, chuỗi lệnh được hiểu là lệnh shell thô

Việc sử dụng

subprocess.call("ls -lha", shell=True)
# returns 0 (the return code)
4 có thể khiến bạn bị chèn mã nếu bạn sử dụng đầu vào của người dùng để tạo chuỗi lệnh

subprocess.call("ls -lha", shell=True)
# returns 0 (the return code)

ví dụ call(), chụp thiết bị xuất chuẩn và thiết bị xuất chuẩn

Nếu bạn đang sử dụng Python 3. 5+, thay vào đó hãy sử dụng

subprocess.call("ls -lha", shell=True)
# returns 0 (the return code)
6 vì nó an toàn hơn

import subprocess
import sys

# create two files to hold the output and errors, respectively
with open('out.txt','w+') as fout:
    with open('err.txt','w+') as ferr:
        out=subprocess.call(["ls",'-lha'],stdout=fout,stderr=ferr)
        # reset file to read from it
        fout.seek(0)
        # save output (if any) in variable
        output=fout.read())

        # reset file to read from it
        ferr.seek(0) 
        # save errors (if any) in variable
        errors = ferr.read()

output
# total 20K
# drwxrwxr-x  3 felipe felipe 4,0K Nov  4 15:28 .
# drwxrwxr-x 39 felipe felipe 4,0K Nov  3 18:31 ..
# drwxrwxr-x  2 felipe felipe 4,0K Nov  3 19:32 .ipynb_checkpoints
# -rw-rw-r--  1 felipe felipe 5,5K Nov  4 15:28 main.ipynb

errors
# '' empty string

ví dụ call(), bắt buộc ngoại lệ nếu quá trình gây ra lỗi

Sử dụng

subprocess.call("ls -lha", shell=True)
# returns 0 (the return code)
7

import subprocess

# unlike subprocess.call, this throws a CalledProcessError
# if the underlying process errors out
subprocess.check_call(["./bash-script-with-bad-syntax"])

Chạy lệnh và chụp đầu ra

Sử dụng

subprocess.call("ls -lha", shell=True)
# returns 0 (the return code)
8 chuyển đổi đầu ra thành một chuỗi thay vì một mảng byte

  • Python phiên bản 2. 7 -> 3. 4

    import subprocess
    
    # errors in the created process are raised here too
    output = subprocess.check_output(["ls","-lha"],universal_newlines=True)
    
    output
    # total 20K
    # drwxrwxr-x  3 felipe felipe 4,0K Nov  4 15:28 .
    # drwxrwxr-x 39 felipe felipe 4,0K Nov  3 18:31 ..
    # drwxrwxr-x  2 felipe felipe 4,0K Nov  3 19:32 .ipynb_checkpoints
    # -rw-rw-r--  1 felipe felipe 5,5K Nov  4 15:28 main.ipynb
    

  • Python phiên bản 3. 5+

    import subprocess
    
    # run() returns a CompletedProcess object if it was successful
    # errors in the created process are raised here too
    process = subprocess.run(['ls','-lha'], check=True, stdout=subprocess.PIPE, universal_newlines=True)
    output = process.stdout
    
    output
    # total 20K
    # drwxrwxr-x  3 felipe felipe 4,0K Nov  4 15:28 .
    # drwxrwxr-x 39 felipe felipe 4,0K Nov  3 18:31 ..
    # drwxrwxr-x  2 felipe felipe 4,0K Nov  3 19:32 .ipynb_checkpoints
    # -rw-rw-r--  1 felipe felipe 5,5K Nov  4 15:28 main.ipynb
    

Chạy chuỗi thô dưới dạng dòng lệnh Shell

Đừng làm điều này nếu chuỗi của bạn sử dụng đầu vào của người dùng, vì họ có thể chèn mã tùy ý

Điều này tương tự như ví dụ trên, với

subprocess.call("ls -lha", shell=True)
# returns 0 (the return code)
4

  • Python phiên bản 2. 7 -> 3. 4

    import subprocess
    
    # errors in the created process are raised here too
    output = subprocess.check_output("ls -lha", shell=True, universal_newlines=True)
    
    output
    # total 20K
    # drwxrwxr-x  3 felipe felipe 4,0K Nov  4 15:28 .
    # drwxrwxr-x 39 felipe felipe 4,0K Nov  3 18:31 ..
    # drwxrwxr-x  2 felipe felipe 4,0K Nov  3 19:32 .ipynb_checkpoints
    # -rw-rw-r--  1 felipe felipe 5,5K Nov  4 15:28 main.ipynb
    

  • Python phiên bản 3. 5+

    import subprocess
    
    # run() returns a CompletedProcess object if it was successful
    # errors in the created process are raised here too
    process = subprocess.run('ls -lha', shell=True, check=True, stdout=subprocess.PIPE, universal_newlines=True)
    output = process.stdout
    
    output
    # total 20K
    # drwxrwxr-x  3 felipe felipe 4,0K Nov  4 15:28 .
    # drwxrwxr-x 39 felipe felipe 4,0K Nov  3 18:31 ..
    # drwxrwxr-x  2 felipe felipe 4,0K Nov  3 19:32 .ipynb_checkpoints
    # -rw-rw-r--  1 felipe felipe 5,5K Nov  4 15:28 main.ipynb
    

chạy () ví dụ. chạy lệnh và nhận mã trả về

subprocess.call("ls -lha", shell=True)
# returns 0 (the return code)
1 hầu như hoạt động giống như
import subprocess
import sys

# create two files to hold the output and errors, respectively
with open('out.txt','w+') as fout:
    with open('err.txt','w+') as ferr:
        out=subprocess.call(["ls",'-lha'],stdout=fout,stderr=ferr)
        # reset file to read from it
        fout.seek(0)
        # save output (if any) in variable
        output=fout.read())

        # reset file to read from it
        ferr.seek(0) 
        # save errors (if any) in variable
        errors = ferr.read()

output
# total 20K
# drwxrwxr-x  3 felipe felipe 4,0K Nov  4 15:28 .
# drwxrwxr-x 39 felipe felipe 4,0K Nov  3 18:31 ..
# drwxrwxr-x  2 felipe felipe 4,0K Nov  3 19:32 .ipynb_checkpoints
# -rw-rw-r--  1 felipe felipe 5,5K Nov  4 15:28 main.ipynb

errors
# '' empty string
1 và bạn nên sử dụng nó thay vì call() cho phiên bản 3. 5 trở đi

quy trình con. run() không đưa ra một ngoại lệ nếu các lỗi quá trình cơ bản

import subprocess

cp = subprocess.run(["ls","-lha"])

cp
# CompletedProcess(args=['ls', '-lha'], returncode=0)

chạy () ví dụ. chạy lệnh, buộc ngoại lệ nếu lỗi quy trình

Sử dụng

import subprocess
import sys

# create two files to hold the output and errors, respectively
with open('out.txt','w+') as fout:
    with open('err.txt','w+') as ferr:
        out=subprocess.call(["ls",'-lha'],stdout=fout,stderr=ferr)
        # reset file to read from it
        fout.seek(0)
        # save output (if any) in variable
        output=fout.read())

        # reset file to read from it
        ferr.seek(0) 
        # save errors (if any) in variable
        errors = ferr.read()

output
# total 20K
# drwxrwxr-x  3 felipe felipe 4,0K Nov  4 15:28 .
# drwxrwxr-x 39 felipe felipe 4,0K Nov  3 18:31 ..
# drwxrwxr-x  2 felipe felipe 4,0K Nov  3 19:32 .ipynb_checkpoints
# -rw-rw-r--  1 felipe felipe 5,5K Nov  4 15:28 main.ipynb

errors
# '' empty string
2 để buộc phương thức Python đưa ra một ngoại lệ nếu quy trình cơ bản gặp lỗi

import subprocess

# no Python Exception is thrown!
subprocess.call(["./bash-script-with-bad-syntax"])
# >>> 127
0

chạy () ví dụ. sử dụng shell=True

Như trong ví dụ call(),

subprocess.call("ls -lha", shell=True)
# returns 0 (the return code)
4, chuỗi lệnh được hiểu là lệnh shell thô

Một lần nữa, việc sử dụng

subprocess.call("ls -lha", shell=True)
# returns 0 (the return code)
4 có thể khiến bạn bị chèn mã nếu bạn sử dụng đầu vào của người dùng để tạo chuỗi lệnh

import subprocess

# no Python Exception is thrown!
subprocess.call(["./bash-script-with-bad-syntax"])
# >>> 127
1

chạy () ví dụ. lưu trữ đầu ra và thông báo lỗi trong chuỗi

Nếu quy trình cơ bản trả về mã thoát khác không, bạn sẽ không nhận được ngoại lệ;

  • trường hợp 1. xử lý trả về 0 mã thoát

    import subprocess
    
    # no Python Exception is thrown!
    subprocess.call(["./bash-script-with-bad-syntax"])
    # >>> 127
    
    2

  • trường hợp 2. quá trình trả về mã thoát khác không

    import subprocess
    
    # no Python Exception is thrown!
    subprocess.call(["./bash-script-with-bad-syntax"])
    # >>> 127
    
    3

  • trường hợp 3. các lỗi cấp hệ điều hành khác

    trường hợp này sẽ ném một ngoại lệ bất kể điều gì. Ví dụ: nếu bạn gọi một tệp thực thi không tồn tại. Điều này đưa ra một ngoại lệ vì không phải quy trình con có lỗi - nó chưa bao giờ được tạo ngay từ đầu

    import subprocess
    
    # no Python Exception is thrown!
    subprocess.call(["./bash-script-with-bad-syntax"])
    # >>> 127
    
    4

ví dụ về giáo hoàng. chạy lệnh và nhận mã trả về

được sử dụng cho các ví dụ phức tạp hơn khi bạn cần. Nhìn thấy

Điều này khiến chương trình python bị chặn cho đến khi quy trình con trả về

import subprocess

# no Python Exception is thrown!
subprocess.call(["./bash-script-with-bad-syntax"])
# >>> 127
5

ví dụ về giáo hoàng. Lưu trữ đầu ra và thông báo lỗi trong chuỗi

import subprocess

# no Python Exception is thrown!
subprocess.call(["./bash-script-with-bad-syntax"])
# >>> 127
6

ví dụ về giáo hoàng. Chuyển hướng đầu ra sang tập tin

import subprocess

# no Python Exception is thrown!
subprocess.call(["./bash-script-with-bad-syntax"])
# >>> 127
7

ví dụ về giáo hoàng. Chuyển hướng đầu ra và lỗi vào cùng một tệp

import subprocess

# no Python Exception is thrown!
subprocess.call(["./bash-script-with-bad-syntax"])
# >>> 127
8

ví dụ về giáo hoàng. Chạy lệnh trong nền

Theo mặc định, các cuộc gọi đến ____9_______7 sinh ra một quy trình con trong nền và không đợi nó kết thúc (trừ khi bạn sử dụng ____________8 trên đối tượng Popen)

Nối các lệnh lại với nhau

Sử dụng

import subprocess
import sys

# create two files to hold the output and errors, respectively
with open('out.txt','w+') as fout:
    with open('err.txt','w+') as ferr:
        out=subprocess.call(["ls",'-lha'],stdout=fout,stderr=ferr)
        # reset file to read from it
        fout.seek(0)
        # save output (if any) in variable
        output=fout.read())

        # reset file to read from it
        ferr.seek(0) 
        # save errors (if any) in variable
        errors = ferr.read()

output
# total 20K
# drwxrwxr-x  3 felipe felipe 4,0K Nov  4 15:28 .
# drwxrwxr-x 39 felipe felipe 4,0K Nov  3 18:31 ..
# drwxrwxr-x  2 felipe felipe 4,0K Nov  3 19:32 .ipynb_checkpoints
# -rw-rw-r--  1 felipe felipe 5,5K Nov  4 15:28 main.ipynb

errors
# '' empty string
9

import subprocess

# no Python Exception is thrown!
subprocess.call(["./bash-script-with-bad-syntax"])
# >>> 127
9

Đợi lệnh kết thúc, không đồng bộ

Sử dụng và chờ đợi

Phương thức

import subprocess

# unlike subprocess.call, this throws a CalledProcessError
# if the underlying process errors out
subprocess.check_call(["./bash-script-with-bad-syntax"])
0 hoạt động tương tự như phương pháp
import subprocess
import sys

# create two files to hold the output and errors, respectively
with open('out.txt','w+') as fout:
    with open('err.txt','w+') as ferr:
        out=subprocess.call(["ls",'-lha'],stdout=fout,stderr=ferr)
        # reset file to read from it
        fout.seek(0)
        # save output (if any) in variable
        output=fout.read())

        # reset file to read from it
        ferr.seek(0) 
        # save errors (if any) in variable
        errors = ferr.read()

output
# total 20K
# drwxrwxr-x  3 felipe felipe 4,0K Nov  4 15:28 .
# drwxrwxr-x 39 felipe felipe 4,0K Nov  3 18:31 ..
# drwxrwxr-x  2 felipe felipe 4,0K Nov  3 19:32 .ipynb_checkpoints
# -rw-rw-r--  1 felipe felipe 5,5K Nov  4 15:28 main.ipynb

errors
# '' empty string
7 nhưng việc gọi
import subprocess
import sys

# create two files to hold the output and errors, respectively
with open('out.txt','w+') as fout:
    with open('err.txt','w+') as ferr:
        out=subprocess.call(["ls",'-lha'],stdout=fout,stderr=ferr)
        # reset file to read from it
        fout.seek(0)
        # save output (if any) in variable
        output=fout.read())

        # reset file to read from it
        ferr.seek(0) 
        # save errors (if any) in variable
        errors = ferr.read()

output
# total 20K
# drwxrwxr-x  3 felipe felipe 4,0K Nov  4 15:28 .
# drwxrwxr-x 39 felipe felipe 4,0K Nov  3 18:31 ..
# drwxrwxr-x  2 felipe felipe 4,0K Nov  3 19:32 .ipynb_checkpoints
# -rw-rw-r--  1 felipe felipe 5,5K Nov  4 15:28 main.ipynb

errors
# '' empty string
8 và
import subprocess

# unlike subprocess.call, this throws a CalledProcessError
# if the underlying process errors out
subprocess.check_call(["./bash-script-with-bad-syntax"])
3 trên các đối tượng được trả về không chặn bộ xử lý, vì vậy trình thông dịch Python có thể được sử dụng trong những việc khác trong khi quy trình con bên ngoài không trả về

Làm cách nào để bắt đầu ra của quy trình con Python?

Có hai cách để làm như vậy. .
chuyển capture_output=True sang quy trình con. chạy()
quy trình con. check_output() nếu bạn chỉ muốn thiết bị xuất chuẩn

Làm cách nào để nắm bắt đầu ra trong cuộc gọi quy trình con?

Nếu bạn muốn nắm bắt đầu ra của lệnh, bạn nên sử dụng quy trình con. check_output() . Nó chạy lệnh với các đối số và trả về đầu ra của nó dưới dạng chuỗi byte. Bạn có thể giải mã chuỗi byte thành chuỗi bằng hàm decode().

Đầu ra của quy trình con gọi Python là gì?

Hàm call() quy trình con của Python trả về mã đã thực thi của chương trình . Nếu không có đầu ra chương trình, hàm sẽ trả về đoạn mã mà nó đã thực hiện thành công. Nó cũng có thể gây ra ngoại lệ CalledProcessError.

Sự khác biệt giữa Check_output và Popen là gì?

Sự khác biệt chính là, trong khi popen là một chức năng không chặn (có nghĩa là bạn có thể tiếp tục thực hiện chương trình mà không cần đợi lệnh gọi kết thúc), cả lệnh gọi và check_output . Sự khác biệt khác là ở những gì họ trả lại. popen trả về một đối tượng Popen. gọi trả về thuộc tính returncode. . The other difference is in what they return: popen returns a Popen object . call returns the returncode attribute.