22 tháng 4 năm 2019
Mục lục
- Sử dụng mô -đun HĐH
- Sử dụng mô -đun phụ
- Sự kết luận
- Tài nguyên
Python là một ngôn ngữ tuyệt vời để viết kịch bản và tự động hóa quy trình công việc và nó được đóng gói với các công cụ hữu ích trong hộp với thư viện tiêu chuẩn Python. Một điều phổ biến cần làm, đặc biệt là đối với một sysadmin, là thực thi các lệnh shell. Nhưng những gì thường sẽ kết thúc trong một tệp bash hoặc hàng loạt, cũng có thể được thực hiện trong Python. Bạn sẽ học ở đây làm thế nào để làm điều đó với các mô -đun OS và quy trình con.
Sử dụng mô -đun import os
stream = os.popen['echo Returned output']
output = stream.read[]
output
1
import os
stream = os.popen['echo Returned output']
output = stream.read[]
output
Cách tiếp cận đầu tiên và thẳng nhất để chạy lệnh shell là bằng cách sử dụng os.system []:
import os
os.system['ls -l']
Nếu bạn lưu điều này dưới dạng tập lệnh và chạy nó, bạn sẽ thấy đầu ra trong dòng lệnh. Vấn đề với phương pháp này là không thể linh hoạt vì bạn thậm chí có thể nhận được đầu ra kết quả là một biến. Bạn có thể đọc thêm về chức năng này trong tài liệu.
Lưu ý rằng, nếu bạn chạy chức năng này trong Notebook Jupyter, bạn đã giành được một đầu ra. Thay vào đó, bạn, đầu ra nội tuyến sẽ là mã trả lại của chương trình thực hiện [
import os
stream = os.popen['echo Returned output']
output = stream.read[]
output
2 để thành công và import os
stream = os.popen['echo Returned output']
output = stream.read[]
output
3 cho không thành công]. Bạn sẽ tìm thấy đầu ra trong dòng lệnh nơi bạn đã bắt đầu Jupyter Notebook.Tiếp theo, lệnh os.popen [] mở một đường ống từ hoặc đến dòng lệnh. Điều này có nghĩa là chúng ta có thể truy cập luồng trong Python. Điều này rất hữu ích vì bây giờ bạn có thể nhận được đầu ra như một biến:
import os
stream = os.popen['echo Returned output']
output = stream.read[]
output
Khi bạn sử dụng hàm
import os
stream = os.popen['echo Returned output']
output = stream.read[]
output
4, bạn sẽ nhận được toàn bộ đầu ra dưới dạng một chuỗi. Bạn cũng có thể sử dụng hàm import os
stream = os.popen['echo Returned output']
output = stream.read[]
output
5, phân tách từng dòng [bao gồm cả dấu vết import os
stream = os.popen['echo Returned output']
output = stream.read[]
output
6]. Lưu ý rằng bạn chỉ có thể chạy chúng một lần. Cũng có thể ghi vào luồng bằng cách sử dụng đối số import os
stream = os.popen['echo Returned output']
output = stream.read[]
output
7. Để đi sâu hơn vào chức năng này, hãy xem tài liệu.Trong ví dụ này và trong các ví dụ sau, bạn sẽ thấy rằng bạn luôn có các đường mòn theo dõi trong đầu ra. Để loại bỏ chúng [bao gồm các khoảng trống và tab trống ở đầu và kết thúc], bạn có thể sử dụng chức năng
import os
stream = os.popen['echo Returned output']
output = stream.read[]
output
8 như với import os
stream = os.popen['echo Returned output']
output = stream.read[]
output
9. Để loại bỏ các ký tự đó chỉ khi sử dụng import subprocess
process = subprocess.Popen[['echo', 'More output'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE]
stdout, stderr = process.communicate[]
stdout, stderr
0 và cho cuối import subprocess
process = subprocess.Popen[['echo', 'More output'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE]
stdout, stderr = process.communicate[]
stdout, stderr
1. Sử dụng mô -đun import subprocess
process = subprocess.Popen[['echo', 'More output'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE]
stdout, stderr = process.communicate[]
stdout, stderr
2
import subprocess
process = subprocess.Popen[['echo', 'More output'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE]
stdout, stderr = process.communicate[]
stdout, stderr
Cách tiếp cận cuối cùng cũng là cách tiếp cận linh hoạt nhất và mô -đun được đề xuất để chạy các lệnh bên ngoài trong Python:
Mô -đun phụ cung cấp các cơ sở mạnh mẽ hơn để sinh ra các quy trình mới và truy xuất kết quả của chúng; Sử dụng mô -đun đó là thích hợp hơn để sử dụng chức năng này. Xem các chức năng thay thế cũ hơn với phần mô -đun phụ trong tài liệu phụ cho một số công thức nấu ăn hữu ích. [Nguồn]
Chức năng chính bạn muốn ghi nhớ nếu bạn sử dụng Python> = 3.5 là quy trình phụ. Lớp Subprocess.popen [] chịu trách nhiệm tạo và quản lý quy trình thực hiện. Trái ngược với các chức năng trước đó, lớp này chỉ thực thi một lệnh duy nhất với các đối số như một danh sách. Điều này có nghĩa là bạn đã thắng được các lệnh:
import subprocess
process = subprocess.Popen[['echo', 'More output'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE]
stdout, stderr = process.communicate[]
stdout, stderr
Bạn có thể nhận thấy rằng chúng tôi đặt
import subprocess
process = subprocess.Popen[['echo', 'More output'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE]
stdout, stderr = process.communicate[]
stdout, stderr
4 và import subprocess
process = subprocess.Popen[['echo', 'More output'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE]
stdout, stderr = process.communicate[]
stdout, stderr
5 thành quy trình con.pipe. Đây là một giá trị đặc biệt chỉ ra import subprocess
process = subprocess.Popen[['echo', 'More output'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE]
stdout, stderr = process.communicate[]
stdout, stderr
6 rằng một đường ống nên được mở mà sau đó bạn có thể đọc với hàm import subprocess
process = subprocess.Popen[['echo', 'More output'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE]
stdout, stderr = process.communicate[]
stdout, stderr
7. Cũng có thể sử dụng một đối tượng tệp như với:with open['test.txt', 'w'] as f:
process = subprocess.Popen[['ls', '-l'], stdout=f]
Một điều khác mà bạn sẽ nhận thấy là đầu ra thuộc loại byte. Bạn có thể giải quyết điều đó bằng cách nhập
import subprocess
process = subprocess.Popen[['echo', 'More output'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE]
stdout, stderr = process.communicate[]
stdout, stderr
8 hoặc bằng cách thêm import subprocess
process = subprocess.Popen[['echo', 'More output'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE]
stdout, stderr = process.communicate[]
stdout, stderr
9 khi gọi import subprocess
process = subprocess.Popen[['echo', 'More output'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE]
stdout, stderr = process.communicate[]
stdout, stderr
6.Khi bạn chạy
import subprocess
process = subprocess.Popen[['echo', 'More output'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE]
stdout, stderr = process.communicate[]
stdout, stderr
7, nó sẽ đợi cho đến khi quá trình hoàn tất. Tuy nhiên, nếu bạn có một chương trình dài mà bạn muốn chạy và bạn muốn liên tục kiểm tra trạng thái trong thời gian thực trong khi làm việc khác, bạn có thể làm điều này như ở đây:process = subprocess.Popen[['ping', '-c 4', 'python.org'],
stdout=subprocess.PIPE,
universal_newlines=True]
while True:
output = process.stdout.readline[]
print[output.strip[]]
# Do something else
return_code = process.poll[]
if return_code is not None:
print['RETURN CODE', return_code]
# Process has finished, read rest of the output
for output in process.stdout.readlines[]:
print[output.strip[]]
break
PING python.org [45.55.99.72] 56[84] bytes of data.
64 bytes from 45.55.99.72 [45.55.99.72]: icmp_seq=1 ttl=51 time=117 ms
64 bytes from 45.55.99.72 [45.55.99.72]: icmp_seq=2 ttl=51 time=118 ms
64 bytes from 45.55.99.72 [45.55.99.72]: icmp_seq=3 ttl=51 time=117 ms
64 bytes from 45.55.99.72 [45.55.99.72]: icmp_seq=4 ttl=51 time=118 ms
--- python.org ping statistics ---
RETURN CODE 0
4 packets transmitted, 4 received, 0% packet loss, time 3001ms
rtt min/avg/max/mdev = 117.215/117.874/118.358/0.461 ms
Bạn có thể sử dụng chức năng
with open['test.txt', 'w'] as f:
process = subprocess.Popen[['ls', '-l'], stdout=f]
2 để kiểm tra mã trả lại của quy trình. Nó sẽ trả lại with open['test.txt', 'w'] as f:
process = subprocess.Popen[['ls', '-l'], stdout=f]
3 trong khi quá trình vẫn đang chạy. Để có được đầu ra, bạn có thể sử dụng with open['test.txt', 'w'] as f:
process = subprocess.Popen[['ls', '-l'], stdout=f]
4 để đọc một dòng. Ngược lại, khi bạn sử dụng with open['test.txt', 'w'] as f:
process = subprocess.Popen[['ls', '-l'], stdout=f]
5, nó sẽ đọc tất cả các dòng và nó cũng chờ quá trình hoàn thành nếu nó chưa kết thúc. Để biết thêm thông tin về chức năng của import subprocess
process = subprocess.Popen[['echo', 'More output'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE]
stdout, stderr = process.communicate[]
stdout, stderr
6, hãy xem tài liệu.Cũng lưu ý rằng bạn đã giành được các trích dẫn cần cho các đối số với không gian ở giữa
with open['test.txt', 'w'] as f:
process = subprocess.Popen[['ls', '-l'], stdout=f]
7. Nếu bạn không chắc chắn làm thế nào để mã hóa các đối số từ lệnh, bạn có thể sử dụng hàm shlex.split []:import shlex
shlex.split["/bin/prog -i data.txt -o \"more data.txt\""]
['/bin/prog', '-i', 'data.txt', '-o', 'more data.txt']
Bạn cũng có hàm SubProcess.call [] theo ý của bạn hoạt động như lớp
with open['test.txt', 'w'] as f:
process = subprocess.Popen[['ls', '-l'], stdout=f]
8, nhưng nó chờ cho đến khi lệnh hoàn thành và cung cấp cho bạn mã trả lại như trong with open['test.txt', 'w'] as f:
process = subprocess.Popen[['ls', '-l'], stdout=f]
9. Tuy nhiên, cách được đề xuất là sử dụng quy trình con.run [] hoạt động kể từ Python 3.5. Nó đã được thêm vào như một sự đơn giản hóa của import subprocess
process = subprocess.Popen[['echo', 'More output'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE]
stdout, stderr = process.communicate[]
stdout, stderr
6. Chức năng sẽ trả về một đối tượng SubProcess.completedProcess:
process = subprocess.run[['echo', 'Even more output'],
stdout=subprocess.PIPE,
universal_newlines=True]
process
CompletedProcess[args=['echo', 'Even more output'], returncode=0, stdout='Even more output\n']
Bây giờ bạn có thể tìm thấy đầu ra kết quả trong biến này:
Tương tự như
process = subprocess.Popen[['ping', '-c 4', 'python.org'],
stdout=subprocess.PIPE,
universal_newlines=True]
while True:
output = process.stdout.readline[]
print[output.strip[]]
# Do something else
return_code = process.poll[]
if return_code is not None:
print['RETURN CODE', return_code]
# Process has finished, read rest of the output
for output in process.stdout.readlines[]:
print[output.strip[]]
break
1 và hàm import subprocess
process = subprocess.Popen[['echo', 'More output'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE]
stdout, stderr = process.communicate[]
stdout, stderr
7 trước đó, nó sẽ chờ đợi quá trình được hoàn thành. Cuối cùng, đây là một ví dụ nâng cao hơn về cách truy cập máy chủ với mô -đun SSH và ____22:import os
stream = os.popen['echo Returned output']
output = stream.read[]
output
0Ở đây bạn có thể thấy cách viết đầu vào cho quy trình. Trong trường hợp này, bạn cần đặt
process = subprocess.Popen[['ping', '-c 4', 'python.org'],
stdout=subprocess.PIPE,
universal_newlines=True]
while True:
output = process.stdout.readline[]
print[output.strip[]]
# Do something else
return_code = process.poll[]
if return_code is not None:
print['RETURN CODE', return_code]
# Process has finished, read rest of the output
for output in process.stdout.readlines[]:
print[output.strip[]]
break
4 để có đầu ra không bị truy cập. Sau khi bạn viết xong cho process = subprocess.Popen[['ping', '-c 4', 'python.org'],
stdout=subprocess.PIPE,
universal_newlines=True]
while True:
output = process.stdout.readline[]
print[output.strip[]]
# Do something else
return_code = process.poll[]
if return_code is not None:
print['RETURN CODE', return_code]
# Process has finished, read rest of the output
for output in process.stdout.readlines[]:
print[output.strip[]]
break
5, bạn cần đóng kết nối.Sự kết luận
Bây giờ bạn đã thấy làm thế nào để chạy các lệnh bên ngoài trong Python. Cách hiệu quả nhất là sử dụng mô -đun
import subprocess
process = subprocess.Popen[['echo', 'More output'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE]
stdout, stderr = process.communicate[]
stdout, stderr
2 với tất cả các chức năng mà nó cung cấp. Đáng chú ý nhất, bạn nên xem xét sử dụng process = subprocess.Popen[['ping', '-c 4', 'python.org'],
stdout=subprocess.PIPE,
universal_newlines=True]
while True:
output = process.stdout.readline[]
print[output.strip[]]
# Do something else
return_code = process.poll[]
if return_code is not None:
print['RETURN CODE', return_code]
# Process has finished, read rest of the output
for output in process.stdout.readlines[]:
print[output.strip[]]
break
7. Đối với một tập lệnh ngắn và nhanh, bạn có thể chỉ muốn sử dụng các hàm process = subprocess.Popen[['ping', '-c 4', 'python.org'],
stdout=subprocess.PIPE,
universal_newlines=True]
while True:
output = process.stdout.readline[]
print[output.strip[]]
# Do something else
return_code = process.poll[]
if return_code is not None:
print['RETURN CODE', return_code]
# Process has finished, read rest of the output
for output in process.stdout.readlines[]:
print[output.strip[]]
break
8 hoặc process = subprocess.Popen[['ping', '-c 4', 'python.org'],
stdout=subprocess.PIPE,
universal_newlines=True]
while True:
output = process.stdout.readline[]
print[output.strip[]]
# Do something else
return_code = process.poll[]
if return_code is not None:
print['RETURN CODE', return_code]
# Process has finished, read rest of the output
for output in process.stdout.readlines[]:
print[output.strip[]]
break
9. Nếu bạn có bất kỳ câu hỏi nào, hãy thoải mái để chúng trong các ý kiến dưới đây. Ngoài ra còn có các thư viện hữu ích khác hỗ trợ các lệnh shell trong Python, như Plumbum, SH, psutils và pexpect.Tài nguyên
- 4 Kỹ thuật để kiểm tra ứng dụng dòng lệnh Python [CLI]
- Đối số thường được sử dụng - quy trình phụ