I am using Ignition v8.1.18. I want to test for the existence of a directory and create it if it doesn't exist. I need to be able to test if the directory creation succeeded so I can notify the user and exit elegantly if it did not. My code succeeds in creating the directory, but when I test for it, the script does not find it. I put in a crude delay, but that has not helped. Here is my code:
import subprocess
import sys
path = "C:\\_Temp\\vlc"
if system.file.fileExists(path):
system.gui.messageBox(path + " exists.", "Exists")
else:
r = system.gui.confirm(path + " does not exist.\r\n\r\nTry to create it?", "Does Not Exist")
if not r:
sys.exit()
cmd = "mkdir"
a1 = path
args = [cmd,a1]
proc = subprocess.Popen(args,shell=True)
print proc
i = 0
while i < 10000:
i+=1
if system.file.fileExists(path):
system.gui.messageBox(path + " successfully created.", "Now Exists")
else:
system.gui.messageBox(path + " creation failed.", "Creation Failed")
When the code executes, the directory will have been created, but I get the messageBox saying that the creation failed. If I execute the script again, it finds the directory. Does anyone have any ideas?
You could skip the middleman and use the java.nio.Files
API instead:
https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/nio/file/Files.html
You'll need an instance of Path to pass into the different methods; something like this:
from java.nio.file import Files, Path
path = Path.of("C:/_Temp/vlc")
Files.exists(path)
The middleman of which you speak, Paul, has been my trusted champion for some 10 years now...but I gave it a shot anyway.
And I suppose I should have mentioned that I am on Winblows.
The following code works a treat:
from java.nio.file import Files, Path
import subprocess
import sys
path = Path.of("C:/_Temp/vlc/")
#print path, str(path)
r = system.gui.confirm("Path returned is:\r\n\r\n" + str(path) + "\r\n\r\nContinue?", "Continue?")
if not r:
sys.exit()
if Files.exists(path):
system.gui.messageBox(str(path) + " exists.", "Exists")
else:
r = system.gui.confirm(str(path) + " does not exist.\r\n\r\nTry to create it?", "Does Not Exist")
if not r:
sys.exit()
# print "Trying to create path"
Files.createDirectories(path)
if Files.exists(path):
system.gui.messageBox(str(path) + " successfully created.", "Now Exists")
else:
system.gui.messageBox(str(path) + " creation failed.", "Creation Failed")
A couple of bumps I ran into, for anyone reading this later, is that my original path of
"C:\\_Temp\\vlc"
did not work for a path because, apparently Path.of() is smart enough to escape its own back slashes, and the back slashes had to be forward slashes.
also
Files.createDirectory(path)
did not work. I figured out that the reason was that I was actually trying to create multiple directories (the parent too), hence the plural,
Files.createDirectories(path)
The code detected the newly created directories on the first try.
Thanks @PGriffith !
3 Likes