I have a QFilesystemModel used in a QTreeView. Every time I remove a folder (e.g. through shutils.rmtree()) which is watched by the underlying QFilesystemWatcher I get a this warning
QInotifyFileSystemWatcherEngine::addPaths: inotify_add_watch failed: Datei oder Verzeichnis nicht gefunden
QFileSystemWatcher: failed to add paths: /path/to/deleted/folder
In my mind this should be solved by removing the folder from QFileSystemWatcher before removing it with QFileSystemWatcher.removePath(). But this doesn't work as there seem to be no way to get in touch with the QFileSystemWatcher from a QFileSystemModel (I searched for a solution without luck).
So is there any other way I can tell the QFileSystemModel to stop watching the folder?
PS: I know I could use QFileSystemModel.remove() or .rmdir() which would handle this automaticaly. But that's not an option for me. I need to remove the folder from outside the QFileSystemModel.
I'm using Qt4 with Python3 on Linux.
Firstly, QFileSystemModel and QFileSystemWatcher are two different classes. They are not related in any way what-so-ever. QFileSystemModel does not do the watching, you should add the file watcher yourself.
By the way, do realize the QFileSystemModel::remove just deletes the file. You'll still get the error.
The QFileSystemWatcher is buried very deep beneath the code for QFileSystemModel which is why you cannot access it.
Edit:
However, there is a simple way as to how you can avoid the warning. Here is a code snippet. We are assuming that there is a folder called /tmp/trial with some files in it. This is the folder being viewed, and is deleted externally.
### == Code that creates a warning == ###
# Initial state
fsm = QFileSystemModel()
lv = QListView()
lv.setRootIndex( fsm.setRootPath( "/tmp/trial" ) )
# External deletion of "/tmp/trial", leads to this error
shutils.rmtree( "/tmp/trial" )
# Error
QInotifyFileSystemWatcherEngine::addPaths: inotify_add_watch failed: file or directory not found
QFileSystemWatcher: failed to add paths: /tmp/trial
### == Suggested edit == ###
# Initial state
fsm = QFileSystemModel()
lv = QListView()
lv.setRootIndex( fsm.setRootPath( "/tmp/trial" ) )
# Just before deleting
lv.setRootIndex( fsm.setRootPath( "/tmp" ) )
# External deletion of "/tmp/trial", gives no error
# This even look very neat for the user.
shutils.rmtree( "/tmp/trial" )
For the sake of simplicity, I have skipped the proxy model and used a list view, but the procedure be the same in your case with proxy model and tree view.
Related
I have this weird problem. I was able to get here() to work but it stopped working and I can't figure out how to fix it.
So basically the structure of my file is like:
C:/First/Second/Third/Analysis/Scripts
C:/First/Second/Third/Analysis/Data
I want to easily bounce between data and scripts in the code
If I type here("C:/First/")
and then follow up with here(), R says that I'm at
C:/First/Documents
I'm not able to type here("Second", "Third", "Analysis", "Data", "todayscode.R")
because it puts me in the folder:
C:/First/Documents/Second/Third/Analysis/Data/
Which obviously does not exist.
It's unclear why you say that C:/First/Documents/Second/Third/Analysis/Data/ "does not exist". You will need to create a subdirectory if it doesn't exist, but at the beginning of your problem presentation you implied that was an existing directory.
Sounds like you want something like this possibilities:
setwd("C:/First/Second/Third/Analysis/")
You should first clarify where your version of the here function is coming from by typing here at the console input line and noting which namespace it comes from. If you then wanted to refer to a directory with that starting point you could use this (using the example set up in the here package at the here help page):
library(here); library(readr)
readr::read_csv(
here("data", "penguins.csv"),
col_types = list(.default = readr::col_guess()),
n_max = 3
)
I am working locally out of a folder on my desktop and I recently decided to organize the outputs of my script into separate folders at the top of my script:
dir.create(file.path("analysis/plots"), showWarnings = FALSE, recursive = TRUE)
dir.create(file.path("analysis/tables"), showWarnings = FALSE, recursive = TRUE)
When I save to analysis/tables, I get absolutely no error whatsoever:
for (i in 1:2) {
if (i == 1) {
write.csv(twas_z_amyg_threshold, file = "analysis/tables/amygdala_twas_significant_genes_zscore.csv")
} else {
write.csv(twas_z_sacc_threshold, file = "analysis/tables/sacc_twas_significant_genes_zscore.csv")
}
}
However, a bit further down, when I try to save an interactive plot, it gives me the following error:
for (i in 1:2) {
...
saveWidget(fin_plot[[i]],
paste0(
"analysis/plots/","BIP_TWAS_",
ifelse(i == 1, "Amygdala", "sACC"),
"_ManhattanPlotly.html"
))
}
Error in normalizePath(path.expand(path), winslash, mustWork) :
path[1]="analysis/plots": The system cannot find the path specified
I am able to see into this path from my wd:
> getwd()
[1] "C:/Users/*****/Desktop/twas_plots"
> dir()
[1] "analysis" "generate_twas_plots.R" "rda"
> dir("analysis/")
[1] "plots" "tables"
> dir("analysis/plots")
[1] "BIP_TWAS_Amygdala_ManhattanPlotly_files" "BIP_TWAS_ManhattanPlot.pdf"
In fact, before this point in the script, I was even able to successfully save a static plot to that path, BIP_TWAS_ManhattanPlot.pdf, as you can see above.
I have absolutely no problem saving into my current wd using the saveWidget() function, which is what I had been doing before I decided to organize my outputs.
I've heard it's good practice to wrap your paths with file.path(), something I need to get into the habit of doing considering that I work back and forth between my local desktop and the cluster. This does not fix the problem, nor does changing / to \\.
If I right-click on the folder and go to Properties, I see that Read-Only is checked for both the base as well as the analysis and plots directories. If I uncheck it and apply, and then later re-open Properties, I find that it's checked again.
Any suggestions? I could always save to my present directory and then later move it, but I just want to know what this problem is.
You must take into account the scope of the source folder to save a file, every time you want to navigate between different directories you must use the following command:
setwd(_PATH_)
I've been having difficulty getting boxr to successfully create a file within my box directory. My code reads:
library(boxr)
box_auth()
my_file_dir <- box_setwd("76009318507")
box_dir_create(dir_name="TEST", parent_dir_id = my_file_dir)
after running which, I get the following output:
box.com remote folder reference
name :
dir id :
size :
modified at :
created at :
uploaded by :
owned by :
shared link : None
parent folder name :
parent folder id :
Checking my box directory, I find no folders have been created.
I've tried using additional arguments within box_dir_create, but according to the documentation only dir_name and parent_dir_name are accepted.
Any help is much appreciated. I understand this is a somewhat obscure R package, so I've included links to the documentation below:
https://cran.r-project.org/web/packages/boxr/boxr.pdf
https://github.com/r-box/boxr
I got an answer via the package's developer, and I figured I'd pay it forward for any fellow travelers in the future.
It turns out that box_setwd() sets a default directory but returns nothing. Using
box_dir_create(dir_name="TEST", parent_dir_id = "76009318507")
creates the folder successfully. It will not do so if a folder of the same name is already created.
After more digging, I was also told that box_dir_create() is quietly passing back a lot of useful information, including the newly created directory's ID. To access it you can save the function results as a variable, like so:
b <- box_dir_create("test_dir")
names(b) # lots of info
b$id # what you want
box_ul(b$id, "image_file.jpg") # is this file by file?
box_push(b$id, "image_directory/") # or a directory wide operation?
Thanks for your help, and I hope this helps someone else down the road. Cheers!
Super big newbie to R. I'm a bit stuck on the file.create function. I've used it successfully to create a file in the set working directory and also when I've already created a separate file path and assigned that file path to a variable.
However, why can't I use file.create and simply list the desired file path and file name without the file.path function? Does the file.create function not possess the capacity to automatically create the file in the specified directory, but requires the file.path function to secure the path to the directory?
Any clarification would be greatly appreciated. I do apologize if this question is rather elementary but I'd like to get the fundamentals down.
Here's the code that worked:
BasicDir <- "/Users/slam1924/Desktop/LearnR Tutorials"
setwd(BasicDir)
file.create("myfile.doc")
fp1 <- file.path("/Users/slam1924/Desktop/Vocal Covers", "mytext.doc")
fp1
file.create(fp1)
Alternative:
file.create(file.path("/Users/slam1924/Desktop/Vocal Covers", "mytext.doc"))
Here's the code that failed:
file.create("/Users/slam1924/Desktop/Vocal Covers", "mytext.doc")
Start by reading the help for the function. help(file.create). The usage is file.create(..., showWarnings = TRUE)
Under Details you'll see
file.create creates files with the given names if they do not already
exist and truncates them if they do.
So when you try
file.create("/Users/slam1924/Desktop/Vocal Covers", "mytext.doc")
It's trying to create two files, one of which ("/Users/slam1924/Desktop/Vocal Covers") is likely already a directory.
If the file or directory already exists, you'll see an error like:
[1] FALSE
Warning message:
In file.create("data") :
cannot create file 'data', reason 'Permission denied'
You could fix this by sending the function one string. Change your code that failed to:
file.create("/Users/slam1924/Desktop/Vocal Covers/mytext.doc")
Question: How to free all file handlers / connections R is using ? In Python, one could have a look which objects are still alive. Is there anything comparable in R?
Within a function, I create a directory with some files. At the end of the function, it should be deleted again. I am facing the problem that I am unable to delete the files, presumably because a file handler is still open. The example is with the MetaSKAT package, but I'm interested in a general solution. The example data can be found here: https://groups.google.com/group/skat_slee/attach/28a76339619d8358/Datasets.zip?part=4&authuser=0
# Code author: Seunggeun (Shawn) Lee
setwd('./Datasets')
foo <- function(dir.name) {
###### Preparation stuff ################################################
if (!require(MetaSKAT)) {install.packages('MetaSKAT'); require(MetaSKAT)}
dir.create(file.path('.',dir.name),showWarnings=F)
dir.path <- paste("./",dir.name,sep="")
file.copy(c("01.fam","01.bed", "01.bim", "01_3.SetID"), dir.path)
setwd(dir.path)
FAM<-read.table("01.fam", header=FALSE)
y<-FAM[,6]
N.Sample<-length(y)
x1<-rnorm(N.Sample)
x2<-rbinom(N.Sample,1, 0.5)
obj <-SKAT_Null_Model(y~cbind(x1, x2))
re <-Generate_Meta_Files(obj, "01.bed", "01.bim", "01_3.SetID", "01.MSSD", "01.MInfo", N.Sample)
###### Problem #######################################################
print(file.remove(list.files(), force = T)) # problem: cannot delete
# curiously, sometimes there is 1, sometimes 2 False...
###### my different tries to solve it ################################
rm(re)
closeAllConnections()
sink.number() # shows 0
rm(list = ls())
gc()
###### problem is still there ######################################
print(file.remove(list.files()))
setwd('..')
# print(unlink(dir.path, recursive = T)) # I want finally delete the directory
}
debug(foo)
foo("temp2")
I am using R Studio. Even if a try to delete it manually in Windows while R is still open, it tells me that the file is be used by a program. I can only delete it after I closed R.
So how can I force R to free these files? I will try to solve the problem at the root and look at the source code of Generate_Meta_Files(), but I thought there must be a global function in R which forces to free everything (Note: I am well aware that it does not make sense to create the files and delete it directly afterwards, it's just an example.)
Edit: After a hint, I tried it under Linux. It turns out that though it shows me that there was a problem with deletion of one (of the 6) files, all is properly deleted, hence I guess this is a windows-specific problem. Any hints what this is?