Hướng dẫn python run command and get output - python chạy lệnh và nhận đầu ra

Trong tất cả các phiên bản Python được duy trì chính thức, cách tiếp cận đơn giản nhất là sử dụng hàm

>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
3:

>>> subprocess.check_output(['ls', '-l'])
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'

>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
4 chạy một chương trình duy nhất lấy các đối số làm đầu vào.1 Nó trả về kết quả chính xác như được in thành
>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
5. Nếu bạn cần ghi đầu vào vào
>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
6, hãy bỏ qua các phần
>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
7 hoặc
>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
8. Nếu bạn muốn thực thi các lệnh shell phức tạp, hãy xem ghi chú trên
>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
9 khi kết thúc câu trả lời này.

Hàm

>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
4 hoạt động trong tất cả các phiên bản Python được duy trì chính thức. Nhưng đối với các phiên bản gần đây, một cách tiếp cận linh hoạt hơn có sẵn.

Các phiên bản hiện đại của Python (3,5 trở lên): >>> import subprocess >>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE) >>> result.stdout b'total 0\n-rw-r--r-- 1 memyself staff 0 Mar 14 11:04 files\n' 7

Nếu bạn đang sử dụng Python 3.5+ và không cần tương thích ngược, chức năng

>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
7 mới được khuyến nghị bởi tài liệu chính thức cho hầu hết các nhiệm vụ. Nó cung cấp một API cấp cao, rất chung cho mô-đun
>>> result.stdout.decode('utf-8')
'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
3. Để ghi lại đầu ra của chương trình, hãy chuyển cờ
>>> result.stdout.decode('utf-8')
'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
4 đến đối số từ khóa
>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
5. Sau đó truy cập thuộc tính
>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
5 của đối tượng
>>> result.stdout.decode('utf-8')
'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
7 đã trả về:Python 3.5+, and do not need backwards compatibility, the new
>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
7 function is recommended by the official documentation for most tasks. It provides a very general, high-level API for the
>>> result.stdout.decode('utf-8')
'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
3 module. To capture the output of a program, pass the
>>> result.stdout.decode('utf-8')
'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
4 flag to the
>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
5 keyword argument. Then access the
>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
5 attribute of the returned
>>> result.stdout.decode('utf-8')
'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
7 object:

>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'

Giá trị trả về là một đối tượng

>>> result.stdout.decode('utf-8')
'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
8, vì vậy nếu bạn muốn một chuỗi phù hợp, bạn sẽ cần phải
>>> result.stdout.decode('utf-8')
'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
9. Giả sử quy trình được gọi trả về chuỗi được mã hóa UTF-8:

>>> result.stdout.decode('utf-8')
'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'

Tất cả điều này có thể được nén thành một lớp lót nếu muốn:

>>> subprocess.run(['ls', '-l'], stdout=subprocess.PIPE).stdout.decode('utf-8')
'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'

Nếu bạn muốn chuyển đầu vào cho

>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
6 của quy trình, bạn có thể chuyển đối tượng
>>> result.stdout.decode('utf-8')
'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
8 cho đối số từ khóa
>>> subprocess.run(['ls', '-l'], stdout=subprocess.PIPE).stdout.decode('utf-8')
'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
2:

>>> cmd = ['awk', 'length($0) > 5']
>>> ip = 'foo\nfoofoo\n'.encode('utf-8')
>>> result = subprocess.run(cmd, stdout=subprocess.PIPE, input=ip)
>>> result.stdout.decode('utf-8')
'foofoo\n'

Bạn có thể nắm bắt lỗi bằng cách truyền

>>> subprocess.run(['ls', '-l'], stdout=subprocess.PIPE).stdout.decode('utf-8')
'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
3 (nắm bắt đến
>>> subprocess.run(['ls', '-l'], stdout=subprocess.PIPE).stdout.decode('utf-8')
'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
4) hoặc
>>> subprocess.run(['ls', '-l'], stdout=subprocess.PIPE).stdout.decode('utf-8')
'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
5 (nắm bắt đến
>>> subprocess.run(['ls', '-l'], stdout=subprocess.PIPE).stdout.decode('utf-8')
'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
6 cùng với đầu ra thông thường). Nếu bạn muốn
>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
7 ném một ngoại lệ khi quá trình trả về mã thoát khác không, bạn có thể vượt qua
>>> subprocess.run(['ls', '-l'], stdout=subprocess.PIPE).stdout.decode('utf-8')
'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
8. .

Các phiên bản sau của Python hợp lý hóa ở trên hơn nữa. Trong Python 3.7+, có thể đánh vần một lớp trên như thế này:

>>> subprocess.run(['ls', '-l'], capture_output=True, text=True).stdout
'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'

Sử dụng

>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
7 theo cách này chỉ thêm một chút phức tạp, so với cách làm việc cũ. Nhưng bây giờ bạn có thể làm hầu hết mọi thứ bạn cần làm với chức năng
>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
7.

Các phiên bản cũ của Python (3-3.4): Thêm về >>> import subprocess >>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE) >>> result.stdout b'total 0\n-rw-r--r-- 1 memyself staff 0 Mar 14 11:04 files\n' 4

Nếu bạn đang sử dụng phiên bản Python cũ hơn hoặc cần khả năng tương thích ngược khiêm tốn, bạn có thể sử dụng chức năng

>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
4 như được mô tả ngắn gọn ở trên. Nó đã có sẵn kể từ Python 2.7.

subprocess.check_output(*popenargs, **kwargs)  

Phải mất các đối số tương tự như

>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
8 (xem bên dưới) và trả về một chuỗi chứa đầu ra của chương trình. Sự khởi đầu của câu trả lời này có một ví dụ sử dụng chi tiết hơn. Trong Python 3.5+,
>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
4 tương đương với việc thực thi
>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
7 với
>>> subprocess.run(['ls', '-l'], stdout=subprocess.PIPE).stdout.decode('utf-8')
'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
8 và
>>> subprocess.run(['ls', '-l'], capture_output=True, text=True).stdout
'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
0 và chỉ trả về thuộc tính
>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
5.

Bạn có thể vượt qua

>>> subprocess.run(['ls', '-l'], stdout=subprocess.PIPE).stdout.decode('utf-8')
'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
5 để đảm bảo rằng các thông báo lỗi được bao gồm trong đầu ra trả về. Khi bảo mật không phải là một mối quan tâm, bạn cũng có thể chạy các lệnh shell phức tạp hơn bằng cách vượt qua
>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
9 như được mô tả ở cuối câu trả lời này.

Nếu bạn cần phải từ

>>> subprocess.run(['ls', '-l'], capture_output=True, text=True).stdout
'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
4 hoặc chuyển đầu vào cho quy trình,
>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
4 sẽ không tùy thuộc vào nhiệm vụ. Xem các ví dụ
>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
8 dưới đây trong trường hợp đó.

Các ứng dụng phức tạp và phiên bản di sản của Python (2.6 trở xuống): >>> import subprocess >>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE) >>> result.stdout b'total 0\n-rw-r--r-- 1 memyself staff 0 Mar 14 11:04 files\n' 8

Nếu bạn cần khả năng tương thích ngược sâu hoặc nếu bạn cần chức năng tinh vi hơn

>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
4 hoặc
>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
7 cung cấp, bạn sẽ phải làm việc trực tiếp với các đối tượng
>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
8, gói gọn API cấp thấp cho các quy trình con.

Trình xây dựng

>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
8 chấp nhận một lệnh duy nhất mà không có đối số hoặc danh sách chứa lệnh là mục đầu tiên của nó, theo sau là bất kỳ số lượng đối số nào, mỗi mục là một mục riêng biệt trong danh sách.
subprocess.check_output(*popenargs, **kwargs)  
2 có thể giúp phân tích các chuỗi vào các danh sách được định dạng phù hợp. Các đối tượng
>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
8 cũng chấp nhận một loạt các đối số khác nhau để quản lý IO và cấu hình cấp thấp.a single command without arguments, or a list containing a command as its first item, followed by any number of arguments, each as a separate item in the list.
subprocess.check_output(*popenargs, **kwargs)  
2 can help parse strings into appropriately formatted lists.
>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
8 objects also accept a host of different arguments for process IO management and low-level configuration.

Để gửi đầu vào và đầu ra,

subprocess.check_output(*popenargs, **kwargs)  
4 hầu như luôn luôn là phương pháp ưa thích. Như trong:

output = subprocess.Popen(["mycmd", "myarg"], 
                          stdout=subprocess.PIPE).communicate()[0]

Hoặc

>>> import subprocess
>>> p = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE, 
...                                    stderr=subprocess.PIPE)
>>> out, err = p.communicate()
>>> print out
.
..
foo

Nếu bạn đặt

subprocess.check_output(*popenargs, **kwargs)  
5,
subprocess.check_output(*popenargs, **kwargs)  
4 cũng cho phép bạn truyền dữ liệu cho quy trình thông qua
>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
6:

>>> cmd = ['awk', 'length($0) > 5']
>>> p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
...                           stderr=subprocess.PIPE,
...                           stdin=subprocess.PIPE)
>>> out, err = p.communicate('foo\nfoofoo\n')
>>> print out
foofoo

Lưu ý câu trả lời của Aaron Hall, chỉ ra rằng trên một số hệ thống, bạn có thể cần phải đặt

>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
5,
>>> subprocess.run(['ls', '-l'], capture_output=True, text=True).stdout
'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
4 và
>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
6 tất cả thành
output = subprocess.Popen(["mycmd", "myarg"], 
                          stdout=subprocess.PIPE).communicate()[0]
1 (hoặc
output = subprocess.Popen(["mycmd", "myarg"], 
                          stdout=subprocess.PIPE).communicate()[0]
2) để có được
subprocess.check_output(*popenargs, **kwargs)  
4 hoạt động.

Trong một số trường hợp hiếm hoi, bạn có thể cần chụp đầu ra thời gian thực phức tạp. Câu trả lời của Vartec cho thấy một con đường phía trước, nhưng các phương pháp khác ngoài

subprocess.check_output(*popenargs, **kwargs)  
4 dễ bị bế tắc nếu không được sử dụng cẩn thận.

Như với tất cả các chức năng trên, khi bảo mật không phải là một mối quan tâm, bạn có thể chạy các lệnh shell phức tạp hơn bằng cách vượt qua

>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
9.

Ghi chú

1. Chạy các lệnh shell: đối số

>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
9

Thông thường, mỗi cuộc gọi đến

>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
7,
>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
4 hoặc hàm tạo
>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
8 thực thi một chương trình duy nhất. Điều đó có nghĩa là không có đường ống kiểu bash lạ mắt. Nếu bạn muốn chạy các lệnh shell phức tạp, bạn có thể vượt qua
>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
9, mà cả ba chức năng đều hỗ trợ. Ví dụ:

>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
0

Tuy nhiên, làm điều này làm tăng mối quan tâm an ninh. Nếu bạn đang làm bất cứ điều gì nhiều hơn kịch bản ánh sáng, bạn có thể gọi riêng từng quy trình và chuyển đầu ra từ mỗi đầu vào sang đầu vào, thông qua

>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
1

Hoặc

>>> import subprocess
>>> result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
>>> result.stdout
b'total 0\n-rw-r--r--  1 memyself  staff  0 Mar 14 11:04 files\n'
2

Sự cám dỗ để kết nối trực tiếp các đường ống là mạnh mẽ; chống lại nó. Nếu không, bạn có thể sẽ thấy bế tắc hoặc phải làm những việc hack như thế này.

Lệnh Python cho đầu ra là gì?

Cách cơ bản để làm đầu ra là câu lệnh in. Để kết thúc dòng in bằng một dòng mới, thêm một câu lệnh in mà không có bất kỳ đối tượng nào. Điều này sẽ in cho bất kỳ đối tượng nào thực hiện write (), bao gồm các đối tượng tệp.print statement. To end the printed line with a newline, add a print statement without any objects. This will print to any object that implements write(), which includes file objects.

Có một lệnh chạy trong Python?

Lệnh chạy () trả về mã thoát của những gì đã được thực thi.Không giống như hệ điều hành.hệ thống (), lưu ý cách xử lý con.chạy () yêu cầu một danh sách các chuỗi làm đầu vào thay vì một chuỗi. returns the exit code of what was executed. Unlike os. system() , note how subprocess. run() requires a list of strings as input instead of a single string.