python批量执行linux命令并写入log日志

linux下使用python运行make命令并把日志有错的路径写入.log日志中

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import subprocess
import sys
import os
import time
import glob
# 所有可执行文件
# rootdir = '/home/test/'
rootdir = raw_input("可执行文件根目录:")
errorDir = '/home/'
paths = []
errorPaths = []
# 开始方法
def runPath(index):
    # 进入目录
    cd = "cd %s;" %paths[index]
    # 执行的命令行命令
    cmd = "%s make" %cd
    # 执行命令并返回执行
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    # 循环输出执行行
    for line in p.stdout.readlines():
        print line
    # 执行结果
    retval = p.wait()
    print "执行结果:", retval
    # 文件下所有df文件
    df_list = glob.glob(paths[index] + "/*.df")
    for df_item in df_list:
        retval = os.path.getsize(df_item)
        print "文件路径:%s 执行结果:%s" %(df_item,retval)
        # 文件下所有df文件大小
        if retval > 0:
            errorPaths.append(paths[index])
            break

def run_1():
    # 从第一个开始循环
    print "----所有文件-------\n"
    count = 0
    while count < len(paths):
        print "-------------------------\n"
        # 执行方法
        runPath(count)
        count += 1
    # 打印输出日志
    printError()

def run_2():
    # 从第一个开始循环
    count = 0
    print "-------------------------\n"
    print "-1. 退出"
    while count < len(paths):
        # 执行方法
        print count,". ",paths[count],'\n'
        count += 1
    runLang = int(raw_input("请输入要执行的文件:"))
    if runLang >= 0:
        runPath(runLang)
        # 打印输出日志
        printError()
    else:
        close()

def run_3():
    global errorDir
    errorDir = raw_input("请输入要存放的位置:")
    print "修改成功!"

# 结束
def close():
    print "再见"
    sys.exit()

# 开始
def play():
    # 初始化错误
    global errorPaths
    errorPaths = []
    print "---------- 欢迎进入执行系统 ---------------"
    print "1. 执行所有文件\n2. 执行指定文件\n3. 修改log日志默认位置\n0. 退出"
    runLang = raw_input("请输入:")
    switch = {
        '1': run_1,
        '2': run_2,
        '3': run_3,
        '0': close
    }
    switch.get(runLang)()
    play()

# 写日志
def printError():
    print "%s,type:%s" %(errorDir,type(errorDir))
    datestr = time.strftime("%Y-%m-%d%H%M%S",time.gmtime())
    errlogpath = errorDir + datestr + "error.log"
    print errlogpath
    # errlogpath = "/home/zhangluhang/2021-0409110904error.log"
    f = open(errlogpath,'w+')
    for path in errorPaths:
        f.write("%s\r\n" % path)
    try:
        print 0
    except IOError:
        print "文件写异常"
    else:
        f.close()

# 执行获取路径
def root_paths():
    for root,dirs,files in os.walk(rootdir):
        # print dirs
        for dir in dirs:
            # 获取文件所属目录
            filePath = os.path.join(root,dir)
            paths.append(filePath)
    # 开始程序
    play()

root_paths()

<think>嗯,用户之前问过Python创建文件的方法,现在又特别询问Linux环境下Python创建文件的情况。我需要考虑用户可能的实际需求和遇到的问题。 首先,用户可能已经在Windows或其他系统上使用过Python创建文件,现在切换到Linux环境,想了解有没有不同之处。或者他们在Linux上遇到了权限、路径等问题,需要针对性的解答。 之前的回答已经涵盖了Python创建文件的几种模式,但Linux下的文件权限、路径处理可能更复杂。用户可能关心如何正确处理文件权限,比如执行权限的问题,或者路径中的符号链接。另外,Linux对大小写敏感,可能需要提醒用户注意文件名的大小写。 还要考虑用户是否需要高级功能,比如创建临时文件、处理二进制文件,或者批量创建文件。另外,Linux下的隐藏文件以点开头,可能需要特别提醒。 用户可能是在部署Python应用到Linux服务器时遇到问题,比如权限不足导致的创建失败,或者路径不存在。需要给出解决方案,比如使用os.makedirs创建目录,或者修改权限的命令。 还有,编码问题在Linux下可能更常见,特别是使用UTF-8的情况,要确保用户在创建文件时指定正确的编码,避免乱码。 总结一下,回答需要涵盖基本创建方法,但重点突出Linux下的注意事项,如权限、路径处理、编码、隐藏文件等,提供常见问题的解决方法。可能还需要补充使用pathlib库的例子,因为它在处理路径时更直观,适合跨平台。</think>以下是在Linux环境下使用Python创建文件的详细指南,包含基础操作、系统特性适配及常见问题解决方案: --- ### 一、基础创建方法 #### 1. 标准文件操作 ```python # 写入模式(覆盖/新建) with open("/var/log/myapp.log", "w") as f: f.write("日志初始化\n") # 追加模式(日志记录推荐) with open("~/data.log", "a") as f: # ~会自动扩展为家目录 f.write(f"{datetime.now()} 新事件\n") ``` #### 2. 安全创建(防覆盖) ```python import os filepath = "critical_data.db" if not os.path.exists(filepath): with open(filepath, "x") as f: f.write("初始数据") else: print("错误:文件已存在!") ``` --- ### 二、Linux特有注意事项 #### 1. 权限管理 ```python # 创建后设置权限 (rw-r--r--) with open("config.cfg", "w") as f: f.write("配置内容") os.chmod("config.cfg", 0o644) # 八进制格式权限 # 创建可执行文件 with open("script.sh", "w") as f: f.write("#!/bin/bash\necho 'Hello Linux'") os.chmod("script.sh", 0o755) # 添加执行权限 ``` #### 2. 路径处理规范 ```python from pathlib import Path # 自动处理家目录和符号链接 log_dir = Path("~/symlink_dir").expanduser().resolve() # 解析真实路径 log_dir.mkdir(parents=True, exist_ok=True) # 递归创建目录 (log_dir / "app.log").touch() # 创建空文件 ``` --- ### 三、高级场景实现 #### 1. 创建系统日志文件 ```python import syslog # 通过syslog接口创建日志 syslog.openlog(ident="MyApp", facility=syslog.LOG_LOCAL2) syslog.syslog(syslog.LOG_INFO, "应用程序启动") # 日志自动写入/var/log/ ``` #### 2. inotify监控文件创建 ```python from pyinotify import WatchManager, Notifier, ProcessEvent class FileCreateHandler(ProcessEvent): def process_IN_CREATE(self, event): print(f"检测到新文件:{event.pathname}") wm = WatchManager() mask = pyinotify.IN_CREATE # 监控创建事件 wm.add_watch('/tmp', mask) # 监控/tmp目录 notifier = Notifier(wm, FileCreateHandler()) notifier.loop() ``` --- ### 四、常见问题排查 #### 1. 权限错误解决方案 ```bash # 终端授权(示例) sudo chmod 777 /target_dir # 开放权限(生产环境慎用) sudo chown $USER:$USER /target_dir # 修改所有者 ``` #### 2. 特殊目录处理 ```python # 在需要root权限的目录创建文件 import subprocess subprocess.run(['sudo', 'touch', '/etc/myapp.conf']) # 通过sudo提权 ``` #### 3. 文件锁定机制 ```python import fcntl with open("shared.log", "a") as f: fcntl.flock(f, fcntl.LOCK_EX) # 获取排他锁 f.write("线程安全写入\n") fcntl.flock(f, fcntl.LOCK_UN) # 释放锁 ``` --- ### 五、性能优化建议 1. **批量写入**:累计数据后集中写入 ```python buffer = [] for i in range(1000): buffer.append(f"记录{i}") with open("bigfile.log", "w") as f: f.write("\n".join(buffer)) ``` 2. **异步写入**(Python 3.7+) ```python import aiofiles async def async_write(): async with aiofiles.open('async.log', 'w') as f: await f.write('异步写入内容') ``` --- ### 六、推荐工具 1. **logrotate集成**:自动处理日志轮转 2. **systemd服务文件**:规范服务类应用的文件创建位置 3. **SELinux上下文设置**(针对安全敏感场景): ```bash chcon -t httpd_sys_content_t /var/www/html/new_file.html ``` 通过合理运用Linux的文件系统特性结合Python的跨平台能力,可以实现安全高效的自动化文件管理。建议重点注意权限控制、路径解析和日志轮转机制,在涉及系统关键目录操作时优先使用Python标准库而非直接执行shell命令
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值