Trying to Convert an Absolute .m3u Path to a Relative .m3u Path - python

I am trying to remove absolute path info from my playlist.m3u file(s) and convert this file(s) to a relative path, using Python. I can do this with an Excel script that concatenates and it works great, but I would think the Python route would be easier.
Here is a script I have been trying to get to work, without success.
import sys
import os
infile = sys.argv[1]
basepath = os.path.dirname(os.path.abspath(infile))
outlines = []
fp = open(infile)
for line in fp.readlines():
if line.startswith('#'): # m3u comments start with #
outlines.append(line)
else:
outlines.append(os.path.relpath(line, basepath))
fp.close()
fp = open(infile, "w")
for line in outlines:
fp.write(line)
fp.close()
Here is an example of the absolute path playlist file contents:
J:\NTFS_1\MP3_D\Dan Fogelberg - River of Souls - 08 - A Love Like This.mp3
J:\NTFS_1\MP3_H\Harry Chapin - Verities & Balderdash - 04 - 30,000 Pounds Of Bananas.mp3
Here is the relative path playlist contents from Excel:
\Dan Fogelberg - River of Souls - 08 - A Love Like This.mp3
\Harry Chapin - Verities & Balderdash - 04 - 30,000 Pounds Of Bananas.mp3
I execute the python code with the command line:
c:\temp>playlist.py playlist.m3u > playlistout.m3u
The program does generate an output file playlistout.m3u but it is blank or empty. I have really looked around and posted elsewhere about a solution, without success. I'm exhausted at this point. Anyone? Thanks.

You are calling this with
c:\temp>playlist.py playlist.m3u > playlistout.m3u
which redirects the stdout printed output of playlist.py to playlistout.m3u. However, in your program you aren't printing anything. Your program actually writes back into the original input file in these lines
fp = open(infile, "w")
for line in outlines:
fp.write(line)
fp.close()
The way you're calling this program you would actually want to replace those lines with
for line in outlines:
print(line)
You don't actually need to store the outlines and could rewrite the program to exclude that part but we'll save that for later.
If you want to make sure that you are producing anything in outlines at all you can do:
import sys
print("Number of lines to print: {}".format(len(outlines)), file=sys.stderr)
for line in outlines:
print(line)

This answer talks primarily about script code that sends output to a specific local computer hard drive and folder. There are 2 answers that I have posted here. I am answering my own questions, as the originating poster. I have put in a lot of personal effort researching the question in the original post. Just seems like a lot of things came together, here recently. So, I furnished 2 answers on the same general question. Thanks. Bill M.
My previous answer stands as is and serves the purpose described. The script output location, in the earlier case, was a function of a command line statement variable. I noted this constraint. My preference was to be able to specify, within the python script itself, where the output file should be placed. After additional research, I have cobbled together a couple lines of code that make my needs complete. The product is spartan. Not very elegant. But it works for me. If I could have found a script that performed this directly, I would have used it. Maybe others will find it useful directly or indirectly.
So, in this second answer, to my own question, I have reworked some Stackoverflow code from another topic to allow for stipulating where the converted playlist output is placed.
The original code for handling how to redirect the output of print to a TXT file was found at the link How to redirect the output of print to a TXT file.
One of the responses by Eli Courtwright was ideal for this situation. Here are the pertinent code pieces that I extracted:
log = open("c:\\goat.txt", "w")
print >>log, "test"
Here is how I adapted them and (later) incorporated them for my situation
outfile = open("c:\\temp\goat.m3u", "w")
print >> outfile,('\%s' % (filename))
I changed from:log to:outfile. I modified my earlier print command to now point to outfile, which previously was associated with my preferred local hard drive location. Note the use of the double rear facing slashes.
Finally, here is the complete 9 lines of code required to read an absolute path playlist, then convert and generate a new playlist file for my Android mp3 player application.
# Python Script to extract playlist relative folder path and names
# Script removes local storage absolute path info from playlist records.
import sys
import os
outfile = open("c:\\temp\goat.m3u", "w")
f = open('output.txt','w')
with open('C:/temp/playlist.m3u') as f:
for line in f:
drive, path = os.path.splitdrive(line)
path, filename = os.path.split(path)
# Note the '\' in the print command. Need this because the
# previous operation removes any/all path info. This 1 '\'
# is required to be restored
print >> outfile,('\%s' % (filename))
That's all I have. I'm thinking I can still write a batch file like "convert.bat" where I can drop my original playlist.m3u file and have it execute the python script directly, instead of running it from PyCharm or the Command Line. But that's another day. Merry Christmas.

This answer talks about the script code required to extract the relative path information from the absolute path information that is generally found in a playlist created by a stand alone media center file and database manager. Playlists can then be generated and exported, along with media files, to portable tablets and cellphones within a household.
I am answering my own question, as the originating poster. I have put in a lot of personal effort researching the question in the original post. Just seems like a lot of things came together, here recently. So, I furnished 2 answers on the same general question. Thanks. Bill M.
The below script is a very compact way to convert a playlist with full absolute path information to a playlist with minimal relative path information. I use a popular Android music player, except. It cannot decipher a standard .m3u playlist, when that playlist is created externally And when the playlist includes the full Drive and Folder path information that is generated by my home media center application. Note, other Android mp3 players apps didn't suffer this shortcoming, but they failed to impress me for other reasons. So, I needed a means to remove the absolute path information. Here are the initial conditions and the solution.
I have a file named playlist.m3u. It is plain text. The file contents are:
J:\NTFS_1\MP3_D\Dan Fogelberg - River of Souls - 08 - A Love Like This.mp3
J:\NTFS_1\MP3_H\Harry Chapin - Verities & Balderdash - 04 - 30,000 Pounds Of Bananas.mp3
The above file reords are not recognized by my Android music player, because each line or record contains absolute path information, such as J:\NTFS_1\MP3_D and J:\NTFS_1\MP3_H. The above is only an example and there are additional absolute path folders for MP3_A, MP_B, etc., etc.
If I edit, or otherwise process the above lines either manually or with an Excel formula conversion, this needs to be the opening format of each record:
\Dan Fogelberg - River of Souls - 08 - A Love Like This.mp3
\Harry Chapin - Verities & Balderdash - 04 - 30,000 Pounds Of Bananas.mp3
Here is a verbatim code snippet that I found here on Stackoverflow at the link: (Splitting path strings into drive, path and file name parts):
with open('C:/Users/visc/scratch/scratch_child/test.txt') as f:
for line in f:
drive, path = os.path.splitdrive(line)
path, filename = os.path.split(path)
print('Drive is %s Path is %s and file is %s' % (drive, path, filename))
Here is a reworked version that meets my requirements. I execute this from the DOS command line, so that I can direct the results to an output file, at the command line.
I named this script playlist.py. On the command line I enter:
C:\temp\playlist.py > output.m3u.
Here is playlist.py:
import sys
import os
with open('C:/temp/playlist.m3u') as f:
for line in f:
drive, path = os.path.splitdrive(line)
path, filename = os.path.split(path)
# print('Drive is %s Path is %s and file is %s' % (drive, path, filename))
# The original print adds spaces and such. I removed the not necessary
# Drive and Path fields. Note, I Added a "\"
print('\%s' % (filename))
I tested the above at the command line. It produces an output file populated as required and shown above. I also tested the script in PyCharm Projects Community. PyCharm will produce the print output on screen. This agrees, of course, with the redirect output for the command line > output.m3u
I'm happy to have satisfied my curiosity and have a functional solution to the issue of the original post.
I could still use some help. What additional code will allow me to specify in the python script, where and to what named file I want the output printed to?

Related

OneDrive free up space with Python

I have been using OneDrive to store a large amount of images and now I need to process those, so I have sync'd my OneDrive folder to my computer, which takes relatively no space on disk. However, since I have to open() them in my code, they all get downloaded, which would take much more than the available memory on my computer. I can manually use the Free up space action in the right-click contextual menu, which keeps them sync'd without taking space.
I'm looking for a way to do the same thing but in my code instead, after every image I process.
Trying to find how to get the commands of contextual menu items led me to these two places in the registry:
HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Directory\shell
HKEY_LOCAL_MACHINE\SOFTWARE\Classes*\shellex\ContextMenuHandlers
However I couldn't find anything related to it and those trees have way too many keys to check blindly. Also this forum post (outside link) shows a few ways to free up space automatically, but it seems to affect all files and is limited to full days intervals.
So is there any way to either access that command or to free up the space in python ?
According to this microsoft post it is possible to call Attrib.exe to do that sort of manipulation on files.
This little snippet does the job for a per-file usage. As shown in the linked post, it's also possible to do it on the full contents of a folder using the /s argument, and much more.
import subprocess
def process_image(path):
# Open the file, which downloads it automatically
with open(path, 'r') as img:
print(img)
# Free up space (OneDrive) after usage
subprocess.run('attrib +U -P "' + path + '"')
The download and freeing up space are fairly quick, but in the case of running this heavily in parallel, it is possible that some disk space will be consumed for a short amount of time. In general though, this is pretty instantaneous.
In addition to Mat's answer. If you are working on a Mac then you can replace Attrib.exe with "/Applications/OneDrive.App/Contents/MacOS/OneDrive /unpin" to make the file online only.
import subprocess
path = "/Users/OneDrive/file.png"
subprocess.run(["/Applications/OneDrive.App/Contents/MacOS/OneDrive", "/unpin", path])
Free up space for multiples files.
import os
import subprocess
path = r"C:\Users\yourUser\Folder"
diret = os.listdir(path)
for di in diret:
dir_atual = path + "\\" + di
for root, dirs, files in os.walk(dir_atual):
for file in files:
arquivos = (os.path.join(root, file))
print (arquivos)
subprocess.run('attrib +U -P "' + arquivos + '"')

Iterating through subdirectories to add unique strings to each file

My goal: To build a program that:
Opens a folder (provided by the user) from the user's computer
Iterates through that folder, opening each document in each subdirectory (named according to language codes; "AR," "EN," "ES," etc.)
Substitutes a string in for another string in each document. Crucially, the new string will change with each document (though the old string will not), according to the language code in the folder name.
My level of experience: Minimal; been learning python for a few months but this is the first program I'm building that's not paint-by-numbers. I'm building it to make a process at work faster. I'm sure I'm not building this as efficiently as possible; I've been throwing it together from my own knowledge and from reading stackexchange religiously while building it.
Research I've done on my own: I've been living in stackexchange the past few days, but I haven't found anyone doing quite what I'm doing (which was very surprising to me). I'm not sure if this is just because I lack the vocabulary to search (tried out a lot of search terms, but none of them totally match what I'm doing) or if this is just the wrong way of going about things.
The issue I'm running into:
I'm getting this error:
Traceback (most recent call last):
File "test5.py", line 52, in <module>
for f in os.listdir(src_dir):
OSError: [Errno 20] Not a directory: 'ExploringEduTubingEN(1).txt'
I'm not sure how to iterate through every file in the subdirectories and update a string within each file (not the file names) with a new and unique string. I thought I had it, but this error has totally thrown me off. Prior to this, I was getting an error for the same line that said "Not a file or directory: 'ExploringEduTubingEN(1).txt'" and it's surprising to me that the first error could request a file or a directory, and once I fixed that, it asked for just a directory; seems like it should've just asked for a directory at the beginning.
With no further ado, the code (placing at bottom because it's long to include context):
import os
ex=raw_input("Please provide an example PDF that we'll append a language code to. ")
#Asking for a PDF to which we'll iteratively append the language codes from below.
lst = ['_ar.pdf', '_cs.pdf', '_de.pdf', '_el.pdf', '_en_gb.pdf', '_es.pdf', '_es_419.pdf',
'_fr.pdf', '_id.pdf', '_it.pdf', '_ja.pdf', '_ko.pdf', '_nl.pdf', '_pl.pdf', '_pt_br.pdf', '_pt_pt.pdf', '_ro.pdf', '_ru.pdf',
'_sv.pdf', '_th.pdf', '_tr.pdf', '_vi.pdf', '_zh_tw.pdf', '_vn.pdf', '_zh_cn.pdf']
#list of language code PDF appending strings.
pdf_list=open('pdflist.txt','w+')
#creating a document to put this group of PDF filepaths in.
pdf2='pdflist.txt'
#making this an actual variable.
for word in lst:
pdf_list.write(ex + word + "\n")
#creating a version of the PDF example for every item in the language list, and then appending the language codes.
pdf_list.seek(0)
langlist=pdf_list.readlines()
#creating a list of the PDF paths so that I can use it below.
for i in langlist:
i=i.rstrip("\n")
#removing the line breaks.
pdf_list.close()
#closing the file after removing the line breaks.
file1=raw_input("Please provide the full filepath of the folder you'd like to convert. ")
#the folder provided by the user to iterate through.
folder1=os.listdir(file1)
#creating a list of the files within the folder
pdfpath1="example.pdf"
langfile="example2.pdf"
#setting variables for below
#my thought here is that i'd need to make the variable the initial folder, then make it a list, then iterate through the list.
for ogfile in folder1:
#want to iterate through all the files in the directory, including in subdirectories
src_dir=ogfile.split("/",6)
src_dir="/".join(src_dir[:6])
#goal here is to cut off the language code folder name and then join it again, w/o language code.
for f in os.listdir(src_dir):
f = os.path.join(src_dir, f)
#i admit this got a little convoluted–i'm trying to make sure the files put the right code in, I.E. that the document from the folder ending in "AR" gets the PDF that will now end in "AR"
#the perils of pulling from lots of different questions in stackexchange
with open(ogfile, 'r+') as f:
content = f.read()
f.seek(0)
f.truncate()
for langfile in langlist:
f.write(content.replace(pdfpath1, langfile))
#replacing the placeholder PDF link with the created PDF links from the beginning of the code
If you read this far, thanks. I've tried to provide as much information as possible, especially about my thought process. I'll keep trying things and reading, but I'd love to have more eyes on it.
You have to specify the full path to your directories/files. Use os.path.join to create a valid path to your file or directory (and platform-independent).
For replacing your string, simply modify your example string using the subfolder name. Assuming that ex as the format filename.pdf, you could use: newstring = ex[:-4] + '_' + str.lower(subfolder) + '.pdf'. That way, you do not have to specify the list of replacement strings nor loop through this list.
Solution
To iterate over your directory and replace the content of your files as you'd like, you can do the following:
# Get the name of the file: "example.pdf" (note the .pdf is assumed here)
ex=raw_input("Please provide an example PDF that we'll append a language code to. ")
# Get the folder to go through
folderpath=raw_input("Please provide the full filepath of the folder you'd like to convert. ")
# Get all subfolders and go through them (named: 'AR', 'DE', etc.)
subfolders=os.listdir(folderpath)
for subfolder in subfolders:
# Get the full path to the subfolder
fullsubfolder = os.path.join(folderpath,subfolder)
# If it is a directory, go through it
if os.path.isdir(fullsubfolder):
# Find all files in subdirectory and go through each of them
files = os.listdir(fullsubfolder)
for filename in files:
# Get full path to the file
fullfile = os.path.join(fullsubfolder, filename)
# If it is a file, process it (note: we do not check if it is a text file here)
if os.path.isfile(fullfile):
with open(fullfile, 'r+') as f:
content = f.read()
f.seek(0)
f.truncate()
# Create the replacing string based on the subdirectory name. Ex: 'example_ar.pdf'
newstring = ex[:-4] + '_' + str.lower(subfolder) + '.pdf'
f.write(content.replace(ex, newstring))
Note
Instead of asking the user to find write the folder, you could ask him to open the directory with a dialog box. See this question for more info: Use GUI to open directory in Python 3

Why is my original folder not kept after compression? Why is my compression so slow? - python 3.4

The purpose of this program is to zip a directory or a folder as simply as possible, and write
the generated .tar.gz to one of my USB flash drives (or any other location), plans are to add a
function that will also use 'GnuPG' to encrypt the folder and another
that will allow user to input a time in order to perform this task
daily, weekly, monthly, etc. I also want the user to be able to choose
the destination of the zipped folder. Just wanted to post this up now
to see if it worked on first attempt and to get a bit of feedback.
My main question is why I lose the main folder upon extraction of the compressed files. For example, if I compress "Documents" which contains the two folders "Videos" and "Pictures" and the file "manual.txt". When I extract the file it does not dump "Documents" into the extraction point it dumps "Videos" and "Pictures" and "manual.txt". Which is fine and all, no data loss and everything is still intact, just creates a bit of clutter and I would like to keep the original directory.
Also wondering why in the world is this program taking so long to convert the file and when it does the conversion in some cases the .tar.gz file is just as large as the original folder, this happens with video files, it does seem to compress text files well, and much quicker.
Are video files just hard to compress? Or what, It takes like 5 minutes to process 2gb of video files and then they are the same as the original size? Kinda pointless.
Also would it make sense to use regex to validate user input in this case, I could just use a couple if statements instead no? like the preferred input in this program is 'root' not '/root'. Couldn't I just have it cut the '/' off if the input starts with a '/'.
I mainly want to see if this is the right, most efficient way of doing things, I'd rather not be given the answer in the usual stack overflow copy/paste way, lets get a discussion going.
So why is this program so slow when processing larger amounts of data? I expect a reduction in speed but not by that much
#!/usr/bin/env python3
'''
author: ryan st***
date: 12/5/2015
time: 18:55 Eastern time (GMT -5)
language: python 3.4
'''
# Import, import, import.
import os, subprocess, sys, zipfile, re
import shutil
import time
# Backup (zip) files
def zipDir():
try:
# Get file to be zipped and zip file destination from user
Dir = "~"
str1 = input ('Input directory to be zipped(eg. Douments, Dowloads, Desktop/programs): ')
# an input example that works "bin/mans"
str2 = input ('Zipped output directory (eg. root, myBackups): ')
# an output example that works "bin2/test"
zipName = input ("What would you like to name your zipped folder? ")
path1 = Dir, str1, "/"
path2 = Dir, str2, "/"
# Zip it up
# print (zipFile, ".tar.gz will be created from the folder ", path1[0]+path1[1]+path1[2])
#"and placed into the folder ", path2[0]+path2[1]+path2[2])
zipDirTo = os.path.expanduser(os.path.join(path2[0], path2[1]+path2[2], zipName))
zipDir = os.path.expanduser(os.path.join(path1[0], path1[1]))
print ('Directory "',zipDir,'" will be zipped and saved to the location: "' ,zipDirTo,'.tar.gz"')
shutil.make_archive(zipDirTo, 'gztar', zipDir)
print ("file zipped")
# In Case of mistake
except:
print ("Something went wrong in compression.\n",
"Ending Task, Please try again")
quit()
# Execute the program
def main():
print ("It will be a fucking miracle if this succeeds.")
zipDir()
print ("Success!!!!!!")
time.sleep(2)
quit()
# Wrap it all up
if __name__ == '__main__':
main()
Video files are normally compressed themselves and recompressing them doesn't help.for image and video file use tar only.
My main question is why I lose the main folder upon extraction of the compressed files
Because you're not storing that folder's name in the zip file. The paths you're using don't include Documents, they start with the name of the items inside Documents.
Are video files just hard to compress?
Any file that is already compressed, such as most video and audio formats, will be hard to compress further, and it will take quite a bit of time to find that out if the size is large. You might consider detecting compressed files and storing them in the zip file without further compression using the ZIP_STORED constant.
let[']s get a discussion going.
Stack Overflow's format is not really suited to discussions.

Why am I getting a FileNotFoundError? [duplicate]

This question already has answers here:
open() gives FileNotFoundError / IOError: '[Errno 2] No such file or directory'
(8 answers)
Closed 7 months ago.
I'm trying to write a simple program to read a file and search for a word then print how many times that word is found in the file. Every time I type in "test.rtf" (which is the name of my document) I get this error:
Traceback (most recent call last):
File "/Users/AshleyStallings/Documents/School Work/Computer Programming/Side Projects/How many? (Python).py", line 9, in <module>
fileScan= open(fileName, 'r') #Opens file
FileNotFoundError: [Errno 2] No such file or directory: 'test.rtf'
In class last semester, I remember my professor saying you have to save the file in a specific place? I'm not sure if he really said that though, but I'm running apple OSx if that helps.
Here's the important part of my code:
fileName= input("Please enter the name of the file you'd like to use.")
fileScan= open(fileName, 'r') #Opens file
If the user does not pass the full path to the file (on Unix type systems this means a path that starts with a slash), the path is interpreted relatively to the current working directory. The current working directory usually is the directory in which you started the program. In your case, the file test.rtf must be in the same directory in which you execute the program.
You are obviously performing programming tasks in Python under Mac OS. There, I recommend to work in the terminal (on the command line), i.e. start the terminal, cd to the directory where your input file is located and start the Python script there using the command
$ python script.py
In order to make this work, the directory containing the python executable must be in the PATH, a so-called environment variable that contains directories that are automatically used for searching executables when you enter a command. You should make use of this, because it simplifies daily work greatly. That way, you can simply cd to the directory containing your Python script file and run it.
In any case, if your Python script file and your data input file are not in the same directory, you always have to specify either a relative path between them or you have to use an absolute path for one of them.
Is test.rtf located in the same directory you're in when you run this?
If not, you'll need to provide the full path to that file.
Suppose it's located in
/Users/AshleyStallings/Documents/School Work/Computer Programming/Side Projects/data
In that case you'd enter
data/test.rtf
as your file name
Or it could be in
/Users/AshleyStallings/Documents/School Work/Computer Programming/some_other_folder
In that case you'd enter
../some_other_folder/test.rtf
As noted above the problem is in specifying the path to your file.
The default path in OS X is your home directory (/Users/macbook represented by ~ in terminal ...you can change or rename the home directory with the advanced options in System Preferences > Users & Groups).
Or you can specify the path from the drive to your file in the filename:
path = "/Users/macbook/Documents/MyPython/"
myFile = path + fileName
You can also catch the File Not Found Error and give another response using try:
try:
with open(filename) as f:
sequences = pick_lines(f)
except FileNotFoundError:
print("File not found. Check the path variable and filename")
exit()
A good start would be validating the input. In other words, you can make sure that the user has indeed typed a correct path for a real existing file, like this:
import os
fileName = input("Please enter the name of the file you'd like to use.")
while not os.path.isfile(fileName):
fileName = input("Whoops! No such file! Please enter the name of the file you'd like to use.")
This is with a little help from the built in module os, That is a part of the Standard Python Library.
You might need to change your path by:
import os
path=os.chdir(str('Here_should_be_the_path_to_your_file')) #This command changes directory
This is what worked for me at least! Hope it works for you too!
Difficult to give code examples in the comments.
To read the words in the file, you can read the contents of the file, which gets you a string - this is what you were doing before, with the read() method - and then use split() to get the individual words.
Split breaks up a String on the delimiter provided, or on whitespace by default. For example,
"the quick brown fox".split()
produces
['the', 'quick', 'brown', 'fox']
Similarly,
fileScan.read().split()
will give you an array of Strings.
Hope that helps!
First check what's your file format(e.g: .txt, .json, .csv etc ),
If your file present in PWD , then just give the name of the file along with the file format inside either single('')or double("") quote and the appropriate operation mode as your requirement
e.g:
with open('test.txt','r') as f: data=f.readlines() for i in data: print(i)
If your file present in other directory, then just give the full path name where is your file is present and file name along with file format of the file inside either single('')or double("") quote and the appropriate operation mode as your requirement.
If it showing unicode error just put either r before quote of file path or else put '/' instead of ''
with open(r'C:\Users\soman\Desktop\test.txt','r') as f: data=f.readlines() for i in data: print(i)
The mistake I did was
my code :
x = open('python.txt')
print(x)
But the problem was in file directory ,I saved it as python.txt instead of just python .
So my file path was
->C:\Users\noob\Desktop\Python\Course 2\python.txt.txt
That is why it was giving a error.
Name your file without .txt it will run.

In Paraview, how to change the datafile filename of the state to create a snapshot from a given datafile and state?

I am currently able to visualize correctly in ParaView a .vtp file for each time step of a simulation, and to print a screenshot for each. I want to do that in batch, but I want to keep the same state for each one (view point, filters applied, etc). I have already saved the state into a .psvm file , and I tried to write a python script which, after being run by pvbatch, will (hopefully) print the screenshots. But, unfortunately, it is not working. I tried to change the filename in the state by processing the state file and doing a search and replace, but still it is not working. For instance, it keeps plotting the first data input only, even if the current file is different (altough GetSources() shows an always increasing list of sources). I use ParaView 3.14.0 in Snow Leopard. I am sure this is easy, but I am overwhelmed with the large amount of info about python and paraview with no reference to this particularissue. Please, please, any advice is greatly welcome, and I am sorry if this has been answered previously (I looked at google, the paraview mailing list, and here). Below is my script, which can also be found at http://pastebin.com/4xiLNrS0 . Furthermore, you can find some example files and state in http://goo.gl/XjPpE .
#!/bin/python
import glob, string, os, commands
from paraview.simple import *
#help(servermanager)
# vtp files are inside the local subdir DISPLAY
files = (commands.getoutput("ls DISPLAY/data-*.vtp | grep -v contacts")).split()
# process each file
for filename in files:
fullfn = commands.getoutput("ls $PWD/" + filename)
fn = filename.replace('DISPLAY/', '')
#os.system("cp ../dem_git/addons/paraview_state.pvsm tmp.pvsm")
os.system("cp ~/Desktop/state.pvsm tmp.pvsm")
os.system("sed -i.bck 's/DATA.vtp/" + fullfn.replace('/','\/') + "/1' tmp.pvsm") # replace first intance with full path
os.system("sed -i.bck 's/DATA.vtp/" + fullfn.replace('/','\/') + "/1' tmp.pvsm") # replace second intance with full path
os.system("sed -i.bck 's/DATA.vtp/" + fn + "/1' tmp.pvsm") # replace third with just the filename path
servermanager.LoadState("tmp.pvsm")
pm = servermanager.ProxyManager()
reader = pm.GetProxy('sources', fullfn)
reader.FileName = fullfn
reader.FileNameChanged()
reader.UpdatePipeline()
view = servermanager.GetRenderView()
SetActiveView(view)
view.StillRender()
WriteImage(filename.replace(".vtp", ".png"))
os.system("rm -f tmp.pvsm")
os.system("rm -f tmp.pvsm.bck")
Delete(reader)
I realise this is an old question, but I had exactly the same problem recently and couldn't find any answers either. All you need to do is add Delete(view) after Delete(reader) for your script to work.

Categories