Hướng dẫn python subprocess call synchronous - đồng bộ cuộc gọi quy trình con python

Tôi đang cố gắng sử dụng popen để khởi động một quy trình con gọi hai lệnh (với nhiều tranh luận) lần lượt từng lệnh. Lệnh thứ hai dựa vào lệnh đầu tiên đang chạy, vì vậy tôi đã hy vọng sử dụng một quy trình con duy nhất để chạy cả thay vì sinh sản hai quy trình và chờ vào thứ nhất.

Show

Nhưng tôi đang gặp phải các vấn đề vì tôi không chắc chắn làm thế nào để đưa ra hai đầu vào lệnh hoặc để tách lệnh như một đối tượng.

Ngoài ra, tôi đang cố gắng tránh đặt shell thành true nếu có thể.

Đây thực chất là những gì tôi đang cố gắng làm:

for test in resources:
    command = [
        'pgh',
        'resource',
        'create',
        '--name', test['name'],
        '--description', test['description'],
    ]
    command2 = [
        'pgh',
        'assignment',
        'create',
        '--name', test['name'],
        '--user', test['user'],
    ]


    p = Popen(command, stdout=PIPE, stderr=PIPE)
    stdout, stderr = p.communicate()
    print(stdout)
    print(stderr)

Mã nguồn: lib/sub -crocess.py Lib/subprocess.py


Mô -đun

Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
9 cho phép bạn sinh ra các quy trình mới, kết nối với đường ống đầu vào/đầu ra/lỗi của chúng và có được mã trả lại của chúng. Mô -đun này dự định thay thế một số mô -đun và chức năng cũ hơn:

Thông tin về cách mô -đun

Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
9 có thể được sử dụng để thay thế các mô -đun và chức năng này có thể được tìm thấy trong các phần sau.

Xem thêm

PEP 324 - PEP đề xuất mô -đun phụ – PEP proposing the subprocess module

Tính khả dụng: Không phải emscripten, không phải wasi.: not Emscripten, not WASI.

Mô -đun này không hoạt động hoặc không có sẵn trên các nền tảng Webassugging

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
1 và
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
2. Xem các nền tảng Webassugging để biết thêm thông tin.WebAssembly platforms for more information.

Sử dụng mô -đun Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."]) 9

Cách tiếp cận được đề xuất để gọi các quy trình con là sử dụng chức năng

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
4 cho tất cả các trường hợp sử dụng mà nó có thể xử lý. Đối với các trường hợp sử dụng nâng cao hơn, giao diện
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
5 cơ bản có thể được sử dụng trực tiếp.

SubProcess.run (args, *, stdin = none, input = none, stdout = none, stderr = none, capture_output = false, shell = false, cwd = none Không, Text = none, env = none, Universal_Newlines = none, ** other_popen_kwargs) ¶run(args, *, stdin=None, input=None, stdout=None, stderr=None, capture_output=False, shell=False, cwd=None, timeout=None, check=False, encoding=None, errors=None, text=None, env=None, universal_newlines=None, **other_popen_kwargs)

Chạy lệnh được mô tả bởi Args. Đợi lệnh hoàn thành, sau đó trả lại một thể hiện

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
6.

Các đối số được hiển thị ở trên chỉ là những đối số phổ biến nhất, được mô tả dưới đây trong các đối số được sử dụng thường xuyên (do đó việc sử dụng ký hiệu chỉ từ khóa trong chữ ký viết tắt). Chữ ký chức năng đầy đủ phần lớn giống như hàm xây dựng

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
5 - hầu hết các đối số cho hàm này được chuyển qua giao diện đó. (Thời gian chờ, đầu vào, kiểm tra và capture_output không.)Frequently Used Arguments (hence the use of keyword-only notation in the abbreviated signature). The full function signature is largely the same as that of the
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
5 constructor - most of the arguments to this function are passed through to that interface. (timeout, input, check, and capture_output are not.)

Nếu Capture_output là đúng, stdout và stderr sẽ bị bắt. Khi được sử dụng, đối tượng

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
5 nội bộ được tự động tạo bằng
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
9 và
Popen(['/bin/sh', '-c', args[0], args[1], ...])
0. Các đối số stdout và stderr có thể không được cung cấp cùng lúc với Capture_output. Nếu bạn muốn chụp và kết hợp cả hai luồng thành một, hãy sử dụng
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
9 và
Popen(['/bin/sh', '-c', args[0], args[1], ...])
2 thay vì Capture_output.

Đối số thời gian chờ được chuyển đến

Popen(['/bin/sh', '-c', args[0], args[1], ...])
3. Nếu thời gian chờ hết hạn, quá trình trẻ em sẽ bị giết và chờ đợi. Ngoại lệ
Popen(['/bin/sh', '-c', args[0], args[1], ...])
4 sẽ được nuôi dưỡng lại sau khi quá trình con đã chấm dứt.

Đối số đầu vào được chuyển đến

Popen(['/bin/sh', '-c', args[0], args[1], ...])
3 và do đó cho quá trình phụ stdin. Nếu được sử dụng, nó phải là một chuỗi byte hoặc một chuỗi nếu mã hóa hoặc lỗi được chỉ định hoặc văn bản là đúng. Khi được sử dụng, đối tượng
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
5 nội bộ được tự động tạo bằng
Popen(['/bin/sh', '-c', args[0], args[1], ...])
7 và đối số Stdin cũng không được sử dụng.

Nếu kiểm tra là đúng và quy trình thoát ra với mã thoát khác không, ngoại lệ

Popen(['/bin/sh', '-c', args[0], args[1], ...])
8 sẽ được nêu ra. Các thuộc tính của ngoại lệ đó giữ các đối số, mã thoát và stdout và stderr nếu chúng bị bắt.

Nếu mã hóa hoặc lỗi được chỉ định hoặc văn bản là đúng, các đối tượng tệp cho stdin, stdout và stderr được mở ở chế độ văn bản bằng cách sử dụng mã hóa và lỗi được chỉ định hoặc mặc định

Popen(['/bin/sh', '-c', args[0], args[1], ...])
9. Đối số Universal_Newlines tương đương với văn bản và được cung cấp cho khả năng tương thích ngược. Theo mặc định, các đối tượng tệp được mở ở chế độ nhị phân.

Nếu env không phải là

with Popen(["ifconfig"], stdout=PIPE) as proc:
    log.write(proc.stdout.read())
0, thì đó phải là một ánh xạ xác định các biến môi trường cho quy trình mới; Chúng được sử dụng thay vì hành vi mặc định của việc kế thừa môi trường quy trình hiện tại. Nó được truyền trực tiếp đến
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
5. Ánh xạ này có thể được STR trên bất kỳ nền tảng hoặc byte nào cho byte trên các nền tảng POSIX giống như
with Popen(["ifconfig"], stdout=PIPE) as proc:
    log.write(proc.stdout.read())
2 hoặc
with Popen(["ifconfig"], stdout=PIPE) as proc:
    log.write(proc.stdout.read())
3.

Examples:

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')

Mới trong phiên bản 3.5.

Đã thay đổi trong phiên bản 3.6: Đã thêm thông số mã hóa và lỗiAdded encoding and errors parameters

Đã thay đổi trong phiên bản 3.7: Đã thêm tham số văn bản, như một bí danh dễ hiểu hơn của Universal_Newlines. Đã thêm tham số Capture_output.Added the text parameter, as a more understandable alias of universal_newlines. Added the capture_output parameter.

ClassSubProcess.completedProcess¶subprocess.CompletedProcess

Giá trị trả về từ

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
4, đại diện cho một quá trình đã kết thúc.

args¶

Các đối số được sử dụng để khởi chạy quá trình. Đây có thể là một danh sách hoặc một chuỗi.

ReturnCode¶

Trạng thái thoát của quá trình trẻ em. Thông thường, trạng thái thoát là 0 chỉ ra rằng nó đã chạy thành công.

Giá trị âm

with Popen(["ifconfig"], stdout=PIPE) as proc:
    log.write(proc.stdout.read())
5 chỉ ra rằng đứa trẻ bị chấm dứt bởi tín hiệu
with Popen(["ifconfig"], stdout=PIPE) as proc:
    log.write(proc.stdout.read())
6 (chỉ POSIX).

Stdout¶

Đã bắt được stdout từ quá trình trẻ em. Trình tự byte hoặc chuỗi nếu

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
4 được gọi với mã hóa, lỗi hoặc văn bản = true.
with Popen(["ifconfig"], stdout=PIPE) as proc:
    log.write(proc.stdout.read())
0 nếu stdout không bị bắt.

Nếu bạn chạy quy trình với

with Popen(["ifconfig"], stdout=PIPE) as proc:
    log.write(proc.stdout.read())
9, stdout và stderr sẽ được kết hợp trong thuộc tính này và
proc = subprocess.Popen(...)
try:
    outs, errs = proc.communicate(timeout=15)
except TimeoutExpired:
    proc.kill()
    outs, errs = proc.communicate()
0 sẽ là
with Popen(["ifconfig"], stdout=PIPE) as proc:
    log.write(proc.stdout.read())
0.

stderr¶

Đã bắt Stderr từ quá trình trẻ em. Trình tự byte hoặc chuỗi nếu

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
4 được gọi với mã hóa, lỗi hoặc văn bản = true.
with Popen(["ifconfig"], stdout=PIPE) as proc:
    log.write(proc.stdout.read())
0 nếu Stderr không bị bắt.

Check_returnCode ()()

Nếu

proc = subprocess.Popen(...)
try:
    outs, errs = proc.communicate(timeout=15)
except TimeoutExpired:
    proc.kill()
    outs, errs = proc.communicate()
4 là không khác, hãy tăng
Popen(['/bin/sh', '-c', args[0], args[1], ...])
8.

Mới trong phiên bản 3.5.

quá trình con.devnull¶DEVNULL

Giá trị đặc biệt có thể được sử dụng làm đối số STDIN, STDOUT hoặc STDERR thành

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
5 và chỉ ra rằng tệp đặc biệt
proc = subprocess.Popen(...)
try:
    outs, errs = proc.communicate(timeout=15)
except TimeoutExpired:
    proc.kill()
    outs, errs = proc.communicate()
7 sẽ được sử dụng.

Mới trong phiên bản 3.3.

quá trình con.pipe¶PIPE

Giá trị đặc biệt có thể được sử dụng làm đối số stdin, stdout hoặc stderr thành

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
5 và chỉ ra rằng một đường ống vào luồng tiêu chuẩn nên được mở. Hữu ích nhất với
Popen(['/bin/sh', '-c', args[0], args[1], ...])
3.

quá trình con.stdout¶STDOUT

Giá trị đặc biệt có thể được sử dụng làm đối số STDERR thành

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
5 và chỉ ra rằng lỗi tiêu chuẩn sẽ đi vào cùng một tay cầm như đầu ra tiêu chuẩn.

ngoại lệ subprocess.SubprocessError

Lớp cơ sở cho tất cả các trường hợp ngoại lệ khác từ mô -đun này.

Mới trong phiên bản 3.3.

quá trình con.pipe¶ subprocess.TimeoutExpired

Giá trị đặc biệt có thể được sử dụng làm đối số stdin, stdout hoặc stderr thành

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
5 và chỉ ra rằng một đường ống vào luồng tiêu chuẩn nên được mở. Hữu ích nhất với
Popen(['/bin/sh', '-c', args[0], args[1], ...])
3.

quá trình con.stdout¶

Giá trị đặc biệt có thể được sử dụng làm đối số STDERR thành

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
5 và chỉ ra rằng lỗi tiêu chuẩn sẽ đi vào cùng một tay cầm như đầu ra tiêu chuẩn.

ngoại lệ

Lớp cơ sở cho tất cả các trường hợp ngoại lệ khác từ mô -đun này.

ngoại lệ

Lớp con của

si = subprocess.STARTUPINFO()
si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW
1, được tăng lên khi hết thời gian chờ trong khi chờ đợi một quá trình trẻ em.

cmd¶

Lệnh được sử dụng để sinh ra quá trình trẻ em.

hết giờ¶

Thời gian chờ trong giây.

Mới trong phiên bản 3.3.

quá trình con.pipe¶stdout and stderr attributes added

Giá trị đặc biệt có thể được sử dụng làm đối số stdin, stdout hoặc stderr thành
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
5 và chỉ ra rằng một đường ống vào luồng tiêu chuẩn nên được mở. Hữu ích nhất với
Popen(['/bin/sh', '-c', args[0], args[1], ...])
3.
subprocess.CalledProcessError

quá trình con.stdout¶

Giá trị đặc biệt có thể được sử dụng làm đối số STDERR thành
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
5 và chỉ ra rằng lỗi tiêu chuẩn sẽ đi vào cùng một tay cầm như đầu ra tiêu chuẩn.

ngoại lệ

quá trình con.stdout¶

Giá trị đặc biệt có thể được sử dụng làm đối số STDERR thành

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
5 và chỉ ra rằng lỗi tiêu chuẩn sẽ đi vào cùng một tay cầm như đầu ra tiêu chuẩn.

ngoại lệ

Lớp cơ sở cho tất cả các trường hợp ngoại lệ khác từ mô -đun này.

cmd¶

Lệnh được sử dụng để sinh ra quá trình trẻ em.

hết giờ¶

Thời gian chờ trong giây.

quá trình con.pipe¶stdout and stderr attributes added

Giá trị đặc biệt có thể được sử dụng làm đối số stdin, stdout hoặc stderr thành >>> import shlex, subprocess >>> command_line = input() /bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'" >>> args = shlex.split(command_line) >>> print(args) ['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"] >>> p = subprocess.Popen(args) # Success! 5 và chỉ ra rằng một đường ống vào luồng tiêu chuẩn nên được mở. Hữu ích nhất với Popen(['/bin/sh', '-c', args[0], args[1], ...]) 3.

quá trình con.stdout¶

Giá trị đặc biệt có thể được sử dụng làm đối số STDERR thành

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
5 và chỉ ra rằng lỗi tiêu chuẩn sẽ đi vào cùng một tay cầm như đầu ra tiêu chuẩn.

ngoại lệ

Lớp cơ sở cho tất cả các trường hợp ngoại lệ khác từ mô -đun này.

ngoại lệ

Lớp con của

si = subprocess.STARTUPINFO()
si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW
1, được tăng lên khi hết thời gian chờ trong khi chờ đợi một quá trình trẻ em.

cmd¶Added encoding and errors parameters.

Mới trong phiên bản 3.7: Đã thêm tham số văn bản dưới dạng bí danh cho Universal_Newlines.Added the text parameter as an alias for universal_newlines.

Nếu shell là

>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'
8, lệnh được chỉ định sẽ được thực thi thông qua shell. Điều này có thể hữu ích nếu bạn đang sử dụng Python chủ yếu cho luồng điều khiển nâng cao mà nó cung cấp trên hầu hết các vỏ hệ thống và vẫn muốn truy cập thuận tiện vào các tính năng vỏ khác như ống shell, ký tự đại diện, mở rộng biến đổi môi trường và mở rộng
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
14 cho nhà của người dùng danh mục. Tuy nhiên, lưu ý rằng bản thân Python cung cấp việc triển khai nhiều tính năng giống như vỏ (đặc biệt là
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
15,
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
16,
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
17,
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
18,
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
19 và
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
20).

Đã thay đổi trong phiên bản 3.3: Khi Universal_Newlines là

>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'
8, lớp sử dụng mã hóa
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
22 thay vì
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
23. Xem lớp
Popen(['/bin/sh', '-c', args[0], args[1], ...])
9 để biết thêm thông tin về thay đổi này.When universal_newlines is
>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'
8, the class uses the encoding
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
22 instead of
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
23. See the
Popen(['/bin/sh', '-c', args[0], args[1], ...])
9 class for more information on this change.

Các tùy chọn này, cùng với tất cả các tùy chọn khác, được mô tả chi tiết hơn trong tài liệu xây dựng

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
5.

Constructor Popen Constructor¶

Việc tạo và quản lý quy trình cơ bản trong mô -đun này được xử lý bởi lớp

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
5. Nó cung cấp rất nhiều sự linh hoạt để các nhà phát triển có thể xử lý các trường hợp ít phổ biến hơn không được bao phủ bởi các chức năng tiện lợi.

classSubProcess.popen (args, bufsize = -1, thực thi = none, stdin = none, stdout = none, stderr = none . = None, pipesize = -1, process_group = none) ¶subprocess.Popen(args, bufsize=- 1, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=None, startupinfo=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=(), *, group=None, extra_groups=None, user=None, umask=- 1, encoding=None, errors=None, text=None, pipesize=- 1, process_group=None)

Thực hiện một chương trình trẻ em trong một quy trình mới. Trên Posix, lớp sử dụng hành vi giống như ____ 127 để thực hiện chương trình trẻ em. Trên Windows, lớp sử dụng chức năng Windows

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
28. Các đối số cho
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
5 như sau.

Args nên là một chuỗi các đối số chương trình hoặc một đối tượng giống như một chuỗi hoặc giống như đường dẫn. Theo mặc định, chương trình thực thi là mục đầu tiên trong args nếu args là một chuỗi. Nếu Args là một chuỗi, việc giải thích phụ thuộc vào nền tảng và được mô tả dưới đây. Xem các đối số shell và thực thi để biết sự khác biệt bổ sung so với hành vi mặc định. Trừ khi có quy định khác, nên truyền ARGS như một chuỗi.path-like object. By default, the program to execute is the first item in args if args is a sequence. If args is a string, the interpretation is platform-dependent and described below. See the shell and executable arguments for additional differences from the default behavior. Unless otherwise stated, it is recommended to pass args as a sequence.

Cảnh báo

Để có độ tin cậy tối đa, hãy sử dụng một đường dẫn đủ điều kiện cho thực thi. Để tìm kiếm một tên không đủ tiêu chuẩn trên

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
30, hãy sử dụng
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
31. Trên tất cả các nền tảng, việc vượt qua
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
32 là cách được đề xuất để khởi chạy lại trình thông dịch Python hiện tại và sử dụng định dạng dòng lệnh
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
33 để khởi chạy mô-đun đã cài đặt.
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
30, use
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
31. On all platforms, passing
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
32 is the recommended way to launch the current Python interpreter again, and use the
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
33 command-line format to launch an installed module.

Việc giải quyết đường dẫn thực thi (hoặc mục đầu tiên của Args) phụ thuộc vào nền tảng. Đối với POSIX, xem

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
27 và lưu ý rằng khi giải quyết hoặc tìm kiếm đường dẫn thực thi, CWD ghi đè thư mục làm việc hiện tại và ENV có thể ghi đè biến môi trường
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
30. Đối với Windows, hãy xem tài liệu của các tham số
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
36 và
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
37 của WinAPI
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
38 và lưu ý rằng khi giải quyết hoặc tìm kiếm đường dẫn thực thi với
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
39, CWD không ghi đè lên thư mục làm việc hiện tại và Env không thể ghi đè biến đổi môi trường
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
30. Sử dụng một đường dẫn đầy đủ tránh tất cả các biến thể này.

Một ví dụ về việc chuyển một số đối số cho một chương trình bên ngoài như một chuỗi là:

Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])

Trên Posix, nếu Args là một chuỗi, chuỗi được hiểu là tên hoặc đường dẫn của chương trình để thực thi. Tuy nhiên, điều này chỉ có thể được thực hiện nếu không chuyển các đối số cho chương trình.

Ghi chú

Có thể không rõ ràng làm thế nào để chia một lệnh shell thành một chuỗi các đối số, đặc biệt là trong các trường hợp phức tạp.

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
41 có thể minh họa cách xác định mã thông báo chính xác cho ARGS:

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!

Lưu ý cụ thể rằng các tùy chọn (chẳng hạn như -input) và các đối số (như trứng.txt) được phân tách bằng khoảng trắng trong shell đi trong các yếu tố danh sách riêng biệt, trong khi các đối số cần trích dẫn hoặc rút lại khi sử dụng Tên tệp chứa khoảng trắng hoặc lệnh Echo được hiển thị ở trên) là các yếu tố danh sách đơn.

Trên Windows, nếu Args là một chuỗi, nó sẽ được chuyển đổi thành một chuỗi theo cách được mô tả trong việc chuyển đổi một chuỗi đối số thành một chuỗi trên Windows. Điều này là do

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
28 cơ bản hoạt động trên các chuỗi.Converting an argument sequence to a string on Windows. This is because the underlying
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
28 operates on strings.

Đã thay đổi trong phiên bản 3.6: Tham số Args chấp nhận một đối tượng giống như đường dẫn nếu shell là

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
43 và một chuỗi chứa các đối tượng giống như đường dẫn trên POSIX.args parameter accepts a path-like object if shell is
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
43 and a sequence containing path-like objects on POSIX.

Thay đổi trong phiên bản 3.8: Tham số Args chấp nhận một đối tượng giống như đường dẫn nếu shell là

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
43 và một chuỗi chứa byte và các đối tượng giống như đường dẫn trên Windows.args parameter accepts a path-like object if shell is
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
43 and a sequence containing bytes and path-like objects on Windows.

Đối số shell (mặc định là

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
43) chỉ định xem có nên sử dụng shell làm chương trình để thực thi hay không. Nếu shell là
>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'
8, nên chuyển Args dưới dạng chuỗi chứ không phải là một chuỗi.

Trên POSIX với

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
47, shell mặc định là
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
48. Nếu args là một chuỗi, chuỗi chỉ định lệnh để thực thi thông qua shell. Điều này có nghĩa là chuỗi phải được định dạng chính xác như khi được gõ tại dấu nhắc shell. Điều này bao gồm, ví dụ, trích dẫn hoặc chao đảo thoát khỏi các tên tệp với không gian trong đó. Nếu Args là một chuỗi, mục đầu tiên chỉ định chuỗi lệnh và bất kỳ mục bổ sung nào sẽ được coi là đối số bổ sung cho chính shell. Điều đó có nghĩa là,
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
5 có tương đương với:

Popen(['/bin/sh', '-c', args[0], args[1], ...])

Trên Windows với

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
47, biến môi trường
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
51 chỉ định shell mặc định. Lần duy nhất bạn cần chỉ định
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
47 trên Windows là khi lệnh bạn muốn thực thi được tích hợp vào shell (ví dụ: dir hoặc sao chép). Bạn không cần
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
47 để chạy tệp hàng loạt hoặc thực thi dựa trên bảng điều khiển.
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
51 environment variable specifies the default shell. The only time you need to specify
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
47 on Windows is when the command you wish to execute is built into the shell (e.g. dir or copy). You do not need
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
47 to run a batch file or console-based executable.

Bufsize sẽ được cung cấp dưới dạng đối số tương ứng cho hàm

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
54 khi tạo các đối tượng tệp ống stdin/stdout/stderr:

  • >>> subprocess.run(["ls", "-l"])  # doesn't capture output
    CompletedProcess(args=['ls', '-l'], returncode=0)
    
    >>> subprocess.run("exit 1", shell=True, check=True)
    Traceback (most recent call last):
      ...
    subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1
    
    >>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
    CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
    stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
    
    55 có nghĩa là không bị ảnh hưởng (đọc và viết là một cuộc gọi hệ thống và có thể quay lại ngắn)

  • >>> subprocess.run(["ls", "-l"])  # doesn't capture output
    CompletedProcess(args=['ls', '-l'], returncode=0)
    
    >>> subprocess.run("exit 1", shell=True, check=True)
    Traceback (most recent call last):
      ...
    subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1
    
    >>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
    CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
    stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
    
    56 có nghĩa là bộ đệm dòng (chỉ có thể sử dụng nếu
    >>> subprocess.run(["ls", "-l"])  # doesn't capture output
    CompletedProcess(args=['ls', '-l'], returncode=0)
    
    >>> subprocess.run("exit 1", shell=True, check=True)
    Traceback (most recent call last):
      ...
    subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1
    
    >>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
    CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
    stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
    
    57 tức là, trong chế độ văn bản)

  • Bất kỳ giá trị dương nào khác có nghĩa là sử dụng bộ đệm có kích thước xấp xỉ

  • Bufsize âm (mặc định) có nghĩa là mặc định hệ thống của io.default_buffer_size sẽ được sử dụng.

Đã thay đổi trong phiên bản 3.3.1: Bufsize hiện có mặc định thành -1 để bật bộ đệm theo mặc định để phù hợp với hành vi mà hầu hết mã mong đợi. Trong các phiên bản trước Python 3.2.4 và 3.3.1, nó được mặc định không chính xác là

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
55 được không bị truy cập và cho phép đọc ngắn. Điều này là vô ý và không phù hợp với hành vi của Python 2 như hầu hết các mã mong đợi.bufsize now defaults to -1 to enable buffering by default to match the behavior that most code expects. In versions prior to Python 3.2.4 and 3.3.1 it incorrectly defaulted to
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
55 which was unbuffered and allowed short reads. This was unintentional and did not match the behavior of Python 2 as most code expected.

Đối số thực thi chỉ định một chương trình thay thế để thực thi. Nó rất hiếm khi cần thiết. Khi

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
39, thực thi có thể thay thế chương trình để thực hiện được chỉ định bởi Args. Tuy nhiên, ARG ban đầu vẫn được chuyển cho chương trình. Hầu hết các chương trình coi chương trình được ARG chỉ định là tên lệnh, sau đó có thể khác với chương trình thực sự được thực hiện. Trên Posix, tên ARGS trở thành tên hiển thị cho các tiện ích có thể thực thi như PS. Nếu
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
47, trên POSIX đối số thực thi chỉ định một shell thay thế cho
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
48 mặc định.ps. If
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
47, on POSIX the executable argument specifies a replacement shell for the default
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
48.

Thay đổi trong phiên bản 3.6: Tham số thực thi chấp nhận một đối tượng giống như đường dẫn trên POSIX.executable parameter accepts a path-like object on POSIX.

Thay đổi trong phiên bản 3.8: Tham số thực thi chấp nhận một byte và đối tượng giống như đường dẫn trên Windows.executable parameter accepts a bytes and path-like object on Windows.

Stdin, stdout và stderr chỉ định đầu vào tiêu chuẩn của chương trình, đầu ra tiêu chuẩn và tay cầm tệp tiêu chuẩn, tương ứng. Các giá trị hợp lệ là

>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'
9,
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
00, một bộ mô tả tệp hiện có (một số nguyên dương), một đối tượng tệp hiện có với bộ mô tả tệp hợp lệ và
with Popen(["ifconfig"], stdout=PIPE) as proc:
    log.write(proc.stdout.read())
0.
>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'
9 chỉ ra rằng một đường ống mới cho trẻ nên được tạo ra.
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
00 chỉ ra rằng tệp đặc biệt
proc = subprocess.Popen(...)
try:
    outs, errs = proc.communicate(timeout=15)
except TimeoutExpired:
    proc.kill()
    outs, errs = proc.communicate()
7 sẽ được sử dụng. Với các cài đặt mặc định của
with Popen(["ifconfig"], stdout=PIPE) as proc:
    log.write(proc.stdout.read())
0, sẽ không có chuyển hướng nào xảy ra; Tay cầm tập tin trẻ con sẽ được kế thừa từ cha mẹ. Ngoài ra, STDERR có thể là
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
06, điều này chỉ ra rằng dữ liệu STDERR từ các ứng dụng phải được ghi vào cùng một tay cầm tệp như đối với stdout.file object with a valid file descriptor, and
with Popen(["ifconfig"], stdout=PIPE) as proc:
    log.write(proc.stdout.read())
0.
>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'
9 indicates that a new pipe to the child should be created.
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
00 indicates that the special file
proc = subprocess.Popen(...)
try:
    outs, errs = proc.communicate(timeout=15)
except TimeoutExpired:
    proc.kill()
    outs, errs = proc.communicate()
7 will be used. With the default settings of
with Popen(["ifconfig"], stdout=PIPE) as proc:
    log.write(proc.stdout.read())
0, no redirection will occur; the child’s file handles will be inherited from the parent. Additionally, stderr can be
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
06, which indicates that the stderr data from the applications should be captured into the same file handle as for stdout.

Nếu preexec_fn được đặt thành một đối tượng có thể gọi được, đối tượng này sẽ được gọi trong quá trình con ngay trước khi đứa trẻ được thực thi. (Chỉ Posix)

Cảnh báo

Tham số PEREXEC_FN không an toàn để sử dụng với sự hiện diện của các luồng trong ứng dụng của bạn. Quá trình trẻ em có thể bế tắc trước khi EXEC được gọi.

Ghi chú

Nếu bạn cần sửa đổi môi trường cho đứa trẻ sử dụng tham số env thay vì thực hiện nó trong preexec_fn. Các tham số start_new_session và process_group sẽ thay thế mã bằng cách sử dụng preexec_fn để gọi

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
70 hoặc
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
71 ở trẻ.

Đã thay đổi trong phiên bản 3.8: Tham số PreExec_FN không còn được hỗ trợ trong các phần phụ. Việc sử dụng tham số trong trình điều khiển phụ tăng

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
72. Hạn chế mới có thể ảnh hưởng đến các ứng dụng được triển khai trong MOD_WSGI, UWSGI và các môi trường nhúng khác.The preexec_fn parameter is no longer supported in subinterpreters. The use of the parameter in a subinterpreter raises
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
72. The new restriction may affect applications that are deployed in mod_wsgi, uWSGI, and other embedded environments.

Nếu Close_FDS là đúng, tất cả các mô tả tệp ngoại trừ

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
55,
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
56 và
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
75 sẽ bị đóng trước khi quá trình con được thực thi. Mặt khác, khi Close_FDS là sai, các mô tả tệp tuân theo cờ di truyền của họ như được mô tả trong kế thừa của các mô tả tệp.Inheritance of File Descriptors.

Trên Windows, nếu Close_FDS là đúng thì sẽ không có tay cầm nào được kế thừa bởi quy trình con trừ khi được thông qua rõ ràng trong phần tử

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
76 của
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
77 hoặc theo chuyển hướng xử lý tiêu chuẩn.

Đã thay đổi trong phiên bản 3.2: Mặc định cho Close_FDS đã được thay đổi từ

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
43 thành những gì được mô tả ở trên.The default for close_fds was changed from
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
43 to what is described above.

Đã thay đổi trong phiên bản 3.7: Trên Windows, mặc định cho Close_FDS đã được thay đổi từ

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
43 thành
>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'
8 khi chuyển hướng tay cầm tiêu chuẩn. Bây giờ, nó có thể đặt Close_fds thành
>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'
8 khi chuyển hướng các tay cầm tiêu chuẩn.On Windows the default for close_fds was changed from
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
43 to
>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'
8 when redirecting the standard handles. It’s now possible to set close_fds to
>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'
8 when redirecting the standard handles.

pass_fds là một chuỗi các mô tả tệp tùy chọn để tiếp tục mở giữa cha mẹ và con cái. Cung cấp bất kỳ lực lượng pass_fds gần

>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'
8. (Chỉ Posix)

Đã thay đổi trong phiên bản 3.2: Tham số pass_fds đã được thêm vào.The pass_fds parameter was added.

Nếu CWD không phải là

with Popen(["ifconfig"], stdout=PIPE) as proc:
    log.write(proc.stdout.read())
0, chức năng sẽ thay đổi thư mục làm việc thành CWD trước khi thực hiện trẻ. CWD có thể là một chuỗi, byte hoặc đối tượng giống như đường dẫn. Trên POSIX, hàm tìm kiếm thực thi (hoặc cho mục đầu tiên trong ARGS) so với CWD nếu đường dẫn thực thi là một đường dẫn tương đối.path-like object. On POSIX, the function looks for executable (or for the first item in args) relative to cwd if the executable path is a relative path.

Thay đổi trong phiên bản 3.6: Tham số CWD chấp nhận một đối tượng giống như đường dẫn trên POSIX.cwd parameter accepts a path-like object on POSIX.

Thay đổi trong phiên bản 3.7: Tham số CWD chấp nhận một đối tượng giống như đường dẫn trên Windows.cwd parameter accepts a path-like object on Windows.

Thay đổi trong phiên bản 3.8: Tham số CWD chấp nhận đối tượng byte trên Windows.cwd parameter accepts a bytes object on Windows.

Nếu restore_signals là đúng (mặc định), tất cả các tín hiệu mà python đã đặt thành sig_ign được khôi phục thành sig_dfl trong quy trình con trước khi thực hiện. Hiện tại điều này bao gồm các tín hiệu Sigpipe, SigXFZ và SigXFSZ. (Chỉ Posix)

Đã thay đổi trong phiên bản 3.2: Restore_signals đã được thêm vào.restore_signals was added.

Nếu start_new_session là đúng, cuộc gọi hệ thống

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
84 sẽ được thực hiện trong quy trình con trước khi thực hiện quy trình con.

Tính khả dụng: Posix: POSIX

Đã thay đổi trong phiên bản 3.2: start_new_session đã được thêm vào.start_new_session was added.

Nếu Process_group là một số nguyên không âm, cuộc gọi hệ thống

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
85 sẽ được thực hiện trong quy trình con trước khi thực hiện quy trình con.

Tính khả dụng: Posix: POSIX

Đã thay đổi trong phiên bản 3.2: start_new_session đã được thêm vào.process_group was added.

Nếu Process_group là một số nguyên không âm, cuộc gọi hệ thống

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
85 sẽ được thực hiện trong quy trình con trước khi thực hiện quy trình con.

Tính khả dụng: Posix: POSIX

Đã thay đổi trong phiên bản 3.2: start_new_session đã được thêm vào.

Nếu Process_group là một số nguyên không âm, cuộc gọi hệ thống

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
85 sẽ được thực hiện trong quy trình con trước khi thực hiện quy trình con.

Tính khả dụng: Posix: POSIX

Đã thay đổi trong phiên bản 3.2: start_new_session đã được thêm vào.

Nếu Process_group là một số nguyên không âm, cuộc gọi hệ thống

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
85 sẽ được thực hiện trong quy trình con trước khi thực hiện quy trình con.

Tính khả dụng: Posix: POSIX

Đã thay đổi trong phiên bản 3.2: start_new_session đã được thêm vào.

Nếu Process_group là một số nguyên không âm, cuộc gọi hệ thống

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
85 sẽ được thực hiện trong quy trình con trước khi thực hiện quy trình con.

Tính khả dụng: Posix: POSIX

Đã thay đổi trong phiên bản 3.2: start_new_session đã được thêm vào.

Nếu Process_group là một số nguyên không âm, cuộc gọi hệ thống

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
85 sẽ được thực hiện trong quy trình con trước khi thực hiện quy trình con.

Đã thay đổi trong phiên bản 3.11: Process_group đã được thêm vào.

Nếu nhóm không phải là

with Popen(["ifconfig"], stdout=PIPE) as proc:
    log.write(proc.stdout.read())
0, cuộc gọi hệ thống setregid () sẽ được thực hiện trong quy trình con trước khi thực hiện quy trình con. Nếu giá trị được cung cấp là một chuỗi, nó sẽ được tra cứu qua
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
87 và giá trị trong
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
88 sẽ được sử dụng. Nếu giá trị là một số nguyên, nó sẽ được truyền nguyên văn. (Chỉ Posix)must include a valid
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
98.

Mới trong phiên bản 3.9.Frequently Used Arguments. The universal_newlines argument is equivalent to text and is provided for backwards compatibility. By default, file objects are opened in binary mode.

Nếu Extra_groups không phải là

with Popen(["ifconfig"], stdout=PIPE) as proc:
    log.write(proc.stdout.read())
0, cuộc gọi hệ thống setgroup () sẽ được thực hiện trong quy trình con trước khi thực hiện quy trình con. Các chuỗi được cung cấp trong các nhóm thêm sẽ được tra cứu qua
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
87 và các giá trị trong
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
88 sẽ được sử dụng. Giá trị số nguyên sẽ được truyền nguyên văn. (Chỉ Posix)encoding and errors were added.

Nếu người dùng không phải là

with Popen(["ifconfig"], stdout=PIPE) as proc:
    log.write(proc.stdout.read())
0, cuộc gọi hệ thống setreuid () sẽ được thực hiện trong quy trình con trước khi thực hiện quy trình con. Nếu giá trị được cung cấp là một chuỗi, nó sẽ được tra cứu qua
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
93 và giá trị trong
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
94 sẽ được sử dụng. Nếu giá trị là một số nguyên, nó sẽ được truyền nguyên văn. (Chỉ Posix)text was added as a more readable alias for universal_newlines.

Nếu UMASK không âm, cuộc gọi hệ thống Umask () sẽ được thực hiện trong quy trình con trước khi thực hiện quy trình con.

  • Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
    
    01

  • Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
    
    02

  • Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
    
    03

  • Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
    
    04

  • Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
    
    05

  • Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
    
    06

  • Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
    
    07

  • Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
    
    08

  • Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
    
    09

  • Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
    
    10

  • Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
    
    11

  • Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
    
    12

Nếu env không phải là

with Popen(["ifconfig"], stdout=PIPE) as proc:
    log.write(proc.stdout.read())
0, thì đó phải là một ánh xạ xác định các biến môi trường cho quy trình mới; Chúng được sử dụng thay vì hành vi mặc định của việc kế thừa môi trường quy trình hiện tại. Ánh xạ này có thể được STR trên bất kỳ nền tảng hoặc byte nào cho byte trên các nền tảng POSIX giống như
with Popen(["ifconfig"], stdout=PIPE) as proc:
    log.write(proc.stdout.read())
2 hoặc
with Popen(["ifconfig"], stdout=PIPE) as proc:
    log.write(proc.stdout.read())
3.

Mới trong phiên bản 3.10: Tham số

Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
14 đã được thêm vào.The
Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
14 parameter was added.

Các đối tượng popen được hỗ trợ dưới dạng các trình quản lý ngữ cảnh thông qua câu lệnh

Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
15: Khi thoát, các mô tả tệp tiêu chuẩn được đóng và quá trình được chờ đợi.

with Popen(["ifconfig"], stdout=PIPE) as proc:
    log.write(proc.stdout.read())

Popen và các chức năng khác trong mô -đun này sử dụng nó nâng cao sự kiện kiểm toán

Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
16 với các đối số
Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
17,
Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
18,
Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
19 và
Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
20. Giá trị cho
Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
18 có thể là một chuỗi hoặc một danh sách các chuỗi, tùy thuộc vào nền tảng.auditing event
Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
16 with arguments
Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
17,
Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
18,
Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
19, and
Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
20. The value for
Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
18 may be a single string or a list of strings, depending on platform.

Đã thay đổi trong phiên bản 3.2: Đã thêm hỗ trợ Trình quản lý bối cảnh.Added context manager support.

Đã thay đổi trong phiên bản 3.6: Công cụ phá hủy popen hiện phát ra cảnh báo

Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
22 nếu quá trình con vẫn đang chạy.Popen destructor now emits a
Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
22 warning if the child process is still running.

Đã thay đổi trong phiên bản 3.8: Popen có thể sử dụng

Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
23 trong một số trường hợp để có hiệu suất tốt hơn. Trên hệ thống con Windows cho mô phỏng người dùng Linux và QEMU, hàm tạo popen sử dụng
Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
23 không còn gây ra ngoại lệ về các lỗi như bị thiếu chương trình, nhưng quá trình con không thành công với một
proc = subprocess.Popen(...)
try:
    outs, errs = proc.communicate(timeout=15)
except TimeoutExpired:
    proc.kill()
    outs, errs = proc.communicate()
4 khác không.Popen can use
Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
23 in some cases for better performance. On Windows Subsystem for Linux and QEMU User Emulation, Popen constructor using
Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
23 no longer raise an exception on errors like missing program, but the child process fails with a non-zero
proc = subprocess.Popen(...)
try:
    outs, errs = proc.communicate(timeout=15)
except TimeoutExpired:
    proc.kill()
    outs, errs = proc.communicate()
4.

Ngoại lệ ha

Các trường hợp ngoại lệ được nêu ra trong quy trình trẻ em, trước khi chương trình mới bắt đầu thực thi, sẽ được nuôi dưỡng lại trong cha mẹ.

Ngoại lệ phổ biến nhất được nâng lên là

Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
26. Điều này xảy ra, ví dụ, khi cố gắng thực thi một tệp không tồn tại. Các ứng dụng nên chuẩn bị cho các ngoại lệ
Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
26. Lưu ý rằng, khi
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
47,
Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
26 sẽ được con nuôi chỉ khi không tìm thấy vỏ được chọn. Để xác định xem shell không tìm thấy ứng dụng được yêu cầu, cần phải kiểm tra mã trả về hoặc đầu ra từ quy trình con.

Một

Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
30 sẽ được nâng lên nếu
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
5 được gọi với các đối số không hợp lệ.

run(..., check=True, stdout=PIPE).stdout
7 và
si = subprocess.STARTUPINFO()
si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW
3 sẽ tăng
Popen(['/bin/sh', '-c', args[0], args[1], ...])
8 nếu quá trình được gọi là trả lại mã trả lại khác không.

Tất cả các chức năng và phương thức chấp nhận tham số thời gian chờ, chẳng hạn như

Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
35 và
Popen(['/bin/sh', '-c', args[0], args[1], ...])
3 sẽ tăng
Popen(['/bin/sh', '-c', args[0], args[1], ...])
4 nếu thời gian chờ hết hạn trước khi quá trình thoát ra.

Các ngoại lệ được xác định trong mô -đun này tất cả kế thừa từ

si = subprocess.STARTUPINFO()
si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW
1.

Cân nhắc về Bảo mật¶

Không giống như một số chức năng popen khác, việc triển khai này sẽ không bao giờ hoàn toàn gọi một shell hệ thống. Điều này có nghĩa là tất cả các nhân vật, bao gồm cả các metacharacters shell, có thể được truyền một cách an toàn cho các quá trình trẻ em. Nếu vỏ được gọi rõ ràng, thông qua

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
47, thì trách nhiệm của ứng dụng là đảm bảo rằng tất cả các chất trắng và metacharacters được trích dẫn một cách thích hợp để tránh các lỗ hổng tiêm vỏ. Trên một số nền tảng, có thể sử dụng
Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
40 cho việc trốn thoát này.some platforms, it is possible to use
Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
40 for this escaping.

Đối tượng Popen

Các thể hiện của lớp

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
5 có các phương pháp sau:

Popen.poll () ¶poll()

Kiểm tra nếu quá trình trẻ em đã chấm dứt. Đặt và trả về thuộc tính

proc = subprocess.Popen(...)
try:
    outs, errs = proc.communicate(timeout=15)
except TimeoutExpired:
    proc.kill()
    outs, errs = proc.communicate()
4. Nếu không, trả về
with Popen(["ifconfig"], stdout=PIPE) as proc:
    log.write(proc.stdout.read())
0.

Popen.wait (thời gian chờ = không) ¶wait(timeout=None)

Chờ quá trình trẻ em chấm dứt. Đặt và trả về thuộc tính

proc = subprocess.Popen(...)
try:
    outs, errs = proc.communicate(timeout=15)
except TimeoutExpired:
    proc.kill()
    outs, errs = proc.communicate()
4.

Nếu quá trình không chấm dứt sau thời gian chờ giây, hãy tăng ngoại lệ

Popen(['/bin/sh', '-c', args[0], args[1], ...])
4. Nó là an toàn để bắt được ngoại lệ này và thử lại sự chờ đợi.

Ghi chú

Điều này sẽ bế tắc khi sử dụng

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
9 hoặc
Popen(['/bin/sh', '-c', args[0], args[1], ...])
0 và quy trình con tạo ra đủ đầu ra cho một đường ống sao cho nó chặn chờ bộ đệm ống OS chấp nhận thêm dữ liệu. Sử dụng
Popen(['/bin/sh', '-c', args[0], args[1], ...])
3 khi sử dụng đường ống để tránh điều đó.

Thay đổi trong phiên bản 3.3: Thời gian chờ đã được thêm vào.timeout was added.

Popen.Commenticate (input = none, timeout = none) ¶communicate(input=None, timeout=None)

Tương tác với quy trình: Gửi dữ liệu đến Stdin. Đọc dữ liệu từ stdout và stderr, cho đến khi đạt được phần cuối. Đợi quá trình chấm dứt và đặt thuộc tính

proc = subprocess.Popen(...)
try:
    outs, errs = proc.communicate(timeout=15)
except TimeoutExpired:
    proc.kill()
    outs, errs = proc.communicate()
4. Đối số đầu vào tùy chọn phải là dữ liệu được gửi đến quy trình con hoặc
with Popen(["ifconfig"], stdout=PIPE) as proc:
    log.write(proc.stdout.read())
0, nếu không có dữ liệu nào được gửi cho trẻ. Nếu các luồng được mở ở chế độ văn bản, đầu vào phải là một chuỗi. Nếu không, nó phải là byte.

Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
51 Trả về một tuple
Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
52. Dữ liệu sẽ là chuỗi nếu các luồng được mở ở chế độ văn bản; Nếu không, byte.

Lưu ý rằng nếu bạn muốn gửi dữ liệu đến quy trình STDIN, bạn cần tạo đối tượng popen bằng

Popen(['/bin/sh', '-c', args[0], args[1], ...])
7. Tương tự, để có được bất cứ thứ gì khác ngoài
with Popen(["ifconfig"], stdout=PIPE) as proc:
    log.write(proc.stdout.read())
0 trong kết quả, bạn cũng cần cung cấp cho
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
9 và/hoặc
Popen(['/bin/sh', '-c', args[0], args[1], ...])
0.

Nếu quá trình không chấm dứt sau khi hết thời gian chờ, ngoại lệ

Popen(['/bin/sh', '-c', args[0], args[1], ...])
4 sẽ được nâng lên. Bắt được ngoại lệ này và giao tiếp thử lại sẽ không mất bất kỳ đầu ra nào.

Quá trình trẻ em không bị giết nếu hết thời gian chờ, vì vậy để dọn dẹp đúng một ứng dụng được cư xử tốt nên tiêu diệt quy trình trẻ em và kết thúc giao tiếp:

proc = subprocess.Popen(...)
try:
    outs, errs = proc.communicate(timeout=15)
except TimeoutExpired:
    proc.kill()
    outs, errs = proc.communicate()

Ghi chú

Điều này sẽ bế tắc khi sử dụng

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
9 hoặc
Popen(['/bin/sh', '-c', args[0], args[1], ...])
0 và quy trình con tạo ra đủ đầu ra cho một đường ống sao cho nó chặn chờ bộ đệm ống OS chấp nhận thêm dữ liệu. Sử dụng
Popen(['/bin/sh', '-c', args[0], args[1], ...])
3 khi sử dụng đường ống để tránh điều đó.

Thay đổi trong phiên bản 3.3: Thời gian chờ đã được thêm vào.timeout was added.

Popen.Commenticate (input = none, timeout = none) ¶send_signal(signal)

Tương tác với quy trình: Gửi dữ liệu đến Stdin. Đọc dữ liệu từ stdout và stderr, cho đến khi đạt được phần cuối. Đợi quá trình chấm dứt và đặt thuộc tính

proc = subprocess.Popen(...)
try:
    outs, errs = proc.communicate(timeout=15)
except TimeoutExpired:
    proc.kill()
    outs, errs = proc.communicate()
4. Đối số đầu vào tùy chọn phải là dữ liệu được gửi đến quy trình con hoặc
with Popen(["ifconfig"], stdout=PIPE) as proc:
    log.write(proc.stdout.read())
0, nếu không có dữ liệu nào được gửi cho trẻ. Nếu các luồng được mở ở chế độ văn bản, đầu vào phải là một chuỗi. Nếu không, nó phải là byte.

Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
51 Trả về một tuple
Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
52. Dữ liệu sẽ là chuỗi nếu các luồng được mở ở chế độ văn bản; Nếu không, byte.

Ghi chú

Trên Windows, Sigterm là bí danh cho

Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
58. CTRL_C_EVENT và CTRL_BREAK_EVENT có thể được gửi đến các quy trình bắt đầu với tham số CreationFlags bao gồm
Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
02.

Popen.erminate () ¶terminate()

Ngừng đứa trẻ. Trên Posix OSS, phương pháp gửi Sigterm cho đứa trẻ. Trên Windows, hàm API Win32

Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
60 được gọi để ngăn chặn đứa trẻ.

Popen.kill ()kill()

Giết chết đứa trẻ. Trên posix oss, chức năng gửi sigkill cho trẻ. Trên Windows

Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
61 là bí danh cho
Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
58.

Các thuộc tính sau cũng có sẵn:

Popen.args¶args

Đối số Args khi nó được chuyển đến

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
5 - một chuỗi các đối số chương trình hoặc một chuỗi khác.

Mới trong phiên bản 3.3.

Popen.stdin¶stdin

Nếu đối số Stdin là

>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'
9, thuộc tính này là một đối tượng luồng có thể ghi được được trả về bởi
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
54. Nếu các đối số mã hóa hoặc lỗi được chỉ định hoặc đối số Universal_Newlines là
>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'
8, luồng là luồng văn bản, nếu không thì đó là luồng byte. Nếu đối số Stdin không phải là
>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'
9, thuộc tính này là
with Popen(["ifconfig"], stdout=PIPE) as proc:
    log.write(proc.stdout.read())
0.

Popen.stdout¶stdout

Nếu đối số stdout là

>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'
9, thuộc tính này là một đối tượng luồng có thể đọc được được trả về bởi
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
54. Đọc từ luồng cung cấp đầu ra từ quá trình trẻ em. Nếu các đối số mã hóa hoặc lỗi được chỉ định hoặc đối số Universal_Newlines là
>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'
8, luồng là luồng văn bản, nếu không thì đó là luồng byte. Nếu đối số stdout không phải là
>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'
9, thuộc tính này là
with Popen(["ifconfig"], stdout=PIPE) as proc:
    log.write(proc.stdout.read())
0.

Popen.stderr¶stderr

Nếu đối số STDERR là

>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'
9, thuộc tính này là một đối tượng luồng có thể đọc được được trả về bởi
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
54. Đọc từ luồng cung cấp đầu ra lỗi từ quá trình con. Nếu các đối số mã hóa hoặc lỗi được chỉ định hoặc đối số Universal_Newlines là
>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'
8, luồng là luồng văn bản, nếu không thì đó là luồng byte. Nếu đối số Stderr không phải là
>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'
9, thuộc tính này là
with Popen(["ifconfig"], stdout=PIPE) as proc:
    log.write(proc.stdout.read())
0.

Popen.pid¶pid

ID quy trình của quá trình trẻ em.

Lưu ý rằng nếu bạn đặt đối số shell thành

>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'
8, đây là ID quy trình của vỏ được sinh ra.

Popen.returncode¶returncode

Mã trả về con, được đặt bởi

Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
80 và
Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
81 (và gián tiếp bởi
Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
51). Giá trị
with Popen(["ifconfig"], stdout=PIPE) as proc:
    log.write(proc.stdout.read())
0 chỉ ra rằng quá trình này đã chấm dứt.

Giá trị âm

with Popen(["ifconfig"], stdout=PIPE) as proc:
    log.write(proc.stdout.read())
5 chỉ ra rằng đứa trẻ bị chấm dứt bởi tín hiệu
with Popen(["ifconfig"], stdout=PIPE) as proc:
    log.write(proc.stdout.read())
6 (chỉ POSIX).

Windows Popen Helpers¶

Lớp

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
99 và các hằng số sau đây chỉ có sẵn trên Windows.

classSubProcess.StartUpInfo (*, dwflags = 0, hstdinput = none, hstDoutput = none, hstderror = none, wshowWindow = 0, lpattributelist = none)subprocess.STARTUPINFO(*, dwFlags=0, hStdInput=None, hStdOutput=None, hStdError=None, wShowWindow=0, lpAttributeList=None)

Hỗ trợ một phần của cấu trúc Windows startupInfo được sử dụng để tạo

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
5. Các thuộc tính sau đây có thể được đặt bằng cách truyền chúng dưới dạng đối số chỉ từ khóa.

Thay đổi trong phiên bản 3.7: Hỗ trợ đối số chỉ từ khóa đã được thêm vào.Keyword-only argument support was added.

dwflags¶

Một trường bit xác định xem một số thuộc tính

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
99 có được sử dụng khi quá trình tạo ra một cửa sổ.

si = subprocess.STARTUPINFO()
si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW

hstdinput¶

Nếu

Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
89 Chỉ định
Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
90, thuộc tính này là tay cầm đầu vào tiêu chuẩn cho quy trình. Nếu
Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
90 không được chỉ định, mặc định cho đầu vào tiêu chuẩn là bộ đệm bàn phím.

Hstdoutput¶

Nếu

Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
89 chỉ định
Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
90, thuộc tính này là tay cầm đầu ra tiêu chuẩn cho quy trình. Mặt khác, thuộc tính này bị bỏ qua và mặc định cho đầu ra tiêu chuẩn là bộ đệm cửa sổ console.

hstderror¶

Nếu

Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
89 Chỉ định
Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
90, thuộc tính này là xử lý lỗi tiêu chuẩn cho quy trình. Mặt khác, thuộc tính này bị bỏ qua và mặc định cho lỗi tiêu chuẩn là bộ đệm cửa sổ console.

wshowwindow¶

Nếu

Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
89 chỉ định
Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
97, thuộc tính này có thể là bất kỳ giá trị nào có thể được chỉ định trong tham số
Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
98 cho hàm showWindow, ngoại trừ
Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
99. Nếu không, thuộc tính này bị bỏ qua.

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
00 được cung cấp cho thuộc tính này. Nó được sử dụng khi
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
5 được gọi với
>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
47.

lpattributelist¶

Một từ điển các thuộc tính bổ sung để tạo quá trình như được đưa ra trong

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
03, xem UpdateProcThreadAttribution.

Các thuộc tính được hỗ trợ:

handle_list

Trình tự của tay cầm sẽ được kế thừa. Close_fds phải đúng nếu không trống.

Các tay cầm phải tạm thời được kế thừa bằng

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
04 khi được chuyển cho hàm tạo
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
5, nếu không
Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
26 sẽ được nâng lên với lỗi Windows
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
07 (87).

Cảnh báo

Trong một quy trình đa luồng, sử dụng thận trọng để tránh các tay cầm bị rò rỉ có thể di truyền khi kết hợp tính năng này với các cuộc gọi đồng thời đến các chức năng tạo quy trình khác kế thừa tất cả các tay cầm như

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
08. Điều này cũng áp dụng cho chuyển hướng xử lý tiêu chuẩn, tạm thời tạo ra tay cầm có thể thừa kế.

Mới trong phiên bản 3.7.

Hằng số cửa sổ hằng số

Mô -đun

Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
9 hiển thị các hằng số sau.

SubProcess.std_input_handle¶STD_INPUT_HANDLE

Thiết bị đầu vào tiêu chuẩn. Ban đầu, đây là bộ đệm đầu vào bảng điều khiển,

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
10.

Subprocess.std_output_handle¶STD_OUTPUT_HANDLE

Thiết bị đầu ra tiêu chuẩn. Ban đầu, đây là bộ đệm màn hình bảng điều khiển hoạt động,

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
11.

SubProcess.std_error_handle¶STD_ERROR_HANDLE

Thiết bị lỗi tiêu chuẩn. Ban đầu, đây là bộ đệm màn hình bảng điều khiển hoạt động,

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
11.

quá trình phụ.sw_hide¶SW_HIDE

Giấu cửa sổ. Một cửa sổ khác sẽ được kích hoạt.

phụSTARTF_USESTDHANDLES

Chỉ định rằng các thuộc tính

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
13,
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
14 và
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
15 chứa thông tin bổ sung.

SubProcess.startf_useshowwindow¶STARTF_USESHOWWINDOW

Chỉ định rằng thuộc tính

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
16 chứa thông tin bổ sung.

SubProcess.Create_New_Console¶CREATE_NEW_CONSOLE

Quá trình mới có một giao diện điều khiển mới, thay vì kế thừa bảng điều khiển cha mẹ của nó (mặc định).

SubProcess.Create_New_Process_group¶CREATE_NEW_PROCESS_GROUP

Tham số

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
5
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
18 để chỉ định rằng một nhóm quy trình mới sẽ được tạo. Cờ này là cần thiết để sử dụng
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
19 trên quy trình con.

Cờ này bị bỏ qua nếu

Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
01 được chỉ định.

phụABOVE_NORMAL_PRIORITY_CLASS

Tham số

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
5
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
18 để chỉ định rằng một quy trình mới sẽ có mức độ ưu tiên trên trung bình.

Mới trong phiên bản 3.7.

phụBELOW_NORMAL_PRIORITY_CLASS

Tham số

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
5
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
18 để chỉ định rằng một quy trình mới sẽ có mức độ ưu tiên dưới mức trung bình.

Mới trong phiên bản 3.7.

phụHIGH_PRIORITY_CLASS

Tham số

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
5
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
18 để chỉ định rằng một quy trình mới sẽ có mức độ ưu tiên cao.

Mới trong phiên bản 3.7.

phụIDLE_PRIORITY_CLASS

Tham số

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
5
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
18 để chỉ định rằng một quy trình mới sẽ có mức độ ưu tiên không hoạt động (thấp nhất).

Mới trong phiên bản 3.7.

phụNORMAL_PRIORITY_CLASS

Tham số

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
5
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
18 để chỉ định rằng một quy trình mới sẽ có mức độ ưu tiên bình thường. (mặc định)

Mới trong phiên bản 3.7.

phụREALTIME_PRIORITY_CLASS

Tham số

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
5
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
18 để chỉ định rằng một quy trình mới sẽ có mức độ ưu tiên thời gian thực. Bạn hầu như không bao giờ nên sử dụng realtime_priority_class, bởi vì điều này làm gián đoạn các luồng hệ thống quản lý đầu vào chuột, đầu vào bàn phím và xả đĩa nền. Lớp này có thể phù hợp với các ứng dụng mà nói chuyện trực tiếp với phần cứng hoặc thực hiện các tác vụ ngắn gọn nên bị gián đoạn hạn chế.

Mới trong phiên bản 3.7.

SubProcess.Create_NO_Window¶CREATE_NO_WINDOW

Tham số

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
5
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
18 để chỉ định rằng một quy trình mới sẽ không tạo cửa sổ.

Mới trong phiên bản 3.7.

quá trình phụ .detached_process¶DETACHED_PROCESS

Tham số

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
5
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
18 để chỉ định rằng một quy trình mới sẽ không kế thừa bảng điều khiển cha mẹ của nó. Giá trị này không thể được sử dụng với create_new_console.

Mới trong phiên bản 3.7.

SubProcess.Create_Default_error_Mode¶CREATE_DEFAULT_ERROR_MODE

Tham số

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
5
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
18 để chỉ định rằng một quy trình mới không kế thừa chế độ lỗi của quá trình gọi. Thay vào đó, quy trình mới có chế độ lỗi mặc định. Tính năng này đặc biệt hữu ích cho các ứng dụng shell đa luồng chạy với các lỗi cứng bị vô hiệu hóa.

Mới trong phiên bản 3.7.

phụCREATE_BREAKAWAY_FROM_JOB

Tham số

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
5
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
18 để chỉ định rằng một quy trình mới không liên quan đến công việc.

Mới trong phiên bản 3.7.

API cấp cao cũ hơn

Trước Python 3.5, ba chức năng này bao gồm API cấp cao để xử lý phụ. Bây giờ bạn có thể sử dụng

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
4 trong nhiều trường hợp, nhưng rất nhiều mã hiện tại gọi các chức năng này.

Subprocess.call (args, *, stdin = none, stdout = none, stderr = none, shell = falsecall(args, *, stdin=None, stdout=None, stderr=None, shell=False, cwd=None, timeout=None, **other_popen_kwargs)

Chạy lệnh được mô tả bởi Args. Đợi lệnh hoàn thành, sau đó trả lại thuộc tính

proc = subprocess.Popen(...)
try:
    outs, errs = proc.communicate(timeout=15)
except TimeoutExpired:
    proc.kill()
    outs, errs = proc.communicate()
4.

Mã cần bắt giữ Stdout hoặc Stderr nên sử dụng

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
4 thay thế:

Để ngăn chặn stdout hoặc stderr, cung cấp giá trị

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
00.

Các đối số hiển thị ở trên chỉ là một số thông thường. Chữ ký chức năng đầy đủ giống như hàm xây dựng

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
5 - hàm này chuyển tất cả các đối số được cung cấp khác ngoài thời gian chờ trực tiếp đến giao diện đó.

Ghi chú

Không sử dụng

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
9 hoặc
Popen(['/bin/sh', '-c', args[0], args[1], ...])
0 với chức năng này. Quá trình con sẽ chặn nếu nó tạo ra đủ đầu ra cho một đường ống để lấp đầy bộ đệm ống OS vì các đường ống không được đọc từ đó.

Thay đổi trong phiên bản 3.3: Thời gian chờ đã được thêm vào.timeout was added.

Subprocess.check_call (args, *, stdin = none, stdout = none, stderr = none, shell = falsecheck_call(args, *, stdin=None, stdout=None, stderr=None, shell=False, cwd=None, timeout=None, **other_popen_kwargs)

Chạy lệnh với các đối số. Đợi lệnh hoàn thành. Nếu mã trả về bằng không thì hãy quay lại, nếu không thì tăng

Popen(['/bin/sh', '-c', args[0], args[1], ...])
8. Đối tượng
Popen(['/bin/sh', '-c', args[0], args[1], ...])
8 sẽ có mã trả về trong thuộc tính
proc = subprocess.Popen(...)
try:
    outs, errs = proc.communicate(timeout=15)
except TimeoutExpired:
    proc.kill()
    outs, errs = proc.communicate()
4. Nếu
run(..., check=True, stdout=PIPE).stdout
7 không thể bắt đầu quá trình, nó sẽ tuyên truyền ngoại lệ đã được nêu ra.

Mã cần bắt giữ Stdout hoặc Stderr nên sử dụng

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
4 thay thế:

Để ngăn chặn stdout hoặc stderr, cung cấp giá trị

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
00.

Các đối số hiển thị ở trên chỉ là một số thông thường. Chữ ký chức năng đầy đủ giống như hàm xây dựng

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
5 - hàm này chuyển tất cả các đối số được cung cấp khác ngoài thời gian chờ trực tiếp đến giao diện đó.

Ghi chú

Không sử dụng

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
9 hoặc
Popen(['/bin/sh', '-c', args[0], args[1], ...])
0 với chức năng này. Quá trình con sẽ chặn nếu nó tạo ra đủ đầu ra cho một đường ống để lấp đầy bộ đệm ống OS vì các đường ống không được đọc từ đó.

Thay đổi trong phiên bản 3.3: Thời gian chờ đã được thêm vào.timeout was added.

Subprocess.check_output (args, *, stdin = none, stderr = none, shell = false, cwd = none, encoding = nonecheck_output(args, *, stdin=None, stderr=None, shell=False, cwd=None, encoding=None, errors=None, universal_newlines=None, timeout=None, text=None, **other_popen_kwargs)

Chạy lệnh với các đối số và trả về đầu ra của nó.

Nếu mã trả về không khác, nó sẽ tăng

Popen(['/bin/sh', '-c', args[0], args[1], ...])
8. Đối tượng
Popen(['/bin/sh', '-c', args[0], args[1], ...])
8 sẽ có mã trả về trong thuộc tính
proc = subprocess.Popen(...)
try:
    outs, errs = proc.communicate(timeout=15)
except TimeoutExpired:
    proc.kill()
    outs, errs = proc.communicate()
4 và bất kỳ đầu ra nào trong thuộc tính
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
60.

Điều này tương đương với:

run(..., check=True, stdout=PIPE).stdout

Các đối số hiển thị ở trên chỉ là một số thông thường. Chữ ký chức năng đầy đủ phần lớn giống như

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
4 - hầu hết các đối số được chuyển trực tiếp qua giao diện đó. Tồn tại một độ lệch API so với hành vi
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
4: vượt qua
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
63 sẽ hoạt động giống như
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
64 (hoặc
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
65, tùy thuộc vào các đối số khác) thay vì sử dụng xử lý tệp đầu vào tiêu chuẩn của cha mẹ.

Theo mặc định, hàm này sẽ trả về dữ liệu dưới dạng byte được mã hóa. Mã hóa thực tế của dữ liệu đầu ra có thể phụ thuộc vào lệnh được gọi, do đó việc giải mã thành văn bản thường sẽ cần được xử lý ở cấp độ ứng dụng.

Hành vi này có thể bị ghi đè bằng cách đặt văn bản, mã hóa, lỗi hoặc Universal_Newlines thành

>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'
8 như được mô tả trong các đối số được sử dụng thường xuyên và
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
4.Frequently Used Arguments and
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
4.

Để nắm bắt lỗi tiêu chuẩn trong kết quả, hãy sử dụng

with Popen(["ifconfig"], stdout=PIPE) as proc:
    log.write(proc.stdout.read())
9:

>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'

Mới trong phiên bản 3.1.

Thay đổi trong phiên bản 3.3: Thời gian chờ đã được thêm vào.timeout was added.

Subprocess.check_output (args, *, stdin = none, stderr = none, shell = false, cwd = none, encoding = noneSupport for the input keyword argument was added.

Chạy lệnh với các đối số và trả về đầu ra của nó.encoding and errors were added. See

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
4 for details.

Nếu mã trả về không khác, nó sẽ tăng

Popen(['/bin/sh', '-c', args[0], args[1], ...])
8. Đối tượng
Popen(['/bin/sh', '-c', args[0], args[1], ...])
8 sẽ có mã trả về trong thuộc tính
proc = subprocess.Popen(...)
try:
    outs, errs = proc.communicate(timeout=15)
except TimeoutExpired:
    proc.kill()
    outs, errs = proc.communicate()
4 và bất kỳ đầu ra nào trong thuộc tính
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
60.text was added as a more readable alias for universal_newlines.

Điều này tương đương với:

Các đối số hiển thị ở trên chỉ là một số thông thường. Chữ ký chức năng đầy đủ phần lớn giống như

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
4 - hầu hết các đối số được chuyển trực tiếp qua giao diện đó. Tồn tại một độ lệch API so với hành vi
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
4: vượt qua
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
63 sẽ hoạt động giống như
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
64 (hoặc
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
65, tùy thuộc vào các đối số khác) thay vì sử dụng xử lý tệp đầu vào tiêu chuẩn của cha mẹ.

Ghi chú

Không sử dụng

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
9 hoặc
Popen(['/bin/sh', '-c', args[0], args[1], ...])
0 với chức năng này. Quá trình con sẽ chặn nếu nó tạo ra đủ đầu ra cho một đường ống để lấp đầy bộ đệm ống OS vì các đường ống không được đọc từ đó.

Thay đổi trong phiên bản 3.3: Thời gian chờ đã được thêm vào.

Subprocess.check_output (args, *, stdin = none, stderr = none, shell = false, cwd = none, encoding = none

Chạy lệnh với các đối số và trả về đầu ra của nó./bin/sh shell command substitution¶

becomes:

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
0

Nếu mã trả về không khác, nó sẽ tăng Popen(['/bin/sh', '-c', args[0], args[1], ...]) 8. Đối tượng Popen(['/bin/sh', '-c', args[0], args[1], ...]) 8 sẽ có mã trả về trong thuộc tính proc = subprocess.Popen(...) try: outs, errs = proc.communicate(timeout=15) except TimeoutExpired: proc.kill() outs, errs = proc.communicate() 4 và bất kỳ đầu ra nào trong thuộc tính >>> import shlex, subprocess >>> command_line = input() /bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'" >>> args = shlex.split(command_line) >>> print(args) ['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"] >>> p = subprocess.Popen(args) # Success! 60.

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
1

becomes:

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
2

Điều này tương đương với:

Các đối số hiển thị ở trên chỉ là một số thông thường. Chữ ký chức năng đầy đủ phần lớn giống như

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
4 - hầu hết các đối số được chuyển trực tiếp qua giao diện đó. Tồn tại một độ lệch API so với hành vi
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
4: vượt qua
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
63 sẽ hoạt động giống như
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
64 (hoặc
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
65, tùy thuộc vào các đối số khác) thay vì sử dụng xử lý tệp đầu vào tiêu chuẩn của cha mẹ.

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
1

becomes:

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
4

Theo mặc định, hàm này sẽ trả về dữ liệu dưới dạng byte được mã hóa. Mã hóa thực tế của dữ liệu đầu ra có thể phụ thuộc vào lệnh được gọi, do đó việc giải mã thành văn bản thường sẽ cần được xử lý ở cấp độ ứng dụng.

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
5

Notes:

  • Hành vi này có thể bị ghi đè bằng cách đặt văn bản, mã hóa, lỗi hoặc Universal_Newlines thành

    >>> subprocess.check_output(
    ...     "ls non_existent_file; exit 0",
    ...     stderr=subprocess.STDOUT,
    ...     shell=True)
    'ls: non_existent_file: No such file or directory\n'
    
    8 như được mô tả trong các đối số được sử dụng thường xuyên và
    >>> import shlex, subprocess
    >>> command_line = input()
    /bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
    >>> args = shlex.split(command_line)
    >>> print(args)
    ['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
    >>> p = subprocess.Popen(args) # Success!
    
    4.

  • Để nắm bắt lỗi tiêu chuẩn trong kết quả, hãy sử dụng

    with Popen(["ifconfig"], stdout=PIPE) as proc:
        log.write(proc.stdout.read())
    
    9:

  • Mới trong phiên bản 3.1.

Thay đổi trong phiên bản 3.4: Hỗ trợ cho đối số từ khóa đầu vào đã được thêm vào.

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
6

Thay đổi trong phiên bản 3.6: Mã hóa và lỗi đã được thêm vào. Xem >>> import shlex, subprocess >>> command_line = input() /bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'" >>> args = shlex.split(command_line) >>> print(args) ['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"] >>> p = subprocess.Popen(args) # Success! 4 để biết chi tiết.

Mới trong phiên bản 3.7: Văn bản đã được thêm vào dưới dạng bí danh dễ đọc hơn cho Universal_Newlines.

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
7

Thay thế các chức năng cũ bằng mô -đun

Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
9

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
8

Trong phần này, A A trở thành B Bi có nghĩa là B có thể được sử dụng thay thế cho a.

>>> subprocess.run(["ls", "-l"])  # doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n', stderr=b'')
9

Tất cả các chức năng của một người khác trong phần này đều không thành công (ít nhiều) nếu không thể tìm thấy chương trình thực hiện; Thay vào đó, các thay thế của B Biêu tăng

Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
26 thay thế.

Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
0

Ngoài ra, việc thay thế sử dụng si = subprocess.STARTUPINFO() si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW 3 sẽ thất bại với Popen(['/bin/sh', '-c', args[0], args[1], ...]) 8 nếu thao tác được yêu cầu tạo mã trả lại khác không. Đầu ra vẫn có sẵn dưới dạng thuộc tính >>> import shlex, subprocess >>> command_line = input() /bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'" >>> args = shlex.split(command_line) >>> print(args) ['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"] >>> p = subprocess.Popen(args) # Success! 60 của ngoại lệ được nâng lên.

Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
1

Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
2

Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
3

Trong các ví dụ sau, chúng tôi giả định rằng các chức năng liên quan đã được nhập từ mô -đun

Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
9.

Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
4

Thay thế /Bin /SH Shell Lệnh thay thế SHELL

Ghi chú

Thay thế đường ống shell

Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
5

Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
6

Cuộc gọi

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
76 sau khi bắt đầu P2 rất quan trọng để P1 nhận được sigpipe nếu P2 thoát trước P1.

  • Ngoài ra, đối với đầu vào đáng tin cậy, hỗ trợ đường ống riêng Shell Shell vẫn có thể được sử dụng trực tiếp:

  • Thay thế ________ 308¶

  • Gọi chương trình thông qua vỏ thường không được yêu cầu.

  • Giá trị trả về

    Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
    
    35 được mã hóa khác với
    >>> import shlex, subprocess
    >>> command_line = input()
    /bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
    >>> args = shlex.split(command_line)
    >>> print(args)
    ['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
    >>> p = subprocess.Popen(args) # Success!
    
    08.

Hàm >>> import shlex, subprocess >>> command_line = input() /bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'" >>> args = shlex.split(command_line) >>> print(args) ['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"] >>> p = subprocess.Popen(args) # Success! 08 bỏ qua các tín hiệu sigint và sigquit trong khi lệnh đang chạy, nhưng người gọi phải làm điều này một cách riêng biệt khi sử dụng mô -đun Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."]) 9.

Một ví dụ thực tế hơn sẽ trông như thế này:

Subprocess.getStatusOutput (cmd, *, mã hóa = không, lỗi = không) ¶getstatusoutput(cmd, *, encoding=None, errors=None)

Trả về

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
96 của việc thực thi CMD trong vỏ.

Thực hiện chuỗi CMD trong shell với

>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
97 và trả về 2-2-tuple
>>> import shlex, subprocess
>>> command_line = input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print(args)
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
96. Mã hóa và lỗi được sử dụng để giải mã đầu ra; Xem các ghi chú về các đối số thường được sử dụng để biết thêm chi tiết.Frequently Used Arguments for more details.

Một dòng mới được truyền ra từ đầu ra. Mã thoát cho lệnh có thể được hiểu là mã trả lại của quy trình con. Thí dụ:

Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
7

Tính khả dụng: UNIX, Windows.: Unix, Windows.

Thay đổi trong phiên bản 3.3.4: Hỗ trợ Windows đã được thêm vào.Windows support was added.

Hàm bây giờ trả về (outcode, đầu ra) thay vì (trạng thái, đầu ra) như trong Python 3.3.3 và sớm hơn. EXITCODE có cùng giá trị với

proc = subprocess.Popen(...)
try:
    outs, errs = proc.communicate(timeout=15)
except TimeoutExpired:
    proc.kill()
    outs, errs = proc.communicate()
4.

Mới trong phiên bản 3.11: Đã thêm các đối số mã hóa và lỗi.Added encoding and errors arguments.

Subprocess.getOutput (cmd, *, mã hóa = không, lỗi = không) ¶getoutput(cmd, *, encoding=None, errors=None)

Trả về đầu ra (stdout và stderr) của việc thực thi cmd trong shell.

Giống như

Popen(['/bin/sh', '-c', args[0], args[1], ...])
00, ngoại trừ mã thoát bị bỏ qua và giá trị trả về là một chuỗi chứa đầu ra của lệnh. Thí dụ:

Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
8

Tính khả dụng: UNIX, Windows.: Unix, Windows.

Thay đổi trong phiên bản 3.3.4: Hỗ trợ Windows đã được thêm vào.Windows support added

Mới trong phiên bản 3.11: Đã thêm các đối số mã hóa và lỗi.Added encoding and errors arguments.

Subprocess.getOutput (cmd, *, mã hóa = không, lỗi = không) ¶

Trả về đầu ra (stdout và stderr) của việc thực thi cmd trong shell.

Giống như

Popen(['/bin/sh', '-c', args[0], args[1], ...])
00, ngoại trừ mã thoát bị bỏ qua và giá trị trả về là một chuỗi chứa đầu ra của lệnh. Thí dụ:

  1. Đã thay đổi trong phiên bản 3.3.4: được thêm hỗ trợ Windows

  2. Notes¶

  3. Chuyển đổi một chuỗi đối số thành một chuỗi trên Windows¶

  4. Trên Windows, một chuỗi Args được chuyển đổi thành một chuỗi có thể được phân tích cú pháp bằng các quy tắc sau (tương ứng với các quy tắc được sử dụng bởi thời gian chạy MS C):

  5. Các đối số được phân định bởi không gian trắng, đó là không gian hoặc một tab.

Một chuỗi được bao quanh bởi các dấu ngoặc kép được hiểu là một đối số duy nhất, bất kể không gian trắng có trong. Một chuỗi được trích dẫn có thể được nhúng trong một đối số.

Popen(['/bin/sh', '-c', args[0], args[1], ...])
01

Một dấu ngoặc kép có trước một dấu gạch chéo ngược được hiểu là một dấu ngoặc kép theo nghĩa đen.

Backslashes được giải thích theo nghĩa đen, trừ khi chúng ngay lập tức đi trước dấu ngoặc kép.

Nếu dấu gạch chéo ngược ngay trước dấu ngoặc kép, mỗi cặp dấu gạch chéo ngược được hiểu là một dấu gạch chéo ngược theo nghĩa đen. Nếu số lượng dấu gạch chéo ngược là số lẻ, dấu gạch chéo ngược cuối cùng sẽ thoát khỏi dấu ngoặc kép tiếp theo như được mô tả trong Quy tắc 3.

Xem thêm

Mô -đun cung cấp chức năng cho các dòng lệnh phân tích và thoát.

Vô hiệu hóa việc sử dụng

Popen(['/bin/sh', '-c', args[0], args[1], ...])
02 hoặc ________ 403¶

Trên Linux,

Popen(["/usr/bin/git", "commit", "-m", "Fixes a bug."])
9 mặc định sử dụng hệ thống
Popen(['/bin/sh', '-c', args[0], args[1], ...])
02 gọi nội bộ khi an toàn để làm như vậy thay vì
Popen(['/bin/sh', '-c', args[0], args[1], ...])
06. Điều này cải thiện đáng kể hiệu suất.

Nếu bạn từng gặp phải một tình huống được cho là rất bất thường khi bạn cần ngăn chặn

Popen(['/bin/sh', '-c', args[0], args[1], ...])
02 được Python sử dụng, bạn có thể đặt thuộc tính
Popen(['/bin/sh', '-c', args[0], args[1], ...])
08 thành giá trị sai.

SubProcess._USE_VFORK = FALSE # Xem vấn đề Cpython Gh-Nnnnnn.

Cài đặt Điều này không có tác động đến việc sử dụng

Popen(['/bin/sh', '-c', args[0], args[1], ...])
03 có thể sử dụng
Popen(['/bin/sh', '-c', args[0], args[1], ...])
02 trong nội bộ trong quá trình triển khai LIBC của nó. Có một thuộc tính
Popen(['/bin/sh', '-c', args[0], args[1], ...])
11 tương tự nếu bạn cần ngăn chặn việc sử dụng điều đó.
Popen(['/bin/sh', '-c', args[0], args[1], ...])
12

SubProcess._USE_POSIX_SPAWN = FALSE # Xem Cpython vấn đề GH-Nnnnnn.

Popen(['/bin/sh', '-c', args[0], args[1], ...])
13