简体   繁体   English

如何将打印(subprocess.checkout)的输出存储到 Python 中的变量?

[英]How to store the output of a print(subprocess.checkout) to a variable in Python?

I have the below print statement我有以下打印声明

print(subprocess.check_output(['bash', '-c', shell_script], stdin=open('/etc/fstab', 'r')))

that prints few lines like '/xyz NOT mounted' and I would like to store it into a variable just like how the lambda function does it.打印几行像'/ xyz NOT mount',我想将它存储到一个变量中,就像 lambda 函数那样。

out = lambda: print("/xyz NOT mounted")
out()

I would then need to use that variable to write an if statement as in if out contains any string, then print contains string, else contains nothing然后我需要使用该变量来编写 if 语句,如 if out 包含任何字符串,然后打印包含字符串,否则不包含任何内容

Could you please try following, tested and written in Python2.7您能否尝试使用 Python2.7 进行以下、测试和编写

#!/usr/bin/python
import re
out="/xyz NOT mounted"
if re.search(r'[a-zA-Z]+', out):
    print "String found."
else:
    print "String NOT found."

When value of variable out is having string values it prints String found.当变量 out 的值具有字符串值时,它会打印String found.



Now lets test it with NULL value of variable val here.现在让我们在这里用变量 val 的 NULL 值来测试它。

cat script.py
#!/usr/bin/python
import re
out=""
if re.search(r'[a-zA-Z]+', out):
    print "String found."
else:
    print "String NOT found."

When we run above then it gives as String NOT found.当我们在上面运行时,它会给出未String NOT found.

I cannot run your code on my machine because I miss the shell_script part.我无法在我的机器上运行您的代码,因为我错过了 shell_script 部分。

For similar cases I use subprocess.PIPE and collect the output lines in a list that you can iterate and check later:对于类似的情况,我使用 subprocess.PIPE 并将输出行收集在一个列表中,您可以迭代并稍后检查:

import subprocess

def bash_command(cmd):
    sp = subprocess.Popen(['/bin/bash', '-c', cmd], stdout=subprocess.PIPE)
    return sp.stdout.readlines()

result = bash_command('ls') # Insert here your bash command

for line in result:
    if "NOT mounted" in line:
        print("Hey I have a line containing NOT mounted")
    else:
        print("Hey I have a line not containing NOT mounted")

can you not just save the variable and then print it?你不能只保存变量然后打印它吗?

 x = subprocess.check_output()
 print(x)

 #and then...
 if x == ???:
    #do something

Saving the variable and printing it seems a lot easier than trying to grab hold of the print statements' output.保存变量并打印它似乎比试图抓住打印语句的输出要容易得多。

Here, an example to execute a command using subprocess and store and output/buffer data in a variable.这里是使用子进程执行命令并在变量中存储和输出/缓冲数据的示例。

Ex:前任:

Command_Input = subprocess.Popen("Your Command",stdin=process_output.stdout, stdout=subprocess.PIPE, shell=True)
Command_Output = Command_Input.communicate()[0]
Print(Command_Output)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM