Opening a file in the user's home directory - ocaml

I've run into a strange problem using Core.In_channel library. Here's a piece of code meant to open a file in the user's home directory
open Core.Std
In_channel.with_file "~/.todo_list" ~f:(fun in_c ->
(* Do something here... *)
)
However, when running this, here is what I get:
Exception: (Sys_error "~/.todo_list: No such file or directory").
I am absolutely sure that ~/.todo_list exists, but I suspect that the filename is misinterpreted by OCaml.
What am I missing here?

As others have said, the expansion of ~ is done by the shell, not by the underlying system. No shell is involved in your call to with_file so the string is interpreted literally as a file name.
If the code is running on behalf of a user who has logged in, the home directory is available as the value of the environment variable HOME.
# Unix.getenv "HOME";;
- : string = "/Users/username"
Otherwise you will need to extract the home directory from the user database.
# let open Unix in (getpwnam "username").pw_dir;;
- : string = "/Users/username"

Related

How to perform a quick check if the file directory for a script in matlab is correct?

I have a script which relies on different files located in specific folders which are important to run the script without errors. In order to define the path location I decided to create many variables with the according path location name as string:
file directory var file directory location % default entries which
% only work with my computer
fd_1 = '\C:\Testrun\pathfinder.xls\';
fd_2 = '\C:\Testrun\pathfilter.slx\';
fd_3 = '\C:\Testrun\splinegenerator.xls\';
fd_4 = '\C:\Testrun\loftcreator.xls\';
fd_5 = '\C:\Testrun\surface_to_volume.xls\';
fd_6 = '\C:\Testrun\stp_creator.xls\';
fd_7 = '\C:\Testrun\CAD_file.stp\';
fd_8 = '\C:\Testrun\CAD_support_1.atm\';
fd_9 = '\C:\Testrun\CAD_support_2.atm\';
fd_10 = '\C:\Testrun\CAD_support_3.atm\';
This allowed me to use my script on my computer. However this was a pretty static solution which only works for one pc. Hence I need the following dynmamic routine to be coded:
0.) I created a while loop in order to rerun my script with the switch case/expression:
<<<here is the missing code for the file directory check>>>
%(I wanted to use the "strcmp" command to compare the strings with each other?)
<<<Here is my code with the specific while loop to rerun it>>>
1.) Before I enter this loop need to perform a quick check, if the files are correctly located.
2.) If the file directory cannot be assigned to the specific variables responsible for the file
directory name (e.g directory could not be found), a new file directory will be choosen by the
user
3.) The newly choosen file directory will be stored with the default file directory in a list
4.) The variable responsible for the file directory changes according to the list index which the
user choose from the list of stored file directory names
5.) The selection of the specific list index as well as the changes in the list will be permenantly
stored (The changes in the list should be saved and recalled again in the script upon rerunning
or exiting/reopening the script)
6.) The list index can be deleted if the user is unsatisfied with the file directory (e.g due the
file directory corruption)
Is it possible to write such a code and how would it be structered?
I think to put all those folders and files in the same path of main program, by this way, no need to mention drive letter like c:\ or d:, just mentiob folder name and its subfolders, and you can copy the main folder and run your program in another computer without changing anything, just run the main program.

Immuconf with Clojure not handling tree config files

Whenever I add a third config file to my .immuconf.edn I get:
No configuration files were specified, and neither an .immuconf.edn file nor
an IMMUCONF_CFG environment variable was found
This is driving me crazy since I cant really find anything wrong.
Using this loads thing OK:
["configs/betfair.edn" "configs/web-server.edn"]
however this generated an error:
["configs/betfair.edn" "configs/web-server.edn" "~/betfair.edn"]
This is the content of betfair.edn
{:betfair {:usr "..."
:pwd "..."
:app-key "..." ;; key used
:app-key-live "..."
:app-key-test "..."}}
(where ... is replaced with actual strings)
Why am I getting this error when adding the third file and how can I fix this?
Make sure that the last file specified in your <project dir>/.immuconf.edn (~/betfair.edn) exists in your home directory.
Immuconf does some magic to replace ~ in filenames specified in .immuconf.edn with a value of (System/getProperty "user.home") so you might check if that system property points to the same directory where your ~/betfair.edn file is located.
I have recreated your setup and it works on my machine so it is probably a problem with locations or access rights to your files. Unfortunately, error handling for the no arg invocation of (immuconf.config/load) doesn't help in troubleshooting as it swallows any exceptions and returns nil. That exception would probably tell you what kind of error occured (some file not found or some IO error happened). You might want to file a pull request with a patch to log such errors as warnings instead of ignoring them.

Create directory and write files to a remote, password protected computer

What I would like to do is be able to gain access to a computer over the network so I can create a new directory there that I will then save multiple files to throughout the rest of the script.
I have a script that creates a bunch of files that I need to save. The problem is that this script may be ran off any number of computers, but needs to save to the same computer. If I manually remote connect to the computer it prompts me for a username and password, but I am trying to just create a directory there. My code is below, along with the response I get.
if not os.path.exists(self.dirIn):
tryPath = self.dirIn.split("/")[0:-1]
tryPath = '/'.join(tryPath)
if not os.path.exists(tryPath):
os.mkdir(tryPath)
os.mkdir(str(self.dirIn))
else:
os.mkdir(str(self.dirIn))
WindowsError: [Error 1326] The user name or password is incorrect: '//computer/e$/directory/I/am/creating'
I am using Windows, Python27
I was able to just map the drive to my computer using subprocess, do what I needed, and then unmap the drive (optional)
subprocess.Popen("net use E: \\\\computername\\E$ %s /USER:%s" % (password, username))
time.sleep(1) # Short delay to allow E: drive to map before continuing
if not os.path.exists(self.dirIn):
os.makedirs(self.dirIn)
subprocess.Popen("net use E: /delete")
I did run into problems without the sleep, my program wouldn't find the directory without it.

Script failing to open and append multiple files simultaneously

So trying to finish a very simple script that has given me a unbelievably hard time. It's supposed to iterate through specified directories and open all text files in them and append them all with the same specified string.
The issue is it's not doing anything to the files at all. Using print to test my logic I've replaced lines 10 and 11 with print f (the write and close functions), and get the following output:
<open file '/Users/russellculver/documents/testfolder/.DS_Store', mode 'a+' at
So I think it is storing the correct files in the f variable for the write function, however I am not familiar with how Mac's handle DS_STORE or the exact role it plays in temporary location tracking.
Here is the actual script:
import os
x = raw_input("Enter the directory path here: ")
def rootdir(x):
for dirpaths, dirnames, files in os.walk(x):
for filename in files:
try:
with open(os.path.join(dirpaths, filename), 'a+') as f:
f.write('new string content')
f.close()
except:
print "Directory empty or unable to open file."
return x
rootdir(x)
And the exact return in Terminal after execution:
Enter the directory path here: /Users/russellculver/documents/testfolder
Exit status: 0
logout
[Process completed]
Yet nothing written to the .txt files in the provided directory.
The way the indentation is in the question, you return from the function right after writing the first file; either of the for-loops never finish. Which is relatively easy to surmise from the fact that you only get one output file printed.
Since you're not doing anything with the result of the rootdir function, I would just remove the return statement entirely.
An aside: there is no need to use f.close() when you open a file with the with statement: it will automatically be closed (even upon an exception). That is in fact what the with statement was introduced for (see the pep on context managers if necessary).
To be complete, here's the function the way I would have (roughly) written it:
def rootdir(x):
for dirpaths, dirnames, files in os.walk(x):
for filename in files:
path = os.path.join(dirpaths, filename)
try:
with open(path, 'a+') as f:
f.write('new string content')
except (IOError, OSError) as exc:
print "Directory empty or unable to open file:", path
(Note that I'm catching only the relevant I/O errors; any other exceptions (though unlikely) will not be caught, as they are likely not to be related to non-existing/unwritable file.)
Return was indented wrong, ending the iteration after a single loop. Wasn't even necessary so was removed entirely.

Weird Behavior in Windows XP with Python snippet

I wrote a snippet that would automatically copy a file from a source directory to a path on an usb. Because drive letter names are assigned by the PC independent o the slot I figured I would GetLogicalDrives() and if the path to the usb directory is in any of those drives then it would copy (I hope I'm making some sense). Here is the piece of code I wrote in Python:
import itertools, ctypes, string, sys, os.path, shutil
def drive_list():
drive_bitmask = ctypes.cdll.kernel32.GetLogicalDrives()
drive_list = list(itertools.compress(string.ascii_uppercase,
map(lambda x:ord(x) - ord('0'), bin(drive_bitmask)[:1:-1])))
return drive_list
for drive in drive_list():
path = drive + ":\\targer_directory\target_file.ext"
if drive not in ["C", "D", "E"]:
if os.path.exists(path) == True:
shutil.copy2(r'C:\source_directory\source_file.ext', path)
Whenever I run this script I get a bunch of error messages saying:
"Exception Processing Message c0000013 Parameters 75b1bf7c 4 75b1bf7c 75b1bf7c"
I think this probably means that I have some "ghost drives" in my pc. Any help in bypassing this behavior is deeply appreciated.
Note: The code runs at the end and the copy job is done succesfuly, but not until the error messages are cleared which is not the objective if I want to perform automatic backups.
I'm not sure whether this will help or not. But you can try this!
We were receiving the same error on execution of a windows application (an .exe file) and the below steps resolved it.
Goto Registry Editor
(Run -> type 'regedit' -> hit enter)
Expand HKEY_LOCAL_MACHINE
Expand System
Expand CurrentControlSet
Expand Control
Select Windows
Double click on ErrorMode in the right side pane
Set the Value Data as 2
Click OK
Restart your system