【发布时间】:2017-02-21 02:50:26
【问题描述】:
我有一个循环遍历文件夹的 Python 脚本,为每个文件创建一个 shell 命令。
每个命令都写入一个 shell 脚本,然后使用 subprocess.Popen 运行该脚本。 (我需要这样做,因为我还需要先设置环境才能使命令起作用)。
这是一些伪代码:
def create_shell_script(self):
'''loop through a folder, create a command for each file and write this to a shell script'''
# command to run
base_command="run this"
#list of files
command_list=[]
#loop through the files to create a folder
for file in my_folder:
command_list.append(base_command+" "+file)
# open the shell script
scriptname="shell.sh"
shellscript = open(scriptname,'w')
# set the environment using '.' as using bash below to run shell script
shellscript.write("#!/bin/bash\n. /etc/profile.d/set_environment\n")
#loop through commands and write to shellscript
for command in command_list:
shellscript.write(command+"\n")
# use subprocess to run the shell script. Use bash to interpret the environment
cmd="bash "+scriptname
proc = subprocess.Popen([cmd], stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
当我运行这个 python 脚本时,只执行 shell 脚本中的前 6 个命令。该命令的错误消息表明该命令在被子进程读取时被截断。
当我手动运行 shell 脚本时,所有命令都按预期执行,所以我知道 shell 脚本是正确的。
每个命令都是即时的,但我无法想象速度会导致问题。
我确实尝试为每个文件运行一个子进程命令,但我在设置环境时遇到了困难,我喜欢创建单个 sh 脚本的方法,因为它也可以用作日志文件。
我已阅读子流程文档,但没有发现任何内容,谷歌也没有提供帮助。
【问题讨论】:
-
您是否尝试在写入文件后和运行前关闭 shellscript 文件对象?否则执行时文件可能不会完全写入。
-
解决了!谢谢。如果您将其添加为答案,我会将其标记为已接受
标签: linux bash python-2.7 subprocess