TypeError: 强制转换为Unicode时,需要字符串或缓冲区,文件被找到,创建shell脚本时

0 投票
1 回答
2547 浏览
提问于 2025-04-18 20:12

我正在创建一个Python脚本,目的是把一个大的.sh文件分割成多个小的.sh文件,然后把每个小的.sh文件放到一个新的屏幕中去执行。我尝试了这个代码

import os

splitLen = 2         # 2 lines per file
outputBase = 'US11_'
# This is shorthand and not friendly with memory
# on very large files (Sean Cavanagh), but it works.
input = open('US11.sh', 'r').read().split('\n')
at = 1
for lines in range(0, len(input), splitLen):
    # First, get the list slice
    outputData = input[lines:lines+splitLen]

    # Now open the output file, join the new slice with newlines
    # and write it out. Then close the file.
    output = open(outputBase + str(at) + '.sh', 'w')
    output.write('#!/bin/sh\n')
    output.write('\n'.join(outputData))
    output.write('\n')
    output.close()
    os.chmod('{}'.format(output), 0o777)
    os.system("screen -m -d bash -c ./" + output)    
    # Increment the counter
    at += 1

但是在执行这个Python文件时,出现了这个错误

TypeError: coercing to Unicode: need string or buffer, file found

现在这个过程应该是把分割出来的行写入到.sh文件中,然后给这个.sh文件设置权限,再把它放到一个屏幕中去执行。完成这些后,对所有文件进行同样的处理。

我的代码中有什么错误吗?有没有什么想法?

1 个回答

1

os.chmod() 这个函数需要一个文件名,但你现在传入的是文件对象。

你可以在这里使用 output.name

os.chmod(output.name, 0o777)
os.system("screen -m -d bash -c ./" + output.name)    

或者你可以先把生成的文件名存储在一个变量里:

filename = '{0}{1}.sh'.format(outputBase, at)
with open(filename, 'w') as output:
    output.write('#!/bin/sh\n')
    output.write('\n'.join(outputData))
    output.write('\n')
os.chmod(filename, 0o777)
os.system("screen -m -d bash -c ./{0}".format(filename))    

我在这里也把文件对象当作上下文管理器使用;这样用 with 语句的话,当代码块结束时,文件会自动关闭。

撰写回答