在python中使用bash命令脚本

在python中使用bash命令脚本

本文介绍了在python中使用bash命令脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个python脚本,该脚本在运行时会在终端上记录信息,我想将此记录信息发送到文本文件中,

I have a python script which when run, logs information on the terminal, i want to send this logging information to a text file,

要在文件的开头实现此目的,我要插入

To achieve this in the beginning of the file i am inserting

import subprocess
subprocess.call(['script', 'logfile'])

在文件末尾,我放入

subprocess.call(['exit'])

此问题是当它调用第一个命令script logfile时,它将终止脚本,

The problem with this is when it calls the first commandscript logfile,it terminates the script,

关于我如何进行这项工作的任何建议都会非常有帮助,谢谢!

Any suggestions on how i could make this work would be really helpful,Thanks in advance

推荐答案

问题在于,subprocess.call不会返回,直到script生成的shell退出为止,此时您的Python脚本将恢复.

The problem is that subprocess.call isn't returning until the shell spawned by script exits, at which point your Python script will resume.

执行所需操作的最简单方法是使用Python脚本作为参数调用script本身.代替

The simplest way to do what you want is to call script itself with your Python script as an argument. Instead of

#!/usr/bin/python

import subprocess

subprocess.call(['script', 'logfile'])

# Rest of your Python code

subprocess.call(['exit'])

您将使用

#!/usr/bin/python

import os
import sys

if '_underscript' not in os.environ:
    os.environ['_underscript'] = "yes"
    cmd_args = ['script', 'logfile', 'python'] + sys.argv
    os.execvp('script', cmd_args)

# Rest of your Python code

环境变量可防止您的脚本进入使用script重新运行自身的无限循环.当您运行Python脚本时,它将首先在其环境中检查尚不存在的变量.如果没有,它将设置该变量,然后运行script重新运行Python脚本. execvp用对script的调用替换您的脚本; Python脚本中没有其他内容可以执行.第二次脚本运行时,变量_underscript 确实存在,这意味着if块被跳过,其余脚本按预期运行.

The environment variable prevents your script from entering an infinite loop of re-running itself with script. When you run your Python script, it first checks its environment for a variable that should not yet exist. If it doesn't, it sets that variable, then runs script to re-run the Python script. execvp replaces your script with the call to script; nothing else in the Python script executes. This second time your script runs, the variable _underscript does exist, meaning the if block is skipped and the rest of your script runs as intended.

这篇关于在python中使用bash命令脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 07:06