Hướng dẫn run shell script from python with arguments - chạy tập lệnh shell từ python với các đối số

Vấn đề là với

output = subprocess.check_output(['./childdir/execute.sh',str(var1),str(var2)])
print(output)
8. Hoặc xóa đối số đó hoặc chuyển tất cả các đối số dưới dạng chuỗi, như sau:

Process=Popen('./childdir/execute.sh %s %s' % (str(var1),str(var2),), shell=True)

Vỏ sẽ chỉ chuyển các đối số mà bạn cung cấp trong đối số đầu tiên của

output = subprocess.check_output(['./childdir/execute.sh',str(var1),str(var2)])
print(output)
9 cho quá trình này, vì nó thực hiện cách giải thích của chính các đối số. Xem một câu hỏi tương tự được trả lời ở đây. Điều thực sự xảy ra là tập lệnh shell của bạn không có đối số, vì vậy $ 1 và $ 2 trống.

Popen sẽ kế thừa stdout và stderr từ tập lệnh Python, vì vậy thường không cần phải cung cấp các đối số

import os

os.system("echo Hello from the other side!")
0 và
import os

os.system("echo Hello from the other side!")
1 cho popen (trừ khi bạn chạy tập lệnh với chuyển hướng đầu ra, chẳng hạn như
import os

os.system("echo Hello from the other side!")
2). Bạn chỉ nên làm điều này nếu bạn cần đọc đầu ra bên trong tập lệnh Python và thao tác bằng cách nào đó.

Nếu tất cả những gì bạn cần là có được đầu ra (và không ngại chạy đồng bộ), tôi khuyên bạn nên thử

import os

os.system("echo Hello from the other side!")
3, vì nó dễ dàng nhận được đầu ra hơn
output = subprocess.check_output(['./childdir/execute.sh',str(var1),str(var2)])
print(output)
9:

output = subprocess.check_output(['./childdir/execute.sh',str(var1),str(var2)])
print(output)

Lưu ý rằng

import os

os.system("echo Hello from the other side!")
3 và
import os

os.system("echo Hello from the other side!")
6 có các quy tắc tương tự cho đối số
import os

os.system("echo Hello from the other side!")
7 là
output = subprocess.check_output(['./childdir/execute.sh',str(var1),str(var2)])
print(output)
9.

Giới thiệu

Nhiệm vụ lặp đi lặp lại là chín muồi cho tự động hóa. Thông thường các nhà phát triển và quản trị viên hệ thống tự động hóa các tác vụ thường xuyên như kiểm tra sức khỏe và lưu trữ lại với các tập lệnh shell. Tuy nhiên, khi những nhiệm vụ đó trở nên phức tạp hơn, các kịch bản shell có thể trở nên khó duy trì hơn.

May mắn thay, chúng ta có thể sử dụng Python thay vì các tập lệnh shell để tự động hóa. Python cung cấp các phương thức để chạy các lệnh shell, cung cấp cho chúng ta chức năng tương tự của các tập lệnh shells đó. Học cách chạy các lệnh shell trong Python mở ra cánh cửa cho chúng tôi để tự động hóa các tác vụ máy tính theo cách có cấu trúc và có thể mở rộng.

Trong bài viết này, chúng tôi sẽ xem xét các cách khác nhau để thực thi các lệnh shell trong Python và tình huống lý tưởng để sử dụng từng phương thức.

Sử dụng OS.System để chạy lệnh

Python cho phép chúng tôi thực hiện ngay một lệnh shell được lưu trữ trong một chuỗi bằng hàm

import os

os.system("echo Hello from the other side!")
9.

Hãy bắt đầu bằng cách tạo một tệp Python mới có tên là

$ python3 echo_adelle.py
Hello from the other side!
0 và nhập như sau:

import os

os.system("echo Hello from the other side!")

Điều đầu tiên chúng tôi làm trong tệp Python của chúng tôi là nhập mô -đun

$ python3 echo_adelle.py
Hello from the other side!
1, chứa hàm
$ python3 echo_adelle.py
Hello from the other side!
2 có thể thực thi các lệnh shell. Dòng tiếp theo thực hiện chính xác điều đó, chạy lệnh
$ python3 echo_adelle.py
Hello from the other side!
3 trong vỏ của chúng tôi thông qua Python.

Trong thiết bị đầu cuối của bạn, hãy chạy tệp này bằng cách sử dụng lệnh sau và bạn sẽ thấy đầu ra tương ứng:

$ python3 echo_adelle.py
Hello from the other side!

Khi các lệnh

$ python3 echo_adelle.py
Hello from the other side!
3 in cho
$ python3 echo_adelle.py
Hello from the other side!
5 của chúng tôi,
import os

os.system("echo Hello from the other side!")
9 cũng hiển thị đầu ra trên luồng
$ python3 echo_adelle.py
Hello from the other side!
5 của chúng tôi. Mặc dù không hiển thị trong bảng điều khiển, lệnh
import os

os.system("echo Hello from the other side!")
9 trả về mã thoát của lệnh shell. Mã thoát 0 có nghĩa là nó đã chạy mà không có bất kỳ vấn đề nào và bất kỳ số nào khác có nghĩa là lỗi.

Chúng ta hãy tạo một tệp mới có tên

$ python3 echo_adelle.py
Hello from the other side!
9 và nhập như sau:

import os

home_dir = os.system("cd ~")
print("`cd ~` ran with exit code %d" % home_dir)
unknown_dir = os.system("cd doesnotexist")
print("`cd doesnotexis` ran with exit code %d" % unknown_dir)

Trong tập lệnh này, chúng tôi tạo hai biến lưu trữ kết quả thực thi các lệnh thay đổi thư mục thành thư mục gia đình và vào một thư mục không tồn tại. Chạy tệp này, chúng ta sẽ thấy:

$ python3 cd_return_codes.py
`cd ~` ran with exit code 0
sh: line 0: cd: doesnotexist: No such file or directory
`cd doesnotexist` ran with exit code 256

Lệnh đầu tiên, thay đổi thư mục thành thư mục nhà, thực thi thành công. Do đó,

import os

os.system("echo Hello from the other side!")
9 trả về mã thoát của nó, bằng không, được lưu trữ trong
import os

home_dir = os.system("cd ~")
print("`cd ~` ran with exit code %d" % home_dir)
unknown_dir = os.system("cd doesnotexist")
print("`cd doesnotexis` ran with exit code %d" % unknown_dir)
1. Mặt khác,
import os

home_dir = os.system("cd ~")
print("`cd ~` ran with exit code %d" % home_dir)
unknown_dir = os.system("cd doesnotexist")
print("`cd doesnotexis` ran with exit code %d" % unknown_dir)
2 lưu trữ mã thoát của lệnh bash thất bại để thay đổi thư mục thành một thư mục không tồn tại.

Hàm

import os

os.system("echo Hello from the other side!")
9 thực thi lệnh, in bất kỳ đầu ra nào của lệnh vào bảng điều khiển và trả về mã thoát của lệnh. Nếu chúng ta muốn kiểm soát hạt mịn hơn của đầu vào và đầu ra của lệnh shell trong Python, chúng ta nên sử dụng mô -đun
import os

home_dir = os.system("cd ~")
print("`cd ~` ran with exit code %d" % home_dir)
unknown_dir = os.system("cd doesnotexist")
print("`cd doesnotexis` ran with exit code %d" % unknown_dir)
4.

Chạy một lệnh với quy trình con

Mô -đun phụ là cách khuyến nghị của Python để thực thi các lệnh shell. Nó cho chúng ta sự linh hoạt để triệt tiêu đầu ra của các lệnh shell hoặc đầu vào chuỗi và đầu ra của các lệnh khác nhau lại với nhau, trong khi vẫn cung cấp trải nghiệm tương tự với

import os

os.system("echo Hello from the other side!")
9 cho các trường hợp sử dụng cơ bản.

Trong một tệp mới được gọi là

import os

home_dir = os.system("cd ~")
print("`cd ~` ran with exit code %d" % home_dir)
unknown_dir = os.system("cd doesnotexist")
print("`cd doesnotexis` ran with exit code %d" % unknown_dir)
6, hãy viết mã sau:

import subprocess

list_files = subprocess.run(["ls", "-l"])
print("The exit code was: %d" % list_files.returncode)

Trong dòng đầu tiên, chúng tôi nhập mô -đun

import os

home_dir = os.system("cd ~")
print("`cd ~` ran with exit code %d" % home_dir)
unknown_dir = os.system("cd doesnotexist")
print("`cd doesnotexis` ran with exit code %d" % unknown_dir)
4, là một phần của thư viện tiêu chuẩn Python. Sau đó, chúng tôi sử dụng hàm
import os

home_dir = os.system("cd ~")
print("`cd ~` ran with exit code %d" % home_dir)
unknown_dir = os.system("cd doesnotexist")
print("`cd doesnotexis` ran with exit code %d" % unknown_dir)
8 để thực thi lệnh. Giống như
import os

os.system("echo Hello from the other side!")
9, lệnh
import os

home_dir = os.system("cd ~")
print("`cd ~` ran with exit code %d" % home_dir)
unknown_dir = os.system("cd doesnotexist")
print("`cd doesnotexis` ran with exit code %d" % unknown_dir)
8 trả về mã thoát của những gì được thực thi.

Không giống như

import os

os.system("echo Hello from the other side!")
9, lưu ý cách
import os

home_dir = os.system("cd ~")
print("`cd ~` ran with exit code %d" % home_dir)
unknown_dir = os.system("cd doesnotexist")
print("`cd doesnotexis` ran with exit code %d" % unknown_dir)
8 yêu cầu một danh sách các chuỗi làm đầu vào thay vì một chuỗi. Mục đầu tiên của danh sách là tên của lệnh. Các mục còn lại của danh sách là các cờ và các đối số của lệnh.

Lưu ý: Theo nguyên tắc thông thường, bạn cần tách các đối số dựa trên không gian, ví dụ

$ python3 cd_return_codes.py
`cd ~` ran with exit code 0
sh: line 0: cd: doesnotexist: No such file or directory
`cd doesnotexist` ran with exit code 256
3 sẽ là
$ python3 cd_return_codes.py
`cd ~` ran with exit code 0
sh: line 0: cd: doesnotexist: No such file or directory
`cd doesnotexist` ran with exit code 256
4, trong khi
$ python3 cd_return_codes.py
`cd ~` ran with exit code 0
sh: line 0: cd: doesnotexist: No such file or directory
`cd doesnotexist` ran with exit code 256
5, sẽ là
$ python3 cd_return_codes.py
`cd ~` ran with exit code 0
sh: line 0: cd: doesnotexist: No such file or directory
`cd doesnotexist` ran with exit code 256
6. Một ví dụ khác,
$ python3 cd_return_codes.py
`cd ~` ran with exit code 0
sh: line 0: cd: doesnotexist: No such file or directory
`cd doesnotexist` ran with exit code 256
7 sẽ là
$ python3 cd_return_codes.py
`cd ~` ran with exit code 0
sh: line 0: cd: doesnotexist: No such file or directory
`cd doesnotexist` ran with exit code 256
8, trong khi
$ python3 cd_return_codes.py
`cd ~` ran with exit code 0
sh: line 0: cd: doesnotexist: No such file or directory
`cd doesnotexist` ran with exit code 256
9 hoặc
import subprocess

list_files = subprocess.run(["ls", "-l"])
print("The exit code was: %d" % list_files.returncode)
0 sẽ là
import subprocess

list_files = subprocess.run(["ls", "-l"])
print("The exit code was: %d" % list_files.returncode)
1.
As a rule of thumb, you need to separate the arguments based on space, for example
$ python3 cd_return_codes.py
`cd ~` ran with exit code 0
sh: line 0: cd: doesnotexist: No such file or directory
`cd doesnotexist` ran with exit code 256
3 would be
$ python3 cd_return_codes.py
`cd ~` ran with exit code 0
sh: line 0: cd: doesnotexist: No such file or directory
`cd doesnotexist` ran with exit code 256
4, while
$ python3 cd_return_codes.py
`cd ~` ran with exit code 0
sh: line 0: cd: doesnotexist: No such file or directory
`cd doesnotexist` ran with exit code 256
5, would be
$ python3 cd_return_codes.py
`cd ~` ran with exit code 0
sh: line 0: cd: doesnotexist: No such file or directory
`cd doesnotexist` ran with exit code 256
6. As another example,
$ python3 cd_return_codes.py
`cd ~` ran with exit code 0
sh: line 0: cd: doesnotexist: No such file or directory
`cd doesnotexist` ran with exit code 256
7 would be
$ python3 cd_return_codes.py
`cd ~` ran with exit code 0
sh: line 0: cd: doesnotexist: No such file or directory
`cd doesnotexist` ran with exit code 256
8, whereas
$ python3 cd_return_codes.py
`cd ~` ran with exit code 0
sh: line 0: cd: doesnotexist: No such file or directory
`cd doesnotexist` ran with exit code 256
9 or
import subprocess

list_files = subprocess.run(["ls", "-l"])
print("The exit code was: %d" % list_files.returncode)
0 would be
import subprocess

list_files = subprocess.run(["ls", "-l"])
print("The exit code was: %d" % list_files.returncode)
1.

Chạy tệp này và đầu ra của bảng điều khiển của bạn sẽ tương tự như:

$ python3 list_subprocess.py
total 80
[email protected] 1 stackabuse  staff    216 Dec  6 10:29 cd_return_codes.py
[email protected] 1 stackabuse  staff     56 Dec  6 10:11 echo_adelle.py
[email protected] 1 stackabuse  staff    116 Dec  6 11:20 list_subprocess.py
The exit code was: 0

Bây giờ chúng ta hãy cố gắng sử dụng một trong các tính năng nâng cao hơn của

import os

home_dir = os.system("cd ~")
print("`cd ~` ran with exit code %d" % home_dir)
unknown_dir = os.system("cd doesnotexist")
print("`cd doesnotexis` ran with exit code %d" % unknown_dir)
8, cụ thể là bỏ qua đầu ra thành
$ python3 echo_adelle.py
Hello from the other side!
5. Trong cùng một tệp
import os

home_dir = os.system("cd ~")
print("`cd ~` ran with exit code %d" % home_dir)
unknown_dir = os.system("cd doesnotexist")
print("`cd doesnotexis` ran with exit code %d" % unknown_dir)
6, thay đổi:

list_files = subprocess.run(["ls", "-l"])

Với điều này:

list_files = subprocess.run(["ls", "-l"], stdout=subprocess.DEVNULL)

Kiểm tra hướng dẫn thực hành của chúng tôi, thực tế để học Git, với các thực hành tốt nhất, các tiêu chuẩn được công nghiệp chấp nhận và bao gồm bảng gian lận. Ngừng các lệnh git googling và thực sự tìm hiểu nó!

Đầu ra tiêu chuẩn của lệnh bây giờ có đường dẫn đến thiết bị

import subprocess

list_files = subprocess.run(["ls", "-l"])
print("The exit code was: %d" % list_files.returncode)
5 đặc biệt, có nghĩa là đầu ra sẽ không xuất hiện trên bảng điều khiển của chúng tôi. Thực hiện tệp trong vỏ của bạn để xem đầu ra sau:

output = subprocess.check_output(['./childdir/execute.sh',str(var1),str(var2)])
print(output)
0

Điều gì sẽ xảy ra nếu chúng ta muốn cung cấp đầu vào cho một lệnh?

import os

home_dir = os.system("cd ~")
print("`cd ~` ran with exit code %d" % home_dir)
unknown_dir = os.system("cd doesnotexist")
print("`cd doesnotexis` ran with exit code %d" % unknown_dir)
8 tạo điều kiện cho điều này bằng đối số
import subprocess

list_files = subprocess.run(["ls", "-l"])
print("The exit code was: %d" % list_files.returncode)
7 của nó. Tạo một tệp mới có tên
import subprocess

list_files = subprocess.run(["ls", "-l"])
print("The exit code was: %d" % list_files.returncode)
8, gõ các mục sau:

output = subprocess.check_output(['./childdir/execute.sh',str(var1),str(var2)])
print(output)
1

Chúng tôi sử dụng

import os

home_dir = os.system("cd ~")
print("`cd ~` ran with exit code %d" % home_dir)
unknown_dir = os.system("cd doesnotexist")
print("`cd doesnotexis` ran with exit code %d" % unknown_dir)
8 với khá nhiều lệnh, hãy đi qua chúng:

  • $ python3 list_subprocess.py
    total 80
    [email protected] 1 stackabuse  staff    216 Dec  6 10:29 cd_return_codes.py
    [email protected] 1 stackabuse  staff     56 Dec  6 10:11 echo_adelle.py
    [email protected] 1 stackabuse  staff    116 Dec  6 11:20 list_subprocess.py
    The exit code was: 0
    
    0 bảo Python chuyển hướng đầu ra của lệnh sang một đối tượng để nó có thể được đọc thủ công sau
  • $ python3 list_subprocess.py
    total 80
    [email protected] 1 stackabuse  staff    216 Dec  6 10:29 cd_return_codes.py
    [email protected] 1 stackabuse  staff     56 Dec  6 10:11 echo_adelle.py
    [email protected] 1 stackabuse  staff    116 Dec  6 11:20 list_subprocess.py
    The exit code was: 0
    
    1 Trả về
    $ python3 echo_adelle.py
    Hello from the other side!
    
    5 và
    $ python3 list_subprocess.py
    total 80
    [email protected] 1 stackabuse  staff    216 Dec  6 10:29 cd_return_codes.py
    [email protected] 1 stackabuse  staff     56 Dec  6 10:11 echo_adelle.py
    [email protected] 1 stackabuse  staff    116 Dec  6 11:20 list_subprocess.py
    The exit code was: 0
    
    3 dưới dạng chuỗi. Loại trả về mặc định là byte.
  • $ python3 list_subprocess.py
    total 80
    [email protected] 1 stackabuse  staff    216 Dec  6 10:29 cd_return_codes.py
    [email protected] 1 stackabuse  staff     56 Dec  6 10:11 echo_adelle.py
    [email protected] 1 stackabuse  staff    116 Dec  6 11:20 list_subprocess.py
    The exit code was: 0
    
    4 bảo Python thêm chuỗi làm đầu vào vào lệnh
    $ python3 list_subprocess.py
    total 80
    [email protected] 1 stackabuse  staff    216 Dec  6 10:29 cd_return_codes.py
    [email protected] 1 stackabuse  staff     56 Dec  6 10:11 echo_adelle.py
    [email protected] 1 stackabuse  staff    116 Dec  6 11:20 list_subprocess.py
    The exit code was: 0
    
    5.

Chạy tệp này tạo ra đầu ra sau:

output = subprocess.check_output(['./childdir/execute.sh',str(var1),str(var2)])
print(output)
2

Chúng tôi cũng có thể tăng

$ python3 list_subprocess.py
total 80
[email protected] 1 stackabuse  staff    216 Dec  6 10:29 cd_return_codes.py
[email protected] 1 stackabuse  staff     56 Dec  6 10:11 echo_adelle.py
[email protected] 1 stackabuse  staff    116 Dec  6 11:20 list_subprocess.py
The exit code was: 0
6 mà không cần kiểm tra thủ công giá trị trả lại. Trong một tệp mới,
$ python3 list_subprocess.py
total 80
[email protected] 1 stackabuse  staff    216 Dec  6 10:29 cd_return_codes.py
[email protected] 1 stackabuse  staff     56 Dec  6 10:11 echo_adelle.py
[email protected] 1 stackabuse  staff    116 Dec  6 11:20 list_subprocess.py
The exit code was: 0
7, thêm mã bên dưới:

output = subprocess.check_output(['./childdir/execute.sh',str(var1),str(var2)])
print(output)
3

Trong thiết bị đầu cuối của bạn, chạy tập tin này. Bạn sẽ thấy lỗi sau:

output = subprocess.check_output(['./childdir/execute.sh',str(var1),str(var2)])
print(output)
4

Bằng cách sử dụng

$ python3 list_subprocess.py
total 80
[email protected] 1 stackabuse  staff    216 Dec  6 10:29 cd_return_codes.py
[email protected] 1 stackabuse  staff     56 Dec  6 10:11 echo_adelle.py
[email protected] 1 stackabuse  staff    116 Dec  6 11:20 list_subprocess.py
The exit code was: 0
8, chúng tôi bảo Python nêu ra bất kỳ ngoại lệ nào nếu gặp lỗi. Vì chúng tôi đã gặp phải lỗi, câu lệnh
$ python3 list_subprocess.py
total 80
[email protected] 1 stackabuse  staff    216 Dec  6 10:29 cd_return_codes.py
[email protected] 1 stackabuse  staff     56 Dec  6 10:11 echo_adelle.py
[email protected] 1 stackabuse  staff    116 Dec  6 11:20 list_subprocess.py
The exit code was: 0
9 trên dòng cuối cùng không được thực thi.

Hàm

import os

home_dir = os.system("cd ~")
print("`cd ~` ran with exit code %d" % home_dir)
unknown_dir = os.system("cd doesnotexist")
print("`cd doesnotexis` ran with exit code %d" % unknown_dir)
8 mang đến cho chúng ta sự linh hoạt to lớn mà
import os

os.system("echo Hello from the other side!")
9 không khi thực hiện các lệnh shell. Hàm này là một sự trừu tượng hóa đơn giản hóa của lớp
list_files = subprocess.run(["ls", "-l"])
2, cung cấp chức năng bổ sung mà chúng ta có thể khám phá.

Chạy một lệnh với popen

Lớp

list_files = subprocess.run(["ls", "-l"])
2 hiển thị nhiều tùy chọn hơn cho nhà phát triển khi tương tác với vỏ. Tuy nhiên, chúng ta cần rõ ràng hơn về việc truy xuất kết quả và lỗi.

Theo mặc định,

list_files = subprocess.run(["ls", "-l"])
2 không ngừng xử lý chương trình Python nếu lệnh của nó chưa hoàn thành thực thi. Trong một tệp mới có tên là
list_files = subprocess.run(["ls", "-l"])
5, nhập như sau:

output = subprocess.check_output(['./childdir/execute.sh',str(var1),str(var2)])
print(output)
5

Mã này tương đương với mã

import os

home_dir = os.system("cd ~")
print("`cd ~` ran with exit code %d" % home_dir)
unknown_dir = os.system("cd doesnotexist")
print("`cd doesnotexis` ran with exit code %d" % unknown_dir)
6. Nó chạy một lệnh bằng cách sử dụng
list_files = subprocess.run(["ls", "-l"])
2 và chờ nó hoàn thành trước khi thực hiện phần còn lại của tập lệnh Python.

Giả sử chúng tôi không muốn chờ lệnh Shell của chúng tôi hoàn thành việc thực thi để chương trình có thể làm việc với những thứ khác. Làm thế nào nó sẽ biết khi lệnh shell đã hoàn thành thực thi?

Phương thức

list_files = subprocess.run(["ls", "-l"])
8 trả về mã thoát nếu một lệnh đã chạy xong hoặc
list_files = subprocess.run(["ls", "-l"])
9 nếu nó vẫn đang thực thi. Ví dụ: nếu chúng tôi muốn kiểm tra xem
list_files = subprocess.run(["ls", "-l"], stdout=subprocess.DEVNULL)
0 đã hoàn tất thay vì chờ nó, chúng tôi sẽ có dòng mã sau:

output = subprocess.check_output(['./childdir/execute.sh',str(var1),str(var2)])
print(output)
6

Để quản lý đầu vào và đầu ra với

list_files = subprocess.run(["ls", "-l"])
2, chúng ta cần sử dụng phương thức
list_files = subprocess.run(["ls", "-l"], stdout=subprocess.DEVNULL)
2.

Trong một tệp mới có tên

list_files = subprocess.run(["ls", "-l"], stdout=subprocess.DEVNULL)
3, hãy thêm đoạn mã sau:

output = subprocess.check_output(['./childdir/execute.sh',str(var1),str(var2)])
print(output)
7

Phương thức

list_files = subprocess.run(["ls", "-l"], stdout=subprocess.DEVNULL)
2 có một đối số
import subprocess

list_files = subprocess.run(["ls", "-l"])
print("The exit code was: %d" % list_files.returncode)
7 được sử dụng để chuyển đầu vào cho lệnh shell. Phương pháp
list_files = subprocess.run(["ls", "-l"], stdout=subprocess.DEVNULL)
6 cũng trả về cả
$ python3 echo_adelle.py
Hello from the other side!
5 và
$ python3 list_subprocess.py
total 80
[email protected] 1 stackabuse  staff    216 Dec  6 10:29 cd_return_codes.py
[email protected] 1 stackabuse  staff     56 Dec  6 10:11 echo_adelle.py
[email protected] 1 stackabuse  staff    116 Dec  6 11:20 list_subprocess.py
The exit code was: 0
3 khi chúng được đặt.

Đã thấy những ý tưởng cốt lõi đằng sau

list_files = subprocess.run(["ls", "-l"])
2, giờ đây chúng tôi đã đề cập đến ba cách để chạy các lệnh shell trong Python. Hãy kiểm tra lại các đặc điểm của họ để chúng tôi biết phương pháp nào phù hợp nhất cho các yêu cầu của dự án.

Tôi nên sử dụng cái nào?

Nếu bạn cần chạy một hoặc một vài lệnh đơn giản và không bận tâm nếu đầu ra của chúng đi vào bảng điều khiển, bạn có thể sử dụng lệnh

import os

os.system("echo Hello from the other side!")
9. Nếu bạn muốn quản lý đầu vào và đầu ra của lệnh shell, hãy sử dụng
import os

home_dir = os.system("cd ~")
print("`cd ~` ran with exit code %d" % home_dir)
unknown_dir = os.system("cd doesnotexist")
print("`cd doesnotexis` ran with exit code %d" % unknown_dir)
8. Nếu bạn muốn chạy một lệnh và tiếp tục thực hiện công việc khác trong khi nó được thực thi, hãy sử dụng
list_files = subprocess.run(["ls", "-l"])
2.

Dưới đây là một bảng với một số khác biệt về khả năng sử dụng mà bạn cũng có thể sử dụng để thông báo cho quyết định của mình:

os.systemsubprocess.runsubprocess.Popen
Yêu cầu đối số phân tích cú phápkhôngVângVâng
Chờ lệnhVângVângkhông
VângkhôngVângVâng
Chờ lệnhGiao tiếp với Stdin và StdoutTrả lạiTrả lại

Giá trị trả về

sự vật

Sự kết luận

Làm cách nào để chạy kịch bản shell trong Python?

Nếu bạn cần thực hiện lệnh shell bằng python, có hai cách. Bạn có thể sử dụng mô -đun phụ hoặc hàm RunShellCommand (). Tùy chọn đầu tiên dễ dàng hơn để chạy một dòng mã và sau đó thoát, nhưng nó không linh hoạt khi sử dụng các đối số hoặc tạo ra đầu ra văn bản.use the subprocess module or the RunShellCommand() function. The first option is easier to run one line of code and then exit, but it isn't as flexible when using arguments or producing text output.

Shell Script có thể chấp nhận các đối số không?

Thông qua các lập luận.Khả năng chuyển các đối số cho tập lệnh mang lại các tính năng động cho các tập lệnh.Trong kịch bản shell, các đối số được cung cấp cho tập lệnh tại thời điểm thực thi/chạy lệnh.the arguments are provided to the script at the time of execution/running of the command.

Làm cách nào để chạy tập lệnh shell từ các đối số dòng lệnh?

Để chuyển một đối số cho tập lệnh bash của bạn, bạn chỉ cần viết nó theo tên của tập lệnh của bạn:..
./script.sh my_argument ..
#!/usr/bin/env bash.....
./script.sh.....
./fruit.sh quả táo cam.....
#!/usr/bin/env bash.....
./fruit.sh quả táo cam.....
© Wellcome Genome Campus Các khóa học nâng cao và hội nghị khoa học ..

Làm thế nào để bạn chạy một đối số trong tập lệnh Python?

Bạn có thể sử dụng các đối số dòng lệnh bằng cách sử dụng mảng sys.argv [].Chỉ mục đầu tiên của mảng bao gồm tên tệp tập lệnh Python.Và từ vị trí thứ hai, bạn sẽ có các đối số dòng lệnh được truyền trong khi chạy tập lệnh Python.by using the sys. argv[] array. The first index of the array consists of the python script file name. And from the second position, you'll have the command line arguments passed while running the python script.