I want to set options to my parser program via simple config file parsed by boost::program_options. I want to set prefixmiddle to (single space).
I already tried that options:
prefixmiddle=
prefixmiddle=" " # Equals to `" "`
prefixmiddle = " " # Same
prefixmiddle =
Is there a way to do it?
P.S. Of course, I can always use "" and remove them, but I wonder if there is another solution.
Related
I've been getting an error in this snippet of code that says my file path is incorrect. I know python likes to convert file paths to use double slashes (ie. \) however I am using a raw string variable. Does anyone understand why this is happening?
import os
comList = ['D:\\twidl\\data\\intel\\unlock\\unlock.bin\n', 'D:\\Kit025_02_TGF047K_7002\\BI\\TG-OEM\\Dell\\TGB047K_TGL051b7UB_1024.bin\n', 'D:\\twidl\\gui\\utils\\products.xml\n']
def remanTool():
for string in comList:
string1 = r"C:\Users\mgilmore\Desktop\FirmwareInstaller\WinPython-32bit-2.7.13.0Zero\python-2.7.13\python.exe"
string2 = r"C:\Users\mgilmore\Desktop\FirmwareInstaller\TWIDL\PSHH_Reman.py"
command = os.system(string1 + string2 + " -s " + comList[0] + " -f " + comList[1] + " -m " + comList[2] )
print command
I expect the command to be run, however it keeps saying the file path is wrong.
Also, for reference, comList is basically just an array of directories.
The directories for some reason have been saved with endlines and double slashes. I've already tried using os.path.abspath().
Here is my error message:
The filename, directory name, or volume label syntax is incorrect.
I figured out what was wrong guys, it was just an error in my text editor. All I had to do was restart the software.
I'm generating a few Logs on the system, and then copying it to /tmp/MyFolder, and then
I move the folder to the desktop, I'm trying to compact it before you move on, but I don't know how to do it, I have tried the following:
tell application "Finder"
set theItem to "/tmp/MyFolder" as alias
set itemPath to quoted form of POSIX path of theItem
set fileName to name of theItem
set theFolder to POSIX path of (container of theItem as alias)
set zipFile to quoted form of (theFolder & fileName & ".zip")
do shell script "zip -r " & zipFile & " " & itemPath
end tell
While this isn't an AppleScript-ObjC script, I'm posting the corrected version of your own script so that it functions to do as you described:
tell application "System Events"
set itemPath to "/tmp/MyFolder"
set theItem to item itemPath
set fileName to quoted form of (get name of theItem)
set theFolder to POSIX path of (container of theItem)
set zipFile to fileName & ".zip"
end tell
do shell script "cd " & quoted form of theFolder & ¬
"; zip -r " & zipFile & space & fileName & ¬
"; mv " & zipFile & space & "~/Desktop/"
Trying to avoid using Finder for file system operations. It sounds counter-intuitive, but it's not well-suited for it. Use System Events, which has—among many other benefits—the ability to handle posix paths.
The script now zips the folder and its containing items into an archive at /tmp/MyFolder.zip, then moves this archive to the desktop.
I hope I am able to describe my problem well, sorry in advance if it's complicated.
Question:
Does Python (or the os.path calls) automatically insert a return after an amount of characters?
Background:
I try to extract acoustic features from .wav files with the tool openSMILE.
For this purpose I pass the strings of the path (inputfile and outputfile)
via subprocess.
The SMILExtract call takes 3 arguments (-C for config; -I for inputfile -O for output file). I prepare these 3 Arguments with string operations and save the arguments in a list which gets passed to the subprocess call.
def extractFeatures(self,inputFile):
self.openSMILEsettings.append("-I " + inputFile)
outputFile = os.path.dirname(inputFile) + "/featuresOf_" +os.path.basename(inputFile)[0:-3] + "arff"
self.openSMILEsettings.append("-O " + outputFile)
print self.openSMILEsettings[2]
print ' '.join(self.openSMILEsettings)
# print subprocess.check_output(['SMILExtract'] + self.openSMILEsettings)
extractFeatures("/media/USERNAME/MountPOINT/Dir1/Dir2/Dir3/02003_SomeSesssionNumber1_and2_2323123/audioFile.wav")
In the console the output of the print command (print ' '.join(...)) looks alright (example below)
-C OSconfig/IS12_speaker_trait.conf -I /media/USERNAME/MountPOINT/Dir1/Dir2/Dir3/02003_SomeSesssionNumber1_and2_2323123/audioFile.wav -O /media/USERNAME/MountPOINT/Dir1/Dir2/Dir3/02003_SomeSesssionNumber1_and2_2323123/featuresOf_audioFile.arff
However when I try to run the code with the subprocess call I get an exception. For debugging purposes I copied the output of the print to a text Editor and it appears that a Return gets entered, it looks like this
-C OSconfig/IS12_speaker_trait.conf -I /media/USERNAME/MountPOINT/Dir1/Dir2/Dir3/02003_SomeSesssionNumber1_and2_2323123/audioFile.wav -O /media/USERNAME/MountPOINT/Dir1/Dir2/Dir3/02003_SomeSesssionNumber1_and2_2323123/featur
esOf_audioFile.arff
This is word wrap, and is caused by your text editor. Essentially, there is no newline character, but your editor cannot show the text on a single line because it's too long. As a result, it's pushing the text to a new line.
You can disable this in gedit by going to View->Preferences->Uncheck "Enable Text Wrapping".
Thank you Dyno. That explains why there was a return in the texteditor.
I meanwhile found a solution for the exectuion of the SMILExtract call.
I changed subprocess call to os.system and used a template like explained elsewhere
The new call looks like this:
def extractFeatures(self,inputFile):
self.openSMILEsettings.append("-I " + inputFile)
outputFile = os.path.dirname(inputFile) + "/featuresOf_" +os.path.basename(inputFile)[0:-3] + "arff"
self.openSMILEsettings.append("-O " + outputFile)
cmd_template = 'SMILExtract {config_path} {wav_path} {arff_path}'
os.system(cmd_template.format(
config_path=self.openSMILEsettings[0],
wav_path=self.openSMILEsettings[1],
arff_path=self.openSMILEsettings[2],
))
This now runs smoothly. Is there any downside to using os.system insted of subprocess?
Normally I try to avoid the use of macros, so I actually don't know how to use them beyond the very most basic ones, but I'm trying to do some meta-manipulation so I assume macros are needed.
I have an enum listing various log entries and their respective id, e.g.
enum LogID
{
LOG_ID_ITEM1=0,
LOG_ID_ITEM2,
LOG_ID_ITEM3=10,
...
}
which is used within my program when writing data to the log file. Note that they will not, in general, be in any order.
I do most of my log file post-processing in Matlab so I'd like to write the same variable names and values to a file for Matlab to load in. e.g., a file looking like
LOG_ID_ITEM1=0;
LOG_ID_ITEM2=1;
LOG_ID_ITEM3=10;
...
I have no idea how to go about doing this, but it seems like it shouldn't be too complicated. If it helps, I am using c++11.
edit:
For clarification, I'm not looking for the macro itself to write the file. I want a way to store the enum element names and values as strings and ints somehow so I can then use a regular c++ function to write everything to file. I'm thinking the macro might then be used to build up the strings and values into vectors? Does that work? If so, how?
I agree with Adam Burry that a separate script is likely best for this. Not sure which languages you're familiar with, but here's a quick Python script that'll do the job:
#!/usr/bin/python
'''Makes a .m file from an enum in a C++ source file.'''
from __future__ import print_function
import sys
import re
def parse_cmd_line():
'''Gets a filename from the first command line argument.'''
if len(sys.argv) != 2:
sys.stderr.write('Usage: enummaker [cppfilename]\n')
sys.exit(1)
return sys.argv[1]
def make_m_file(cpp_file, m_file):
'''Makes an .m file from enumerations in a .cpp file.'''
in_enum = False
enum_val = 0
lines = cpp_file.readlines()
for line in lines:
if in_enum:
# Currently processing an enumeration
if '}' in line:
# Encountered a closing brace, so stop
# processing and reset value counter
in_enum = False
enum_val = 0
else:
# No closing brace, so process line
if '=' in line:
# If a value is supplied, use it
ev_string = re.match(r'[^=]*=(\d+)', line)
enum_val = int(ev_string.group(1))
# Write output line to file
e_out = re.match(r'[^=\n,]+', line)
m_file.write(e_out.group(0).strip() + '=' +
str(enum_val) + ';\n')
enum_val += 1
else:
# Not currently processing an enum,
# so check for an enum definition
enumstart = re.match(r'enum \w+ {', line)
if enumstart:
in_enum = True
def main():
'''Main function.'''
# Get file names
cpp_name = parse_cmd_line()
m_name = cpp_name.replace('cpp', 'm')
print('Converting ' + cpp_name + ' to ' + m_name + '...')
# Open the files
try:
cpp_file = open(cpp_name, 'r')
except IOError:
print("Couldn't open " + cpp_name + ' for reading.')
sys.exit(1)
try:
m_file = open(m_name, 'w')
except IOError:
print("Couldn't open " + m_name + ' for writing.')
sys.exit(1)
# Translate the cpp file
make_m_file(cpp_file, m_file)
# Finish
print("Done.")
cpp_file.close()
m_file.close()
if __name__ == '__main__':
main()
Running ./enummaker.py testenum.cpp on the following file of that name:
/* Random code here */
enum LogID {
LOG_ID_ITEM1=0,
LOG_ID_ITEM2,
LOG_ID_ITEM3=10,
LOG_ID_ITEM4
};
/* More random code here */
enum Stuff {
STUFF_ONE,
STUFF_TWO,
STUFF_THREE=99,
STUFF_FOUR,
STUFF_FIVE
};
/* Yet more random code here */
produces a file testenum.m containing the following:
LOG_ID_ITEM1=0;
LOG_ID_ITEM2=1;
LOG_ID_ITEM3=10;
LOG_ID_ITEM4=11;
STUFF_ONE=0;
STUFF_TWO=1;
STUFF_THREE=99;
STUFF_FOUR=100;
STUFF_FIVE=101;
This script assumes that the closing brace of an enum block is always on a separate line, that the first identifier is defined on the line following the opening brace, that there are no blank lines between the braces, that enum appears at the start of a line, and that there is no space following the = and the number. Easy enough to modify the script to overcome these limitations. You could have your makefile run this automatically.
Have you considered "going the other way"? It usually makes more sense to maintain your data definitions in a (text) file, then as part of your build process you can generate a C++ header and include it. Python and mako is a good tool for doing this.
I m trying to read two files and replace content of one file with content of other file in files present in folder which also has sub directories.
But its tell sub process not defined.
i'm new to python and shell script can anybody help me with this please?
import os
import sys
import os.path
f = open ( "file1.txt",'r')
g = open ( "file2.txt",'r')
text1=f.readlines()
text2=g.readlines()
i = 0;
for line in text1:
l = line.replace("\r\n", "")
t = text2[i].replace("\r\n", "")
args = "find . -name *.tml"
Path = subprocess.Popen( args , shell=True )
os.system(" sed -r -i 's/" + l + "/" + t + "/g' " + Path)
i = i + 1;
To specifically address your actual error, you need to import the subprocess module as you are making use of it (oddly) in your code:
import subprocess
After that, you will find more problems. I will try and keep it as simple as possible with my suggestions. Code first, then I will break it down. Keep in mind, there are more robust ways to accomplish this task. But I am doing my best to keep in mind your experience level and making it make your current approach as closely as possible.
import subprocess
import sys
# 1
results = subprocess.Popen("find . -name '*.tml'",
shell=True, stdout=subprocess.PIPE)
if results.wait() != 0:
print "error trying to find tml files"
sys.exit(1)
# 2
tml_files = []
for tml in results.stdout:
tml_files.append(tml.strip())
if not tml_files:
print "no tml files found"
sys.exit(0)
tml_string = " ".join(tml_files)
# 3
with open ("file1.txt") as f, open("file2.txt") as g:
while True:
# 4
f_line = f.readline()
if not f_line:
break
g_line = g.readline()
if not g_line:
break
f_line = f_line.strip()
g_line = g_line.strip()
if not f_line or not g_line:
continue
# 5
cmd = "sed -i -e 's/%s/%s/g' %s" % \
(f_line.strip(), g_line.strip(), tml_string)
ret = subprocess.Popen(cmd, shell=True).wait()
if ret != 0:
print "error doing string replacement"
sys.exit(1)
You do not need to read in your entire files at once. If they are large this could be a lot of memory. You can consume a line at a time, and you can also make use of what is called "context managers" when you open the files. This will ensure they close properly no matter what happens:
We start with a subprocess command that is run only once to find all your .tml files. Your version had the same command being run multiple times. If the search path is the same, then we only need it once. This checks the exit code of the command and quits if it failed.
We loop over stdout on the subprocess command, and add the stripped lines to a list. This is a more robust way of your replace("\r\n"). It removes whitespace. A "list comprehension" would be better suited here (down the line). If we didn't find any tml files, then we have no work to do, so we exit. Otherwise, we join them together in a space-separated string to be suitable for our command later.
This is called "context managers". You can open the file in a way that no matter what they will be closed properly. The file is open for the length of the context within that code block. We are going to loop forever, and break when appropriate.
We pull a line, one at a time, from each file. If either line is blank, we reached the end of the file and cannot do any more work, so we break out. We then strip the newlines, and if either string is empty (blank line) we still can't do any work, but we just continue to the next available line.
A modified version of your sed command. We construct the command string on each loop for the source and replacement strings, and tack on the tml file string. Bear in mind this is a very naive approach to the replacement. It really expects your replacement strings to be safe characters and not break the s///g sed format. But we run that with another subprocess command. The wait() simply waits for the return code, and we check it for an error. This approach replaces your os.system() version.
Hope this helps. Eventually you can improve this to do more checking and safe operations.