Difficulty using oct2py - python

I recently installed oct2py along with its dependencies in order to import a few matlab functions to be used in my python code. The .m file is located in the same directory as my python code.
Could you please help me figure out, how I would import those .m files along with the methods located within them and how would I use those functions within my python code, considering that the actual functions are defined in octave/matlab. I have included an example .m file with a function
function x=readfile(y)
% Puts the contents of a text file with path and name
% specified in string y, into char array x.
% Example: mystring = readfile('c:\workdir\readme.txt');
fid = fopen(y,'r'); % Read the Plaintext
M = fread(fid);
fclose(fid);
x = char(M');
The above function is located in a file named 'readfile.m' within the same directory as my python code.

This is as simple as
from oct2py import octave
octave.feval( 'readfile', 'your_input_file_here.txt' )
PS. Your octave executable needs to be available from the system path.

So apparently octave 4 doesn't have 'octave.exe' located within bin, however octave 3 does, and works perfectly well with oct2py

Related

Can a Python Executable create files?

I converted my Python code into an executable using pyinstaller but part of my project involves printing the result onto a text document, stored on the computer. However this same code doesn't work once in the executable. I separately also tried to get it to just create files using the
with open(f'{random.random()}.txt', 'x') as sys.stdout:
print(encmsg)
option and using a random num generator to create new file names so it doesn't overlap. Still didn't create anything.
In Summary,
What code, when running through an executable file, will download the string it produces onto a text file onto the computer SOMEWHERE.
Thank you.
The relevant code is:
string = '1219151'
with open(f'{random.random()}.txt', 'x') as sys.stdout:
print(string)
That is it. It's in an executable, but doesn't produce the txt file anywhere.
I am on Windows 10.

how to modify txt file properties with python

I am trying to make a python program that creates and writes in a txt file.
the program works, but I want it to cross the "hidden" thing in the txt file's properties, so that the txt can't be seen without using the python program I made. I have no clues how to do that, please understand I am a beginner in python.
I'm not 100% sure but I don't think you can do this in Python. I'd suggest finding a simple Visual Basic script and running it from your Python file.
Assuming you mean the file-properties, where you can set a file as "hidden". Like in Windows as seen in screenshot below:
Use operating-system's command-line from Python
For example in Windows command-line attrib +h Secret_File.txt to hide a file in CMD.
import subprocess
subprocess.run(["attrib", "+h", "Secret_File.txt"])
See also:
How to execute a program or call a system command?
Directly call OS functions (Windows)
import ctypes
path = "my_hidden_file.txt"
ctypes.windll.kernel32.SetFileAttributesW(path, 2)
See also:
Hide Folders/ File with Python
Rename the file (Linux)
import os
filename = "my_hidden_file.txt"
os.rename(filename, '.'+filename) # the prefix dot means hidden in Linux
See also:
How to rename a file using Python

Generate TeX/LaTeX file and compile both in Python

I am preparing a data processing code and the results from these are to be fed to a TeX/LaTeX file and the file is to be compiled by Python (i.e. Python should send the command to compile the TeX/LaTeX file)
At present I plan to generate a text file (with .tex extension) with the necessary syntax for TeX/LaTeX and then call external system command using os.system. Is there any easier way or modules that can do this?
No such Python modules exist but you could try generating text files with the required syntax of the text file with .tex extension and compile it by running system commands with Python:
import os
os.system("pdflatex filename")
You could use PyLaTeX for this. This is exactly one of the things that it is meant to be used for. https://github.com/JelteF/PyLaTeX
Make sure, you have installed Perl and MikTeX (for latexmk and pdflatex compilers support) in your system.
If not, you can download Perl from https://www.perl.org/get.html
and MikTeX from https://miktex.org/download.
Also do not forget to check http://mg.readthedocs.io/latexmk.html#installation as it guides nicely about Latex compilers.
I have document.tex with following content.
\documentclass{article}%
\usepackage[T1]{fontenc}%
\usepackage[utf8]{inputenc}%
\usepackage{lmodern}%
\usepackage{textcomp}%
\usepackage{lastpage}%
%
%
%
\begin{document}%
\normalsize%
\section{A section}%
\label{sec:A section}%
Some regular text and some %
\textit{italic text. }%
\subsection{A subsection}%
\label{subsec:A subsection}%
Also some crazy characters: \$\&\#\{\}
%
\end{document}
Finally create any python file and paste any one of the below code and run.
1st way
# 1st way
import os
tex_file_name = "document.tex";
os.system("latexmk " + tex_file_name + " -pdf");
2nd way
# 2nd way
import os
tex_file_name = "document.tex";
os.system("pdflatex " + tex_file_name);
For compiling complex latex files, you need to look for extra options passed with latexmk or pdflatex commands.
Thanks.

Accessing a python script in a different folder, using a python script

Can a python script located in D:\Folder_A\Folder_B\be used to change variables in another python script located in D:\Folder_A\Folder_C\, and then print them out on the console?
NOTE: I'm a beginner in Python, and I'm using v2.7.8.
EDIT: To answer #Rik Verbeek, I created a python file in location A (D:\Folder_A\Folder_B\), and another file at location B (D:\Folder_A\Folder_C\), with both the folders (Folder_B & Folder_C) located in D:\Folder_A\. In the 2nd .py file, I wrote the following:
a = 0
b = 0
Now I want to change these variables from the 1st .py file to 5 and 10 respectively, and print them to the console. Also, these files are not in the Python libraries, but are instead, located in another folder(Folder_A).
To answer #Kasra (and maybe #cdarke), I don't want to import a module, unless it is the only way.
If you have some "global" variables I think is a good idea to have them in a separated module and import that module from each place you need them. This way you only have to do it as cdarke has commented.

running python code, to use sextractor with more than one image file

I have written piece of code which runs sextractor from python, however I only know how to do this for one file, and i need to loop it over 62 files. Im not sure how i would go about doing this. I have attached my code bellow:
#!/usr/bin/env python
# build a catalog using sextractor on des image here
sys.path.append('/home/fitsfiles') #not sure if this does anything/is correct
def sex(image, output, sexdir='/home/sextractor-2.5.0', check_img=None,config=None, l=None) :
'''Construct a sextractor command and run it.'''
#creates a sextractor line e.g sex img.fits -catalog_name -checkimage_name
q="/home/fitsfiles/"+ "01" +".fits"
com = [ "sex ", q, " -CATALOG_NAME " + output]
s0=''
com = s0.join(com)
res = os.system(com)
return res
img_name=sys.argv[0]
output=img_name[0:1]+'_star_catalog.fits'
t=sex(img_name,output)
print '----done !---'
so this code produces a command in my main terminal of, sex /home/fitsfiles/01.fits -CATALOG_NAME g_star_catalog.fits
which successfully produces a star catalogue as I want.
However I want my code to to this for 62 fits files and change the name of star_catalog.fits depending upon which fitsfile is being used. any help would be appreciated.
There are many ways you could approach this. Let's assume you want to run your script as something like
python extract_stars.py /home/fitsfiles/*.fits
Then, you could try something like this:
for arg in len(sys.argv):
filename = arg.split('/')[-1].strip('.fits')
t = sex(arg, filename +'_star_catalog.fits')
# Whatever else
This assumes that you remove the line in sex that reformats the input filename. Also, you do not need to append the fits directory to your path.
The alternative approach is, if you do not plan to do anything else in python, you could write a bash script which would really simplify the task.
And, as a side note, you if you had asked this question more generally (ie, I wish to apply a function I wrote to a number of input files) and without reference to a rather uncommonly used application, you would have likely received an answer much more quickly.
The community has now developed some python wrappers which allow you to run sextractor as if it was a python command. These are: pysex, sewpy and astromatic_wrapper.
The good thing about sextractor wrappers is that allow you to write much cleaner code without the need of defining extra functions, invoking os commands or having the configuration files and the outputfiles on your machine. Moreover, the output can be an astropy table, a pandas dataframe or a numpy array.
For your specific case, you could use pysex and do:
import pysex
import glob
filelist = glob.glob('/directory/*.fits')
for fitsfile in filelist:
cat = pysex.run(fitsfile, params=['X_IMAGE', 'Y_IMAGE', 'FLUX_APER'],
conf_args={'PHOT_APERTURES':5})
print cat['FLUX_APER']

Categories