Hướng dẫn python shell command output to variable - đầu ra lệnh python shell thành biến

Sử dụng mô -đun

import subprocess
output = subprocess.Popen(['awk', '/f89e7000/ {print $2}', 'syscall_list.txt'], stdout=subprocess.PIPE).communicate()[0]
4 thay thế:

import subprocess
output = subprocess.check_output("cat syscall_list.txt | grep f89e7000 | awk '{print $2}'", shell=True)

Chỉnh sửa: Đây là mới trong Python 2.7. Trong các phiên bản trước, điều này sẽ hoạt động (với lệnh được viết lại như hiển thị bên dưới):

import subprocess
output = subprocess.Popen(['awk', '/f89e7000/ {print $2}', 'syscall_list.txt'], stdout=subprocess.PIPE).communicate()[0]

Như một lưu ý phụ, bạn có thể viết lại

cat syscall_list.txt | grep f89e7000

Đến

grep f89e7000 syscall_list.txt

Và bạn thậm chí có thể thay thế toàn bộ câu lệnh bằng một tập lệnh

import subprocess
output = subprocess.Popen(['awk', '/f89e7000/ {print $2}', 'syscall_list.txt'], stdout=subprocess.PIPE).communicate()[0]
5:

awk '/f89e7000/ {print $2}' syscall_list.txt

Dẫn tới:

import subprocess
output = subprocess.check_output(['awk', '/f89e7000/ {print $2}', 'syscall_list.txt'])

sys.stdout = my_result ..

in ('Hello World') # đầu ra được lưu trữ trong my_result ..

sys.stdout = tmp ..

  1. Giới thiệu
  2. Bài viết này sẽ dạy bạn Shell Lệnh đầu ra cho các biến bằng Python. Sau khi đọc nó, bạn sẽ có thể hiểu thư viện Sub -Process và OS.
  3. Mục lục
  4. Cách Shell Lệnh đầu ra để biến bằng Python
  5. Giải pháp 1

Giới thiệu

Bài viết này sẽ dạy bạn Shell Lệnh đầu ra cho các biến bằng Python. Sau khi đọc nó, bạn sẽ có thể hiểu thư viện Sub -Process và OS.subprocess in Python.
Let’s move to the os library; This module provides a portable way of using operating system dependent functionality. If you want to read or write a file, see open(); if you want to manipulate paths, see the os. path module, and if you're going to read all the lines in all the files on the command line, see the fileinput module. For creating temporary files and directories see the tempfile module, and for high-level file and directory handling, see the shutil module. Notes on the availability of these functions: The design of all built-in operating system dependent modules of Python is such that as long as the same functionality is available, it uses the same interface; for example, the function os.stat(path) returns stat information about a path in the same format (which happens to have originated with the POSIX interface). Extensions peculiar to a particular operating system are also available through the os module, but using them is a threat to portability. All functions accepting path or file names take both bytes and string objects and result in an object of the same type if returned a path or file name. Note All functions in this module raise OSError (or subclasses thereof) in the case of invalid or inaccessible file names and paths or other arguments that have the correct type but are not accepted by the operating system.

Giải pháp 1

Hãy để sử dụng mô -đun phụ trong giải pháp này: Đối với Python 2.7:
For python 2.7:

import subprocess
output = subprocess.check_output("cat syscall_list.txt | grep f89e7000 | awk '{print $2}'", shell=True)

Đối với các phiên bản trước của Python:

import subprocess
output = subprocess.Popen(['awk', '/f89e7000/ {print $2}', 'syscall_list.txt'], stdout=subprocess.PIPE).communicate()[0]

Giải pháp 2

Bây giờ, hãy để Lừa chuyển sang một giải pháp khác! Os.Popen hoạt động cho việc này. Popen - Mở một đường ống đến hoặc từ lệnh. Giá trị trả về là một đối tượng tệp mở được kết nối với đường ống, có thể được đọc. Chia ('\ n') chuyển đổi đầu ra thành danh sách.
os.popen works for this. popen - opens a pipe to or from command. The return value is an open file object connected to the pipe, which can be read. split('\n') converts the output to list.

________số 8

Nói chung

Chúng ta nên sử dụng OS hoặc đầu ra lệnh shell phụ để biến bằng Python.

Sự kết luận

Các phương thức đơn giản nhất để shell đầu ra lệnh cho biến bằng cách sử dụng Python đang sử dụng hệ điều hành hoặc quy trình con.

sys.stdout = my_result ..Home / Linux Tips / How to Run a Shell Command from Python and Get The Output?

in ('Hello World') # đầu ra được lưu trữ trong my_result ..

import os
cmd = 'wc -l my_text_file.txt > out_file.txt'
os.system(cmd)

Nhận đầu ra từ lệnh shell bằng cách sử dụng quy trình con

Một cách tốt hơn để có được đầu ra từ việc thực hiện lệnh Linux trong Python là sử dụng mô -đun Python. Dưới đây là một ví dụ về việc sử dụng quy trình phụ của người Viking để đếm số lượng dòng trong một tệp sử dụng lệnh Linux của WC WC -L.

Trước tiên chúng ta hãy nhập mô -đun phụ

import subprocess
output = subprocess.Popen(['awk', '/f89e7000/ {print $2}', 'syscall_list.txt'], stdout=subprocess.PIPE).communicate()[0]
0

Khởi chạy lệnh shell mà chúng tôi muốn thực thi bằng hàm SubProcess.Popen. Các đối số cho lệnh này là lệnh shell dưới dạng danh sách và chỉ định đầu ra và lỗi.

import subprocess
output = subprocess.Popen(['awk', '/f89e7000/ {print $2}', 'syscall_list.txt'], stdout=subprocess.PIPE).communicate()[0]
1

Đầu ra từ Subprocess.Popen là đối tượng SubProcess.Popen. Và đối tượng này có số lượng các phương thức được liên kết với nó và chúng tôi sẽ sử dụng phương thức Communication () để có được đầu ra và lỗi tiêu chuẩn trong trường hợp là một tuple.

Ở đây, đầu ra tiêu chuẩn chứa kết quả từ lệnh WC -L và Stderr không chứa vì không có lỗi.

import subprocess
output = subprocess.Popen(['awk', '/f89e7000/ {print $2}', 'syscall_list.txt'], stdout=subprocess.PIPE).communicate()[0]
2

Sau đó, chúng ta có thể phân tích stdout để có được kết quả từ lệnh shell trong Python, theo cách chúng ta muốn. Ví dụ: nếu chúng ta chỉ muốn số lượng dòng trong tệp, chúng ta sẽ phân chia stdout

import subprocess
output = subprocess.Popen(['awk', '/f89e7000/ {print $2}', 'syscall_list.txt'], stdout=subprocess.PIPE).communicate()[0]
3

Làm thế nào để bạn xuất một lệnh vào một biến trong Python?

Làm thế nào để bạn đặt đầu ra của một lệnh vào một bash biến ?..
var = $ (tên lệnh-here-here) var = $ (tên lệnh-here arg1) var = $ (/path/to/aborm) var = $ (/path/to/lệnh arg1 arg2).
var = `tên lệnh-here` var =` tên lệnh-here arg1` var = `/path/to/cress` var =`/path/to/lệnh arg1 arg1 arg2`.

Làm thế nào để bạn gán đầu ra của lệnh shell cho một biến?

Bash gán đầu ra của lệnh shell và lưu trữ cho một biến..
var = $ (tên lệnh-here-here) var = $ (tên lệnh-here arg1) var = $ (/path/to/cress) var = $ (/path/to/lệnh arg1 arg2) ....
var = `tên lệnh-here` var =` tên lệnh-here arg1` var = `/path/to/cress` var =`/path/to/lệnh arg1 arg1 arg2`.

$ _ Trong tập lệnh shell là gì?

$ _ (Dollar undercore) là một tham số bash đặc biệt khác và được sử dụng để tham chiếu tên tệp tuyệt đối của tập lệnh shell hoặc bash đang được thực thi như được chỉ định trong danh sách đối số.Tham số bash này cũng được sử dụng để giữ tên của tệp thư trong khi kiểm tra email.another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails.

Làm thế nào để bạn lưu trữ các biến đầu ra trong Python?

Như một cái nhìn tổng quan, đây là mã trong tám dòng lưu trữ đầu ra tiêu chuẩn trong một biến my_result:..
Từ IO Nhập chuỗi Stringio.Cái này là cái gì?....
Nhập SYS ..
TMP = sys.stdout ..
my_result = Stringio ().
sys.stdout = my_result ..
in ('Hello World') # đầu ra được lưu trữ trong my_result ..
sys.stdout = tmp ..
print(result.getvalue()).