Nim check if file exists - nim-lang

How to check if a file exists in Nim?
A simple question that might be too long to look for in the official documentation!
I wish someone would have asked that question here.

import os
import std/strformat
if fileExists(path):
echo &"path {path} exists!"

Related

Is there a better/more pythonic way to load an arbitrary set of functions from modules in another folder?

I'm just basically asking:
if it's considered OK to use exec() in this context
if there's a better/more pythonic solution
for any input or comments on how my code could be improved
First, some context. I have main.py which basically takes input and checks to see if I've written a command. Let's say I type '/help'. The slash just tells it my input was supposed to be a command, so then it checks if a function called 'help' exists, and if so, that function will be run.
To keep things tidy in main.py, and to allow myself to add more commands easily, I have a 'commands' directory, with individual command files in it, such as help.py. help.py would look like this for example:
def help():
print("You've been helped")
So then of course, I need to import help() from help.py, which was trivial.
As I added more commands, I decided to add an init.py file where I'd keep all the command import lines of code, and then just do 'from init import *' in main.py. At first, each time I added a command, I'd add another line in init.py to import it. But that wasn't as flexible as I wanted, so I thought, there's got to be a way to just loop through all the .py files in my commands directory and import them. I struggled with this for a while but came up with a solution that works.
In the init.py snippet below, I loop through the commands directory (and a couple others, but they're irrelevant to the question), and you'll see I use the dreaded exec() function to actually import the commands.
loaded, failed = '', ''
for directory in command_directories:
command_list = os.listdir(directory)
command_list.sort()
for command_file in command_list:
if command_file.endswith(".py"):
command_name = command_file.split(".")[0]
try:
# Evil exec() hack to use variable-name directories/modules
# Haven't found a more... pythonic... way to do this
exec(f"from {directory}.{command_name} import {command_name}")
loaded = loaded + f" - Loaded: {command_name}\n"
except:
failed = failed + f" - Failed to load: {command_name}\n"
if debug == True:
for init_debug in [loaded, failed]: print(init_debug)
I use exec() because I don't know a better way to make a variable with the name of the function being loaded, so I use {command_name} in my exec string to arbitrarily evaluate the variable name that will store the function I'm importing. And... well, it works. The functions work perfectly when called from main.py, so I believe they are being imported in the correct namespace.
Obviously, exec() can be dangerous, but I'm not taking any user input into it, just file names. Filenames that I only I am creating. This program isn't being distributed, but if it was, then I believe using exec() would be bad since there's potential someone could exploit it.
If I'm wrong about something, I'd love to hear about it and get suggestions for a better implementation. Python has been very easy to pick up for me, but I'm probably missing some of the fundamentals.
I should note, I'm running python 3.10 on replit (until I move this project to another host).

Ubuntu: Python3 check if file exists with subprocess

I managed to install windows based network printer with python3 on ubuntu.
For better coding, I want to check first if the file with the drivers in it exists after the download. I know it is possible with os.path.isfile or something like that but I would like to do that with subprocess although os will not be supported in the future anymore.
So how do I do it? With subprocess.call or something like that?
to check for a file to be present, You ideally use pathlib, which is the pythonic and portable way to interact with the filesystem.
But to avoid Time of Check to Time of Use Errors (TOCTTOU) You should consider:
Instead of :
if check_printer_present():
# now, after checking the printer is present,
# the printer might go offline
use_printer()
better use:
try:
use_printer()
except PrinterError():
printer_error_cleanup()
see:
https://de.wikipedia.org/wiki/Time-of-Check-to-Time-of-Use-Problem
You might remember that idiom as :
it's better to ask forgiveness than permission
(t is better to act decisively and apologize for it later
than to seek approval to act and risk delay, objections, etc.)

how to caput the id of a case in bonitsoft

Good morning the reason of my question is about how to capture the id of the case in pretty soft I am using a form 6.x when looking for information on how to perform the procedure I do not find information easy to understand I am new used the program if someone knows how you can perform the process or where you can find information about the topic so you can start programming because you do not know where to start. I am used groovy editor
only found that can be done through processDefinitionId, but I can not find documentation
def process = apiAccessor .getProcessAPI().getProcessInstance(processInstanceId);
return process.id.toString();

How to detect oncomplete function when using readline module in node.js?

I am trying to read files 1 line at a time using this doc
https://nodejs.org/api/readline.html
from the answer here
Read a file one line at a time in node.js?
proposed by Dan.
The problem is, it doesn't specify how to call a function when the file is fully read from.
Does anyone know?
Thanks
In the comments of Dan's answer, someone gives the answer to your question:
lineReader.on('close', callback);

Runtime error R6034 in embedded Python application

I am working on an application which uses Boost.Python to embed the Python interpreter. This is used to run user-generated "scripts" which interact with the main program.
Unfortunately, one user is reporting runtime error R6034 when he tries to run a script. The main program starts up fine, but I think the problem may be occurring when python27.dll is loaded.
I am using Visual Studio 2005, Python 2.7, and Boost.Python 1.46.1. The problem occurs only on one user's machine. I've dealt with manifest issues before, and managed to resolve them, but in this case I'm at a bit of a loss.
Has anyone else run into a similar problem? Were you able to solve it? How?
The problem was caused by third-party software that had added itself to the path and installed msvcr90.dll in its program folder. In this case, the problem was caused by Intel's iCLS Client.
Here's how to find the problem in similar situations:
Download Process Explorer here.
Start your application and reproduce runtime error R6034.
Start Process Explorer. In the "View" menu go to "Lower Pane View" and choose "DLLs".
In the top pane, locate your application and click on it. The bottom pane should show a list of DLLS loaded for your application.
Locate "msvcr??.dll" in the list. There should be several. Look for the one that is not in the "winsxs" folder, and make a note of it.
Now, check the path just before your application runs. If it includes the folder you noted in step 5, you've probably found the culprit.
How to fix the problem? You'll have to remove the offending entry from the path before running your program. In my case, I don't need anything else in the path, so I wrote a simple batch file that looks like this:
path=
myprogram.exe
That's it. The batch file simply clears the path before my program runs, so that the conflicting runtime DLL is not found.
This post elaborates on #Micheal Cooper and #frmdstryr and gives a better alternative than my earlier answer.
You can put the following in front of a python script to purge the problematic entries.
import os, re
path = os.environ['PATH'].split(';')
def is_problem(folder):
try:
for item in os.listdir(folder):
if re.match(r'msvcr\d\d\.dll', item):
return True
except:
pass
return False
path = [folder for folder in path if not is_problem(folder)]
os.environ['PATH'] = ';'.join(path)
For the vim with YouCompleteMe case, you can put the following at the top of your vimrc:
python << EOF
import os, re
path = os.environ['PATH'].split(';')
def is_problem(folder):
try:
for item in os.listdir(folder):
if re.match(r'msvcr\d\d\.dll', item):
return True
except:
pass
return False
path = [folder for folder in path if not is_problem(folder)]
os.environ['PATH'] = ';'.join(path)
EOF
A more general solution is:
import os
os.environ['path'] = ";".join(
[path for path in os.environ['path'].split(";")
if "msvcr90.dll" not in map((lambda x:x.lower()), os.listdir(path))])
(I had the same problem with VanDyke SecureCRT)
(This might be better as a comment than a full answer, but my dusty SO acct. doesn't yet have enough rep for that.)
Like the OP I was also using an embedded Python 2.7 and some other native assemblies.
Complicating this nicely was the fact that my application was a med-large .Net solution running on top of 64-Bit IIS Express (VS2013).
I tried Dependency Walker (great program, but too out of date to help with this), and Process Monitor (ProcMon -- which probably did find some hints, but even though I was using filters the problems were buried in thousands of unrelated operations, better filters may have helped).
However, MANY THANKS to Michael Cooper! Your steps and Process Explorer (procexp) got me quickly to a solution that had been dodging me all day.
I can add a couple of notes to Michael's excellent post.
I ignored (i.e. left unchanged) not just the \WinSxS\... folder but also the \System32\... folder.
Ultimately I found msvcr90.dll being pulled in from:
C:\Program Files (x86)\Intel\OpenCL SDK\2.0\bin\x64
Going through my Path I found the above and another, similar directory which seemed to contain 32-bit versions. I removed both of these, restarted and... STILL had the problem.
So, I followed Michael's steps once more, and, discovered another msvcr90.dll was now being loaded from:
C:\Program Files\Intel\iCLS Client\
Going through my Path again, I found the above and an (x86) version of this directory as well. So, I removed both of those, applied the changes, restarted VS2013 and...
No more R6034 Error!
I can't help but feel frustrated with Intel for doing this. I had actually found elsewhere online a tip about removing iCLS Client from the Path. I tried that, but the symptom was the same, so, I thought that wasn't the problem. Sadly iCLS Client and OpenCL SDK were tag-teaming my iisexpress. If I was lucky enough to remove either one, the R6034 error remained. I had to excise both of them in order to cure the problem.
Thanks again to Michael Cooper and everyone else for your help!
Using Michael's answer above, I was able to resolve this without a bat file by adding:
import os
# Remove CLS Client from system path
if os.environ['PATH'].find("iCLS Client")>=0:
os.environ['PATH'] = "".join([it for it in os.environ['PATH'].split(";") if not it.find("iCLS Client")>0])
to the main python file of the application. It just makes sure system path didn't include the paths that were causing the issue before the libraries that loaded the dll's were imported.
Thanks!
This post elaborates on #Micheal Cooper and #frmdstryr.
Once you identified the problematic PATH entries, you can put the following in front of a
python script, assuming here that iCLS Client and CMake are problematic.
import os
for forbidden_substring in ['iCLS Client', 'CMake']:
os.environ['PATH'] = ';'.join([item for item in os.environ['PATH'].split(';')
if not item.lower().find(forbidden_substring.lower()) >= 0])
Concerning the vim with YouCompleteMe case, you can put the following at the top of your vimrc:
python << EOF
import os
for forbidden_substring in ['iCLS Client', 'CMake']:
os.environ['PATH'] = ';'.join([item for item in os.environ['PATH'].split(';')
if not item.lower().find(forbidden_substring.lower()) >= 0])
EOF
If none of these solutions is applicable for you, you can try to remove the problem causing
entries from you PATH manually, but you want to make sure you don't break anything else on your
system that depends on these PATH entries. So, for instance, for CMake you could try to remove
its PATH entry, and only put a symlink (or the like) pointing to the cmake.exe binary into some
other directory that is in your PATH, to make sure cmake is still runnable from anywhere.
Thanks for the solution. I just little modified this sample code as the path variable in my system contains the string "ICLS CLIENT" instead of "iCLS Client"
import os
# print os.environ['PATH']
# Remove CLS Client from system path
if os.environ['PATH'].find("iCLS Client") >= 0 or os.environ['PATH'].find("ICLS CLIENT") >= 0:
os.environ['PATH'] = "".join([it for it in os.environ['PATH'].split(";") if not (it.find("iCLS Client")>0 or it.find("ICLS CLIENT")>0)])
I also had the same problem with embedding Python27.dll from a C-program using the Universal-CRT.
A <PYTHON_ROOT>\msvcr90.dll was the offender. And <PYTHON_ROOT> is off-course in my PATH. AFAICS the only users of msvcr90.dll are the PyWin32 modules
<PYTHON_ROOT>\lib\site-packages\win32\win32*.pyd.
The fix was just move <PYTHON_ROOT>\msvcr90.dll to that directory.
PS. PyWin32 still has this as an issue 7 years later!
In my case the rebuilding of linked libraries and the main project with similar "Runtime execution libraries" project setting helped. Hope that will be usefull for anybody.
In my case, I realised the problem was coming when, after compiling the app into an exe file, I would rename that file. So leaving the original name of the exe file doesn't show the error.
The discussion on this page involves doing things way far advanced above me. (I don't code.) Nevertheless, I ran Process Explorer as the recommended diagnostic. I found that another program uses and needs msvcr90.dll in it's program folder. Not understanding anything else being discussed here, as a wild guess I temporarily moved the dll to a neighboring program folder.
Problem solved. End of Runtime error message.
(I moved the dll back when I was finished with the program generating the error message.)
Thank you all for your help and ideas.
Check any library having user specified path by Process Explorer. It is not necessary must be msvcr??.dll
I solved same problem except I run Python 3. Present solutions not helped because they not indicate unusual paths of msvcr90.dll. I debug code step by step inside till error dialog appears after rows (called when my code was importing PyTables module):
import ctypes
ctypes.cdll.LoadLibrary('libbz2.dll')
Then Process Explorer helps to find path to old libbz2.dll caused the problem (steps 3, 4 of #Micheal Cooper algorithm)
Adding this answer for who is still looking for a solution. ESRI released a patch for this error. Just download the patch from their website (no login required), install it and it will solve the problem. I downloaded the patch for 10.4.1 but there are maybe patches for other versions also.

Resources