Jekyll's is removing static file during cleanup - plugins

I want to include a gnuplot code inside a markdown page and have Jekyll compile the graph when I save it. The graph image is being saved. But it is removed during jekyll's cleanup. The closest that I have found toward a solution is at Copying generated files from a Jekyll plugin to a site resource folder. However, I don't undersand the overall flow of Jekyll and how I keep static files from being removed. I have added site.static_files << Jekyll::StaticFile.new(site, site.source, path, filename) with no results.
If I create a dummy file outside of the _site folder, Jekyll will keep my file safe inside the _site file. I would rather not have to create that dummy file.
Here is code for my plugin. Any help will be awesome.
class RenderGNUplot < Liquid::Block
def initialize(tag_name, markup, tokens)
super
#markup = markup
#attributes = {}
markup.scan(Liquid::TagAttributes) do |key, value| #attributes[key.to_sym] = value end
end
def gnuplot(commands)
IO.popen("gnuplot", "w") { |io| io.puts commands }
end
def render(context)
site = context.registers[:site]
#file = ""
commands = super
if ( commands =~ /set output "(.*)"/ )
setfile_regex = Regexp.new(/set output "((.*))"/)
filepath = commands[setfile_regex, 1]
#file = File.basename filepath
commands = commands.sub!(commands[setfile_regex], 'set output "_site/media/' + #file +'"' )
p commands
end
gnuplot(commands)
site.static_files << Jekyll::StaticFile.new(site, site.source, "_site/media/", "#{#file}")
# site.static_files << Jekyll::StaticSitemapFile.new(site, site.dest, '/', 'sitemap.xml')
"<object id='' type='image/svg+xml' data='#{site.baseurl}/media/{#file}'>Your browser does not support SVG</object>"
end
end
Liquid::Template.register_tag('test', RenderGNUplot)
And Markdown page
---
layout: post
title: "Thin Server"
date: 2015-04-28 10:42:56
categories: thin
---
{% test location: Test%}
set terminal svg size 600,400 dynamic enhanced fname 'arial' fsize 10 #mousing jsdir 'http://localhost:4000/media/' name "histograms_1" butt dashlength 1.0
set output "media/curves.svg"
set key inside left top vertical Right noreverse enhanced autotitle box lt black linewidth 1.000 dashtype solid
set samples 50, 50
set title "Simple Plots"
set title font ",20" norotate
plot [-10:10] sin(x),atan(x),cos(atan(x))
{% endtest%}

This is the exact code that I am using. It only has the Liquid block and jekyll StaticFile
class GNUplotFile < Jekyll::StaticFile
def write(dest)
puts "WRITE---->>>>>>>>>>>"
#File.write('_site/media/BTTTTT.svg', DateTime.now)
gnuplot(#commands)
# do nothing
end
def gnuplot(commands)
IO.popen("gnuplot", "w") { |io| io.puts commands }
end
def givemethecommands(commands)
#commands = commands
end
end
class RenderGNUplot < Liquid::Block
def initialize(tag_name, markup, tokens)
super
#markup = markup
#attributes = {}
markup.scan(Liquid::TagAttributes) do |key, value| #attributes[key.to_sym] = value end
end
def render(context)
site = context.registers[:site]
#file = ""
commands = super
if ( commands =~ /set output "(.*)"/ )
setfile_regex = Regexp.new(/set output "((.*))"/)
filepath = commands[setfile_regex, 1]
#file = File.basename filepath
commands = commands.sub!(commands[setfile_regex], 'set output "_site/media/' + #file +'"' )
#p commands
end
gnuplot = GNUplotFile.new(site, site.source, "_site/media/", "#{#file}")
gnuplot.givemethecommands commands
site.static_files << gnuplot
# site.static_files << Jekyll::StaticFile.new(site, site.dest, '/', 'sitemap.xml')
"<object id='' type='image/svg+xml' data='#{site.baseurl}/media/#{#file}'>Your browser does not support SVG</object>"
end
end
Liquid::Template.register_tag('test', RenderGNUplot)

Related

How do I adjust the number of spaces ipython uses for indentation in the terminal?

I use ipython in a terminal (NOT in a notebook), and by default it autoindents with 4 spaces.
How do I change the number of automatically-inserted spaces?
Number of spaces inserted by the TAB key
Assuming you are on Linux, you can locate your ipython installation directory with:
which ipython
It will return you a path which ends in /bin/ipython. Change directory to that path without the ending part /bin/ipython.
Then locate the shortcuts.py file where the indent buffer is defined:
find ./ -type f -name "shortcuts.py"
And in that file, replace 4 in the below function by 2:
def indent_buffer(event):
event.current_buffer.insert_text(' ' * 4)
Unfortunately, the 4 above is not exposed as a configuration, so we currently have to edit each ipython installation. That's cumbersome when working with many environments.
Number of spaces inserted by autoindent
Visit /path/to/your/IPython/core/inputtransformer2.py and modify two locations where the number of spaces is hard-coded as 4:
diff --git a/IPython/core/inputtransformer2.py b/IPython/core/inputtransformer2.py
index 37f0e7699..7f6f4ddb7 100644
--- a/IPython/core/inputtransformer2.py
+++ b/IPython/core/inputtransformer2.py
## -563,6 +563,7 ## def show_linewise_tokens(s: str):
# Arbitrary limit to prevent getting stuck in infinite loops
TRANSFORM_LOOP_LIMIT = 500
+INDENT_SPACES = 2 # or whatever you prefer!
class TransformerManager:
"""Applies various transformations to a cell or code block.
## -744,7 +745,7 ## def check_complete(self, cell: str):
ix += 1
indent = tokens_by_line[-1][ix].start[1]
- return 'incomplete', indent + 4
+ return 'incomplete', indent + INDENT_SPACES
if tokens_by_line[-1][0].line.endswith('\\'):
return 'incomplete', None
## -778,7 +779,7 ## def find_last_indent(lines):
m = _indent_re.match(lines[-1])
if not m:
return 0
- return len(m.group(0).replace('\t', ' '*4))
+ return len(m.group(0).replace('\t', ' '*INDENT_SPACES))
class MaybeAsyncCompile(Compile):

LibreOffice Calc macro to save a named sheet in a csv file

There is a Calc file named as 'Data.ods' with a sheet named 'DataSheet' which should be saved in a 'Data.csv' file in the current directory using {tab} as field delimiter and double quoted data fields. How to implement this in LO Basic macro?
You have not specified whether the macro should open the 'Data.ods' spreadsheet or whether it is already open. This code works with the current spreadsheet:
Sub Generate_CSV()
Dim sURL As String ' URL of current spreadsheet
Dim FileN As String ' URL of target CSV-file
Dim oCurrentController As Object ' Before save - activate sheet sSheetName
Dim storeParms(2) as new com.sun.star.beans.PropertyValue
Const sSheetName = "DataSheet"
GlobalScope.BasicLibraries.LoadLibrary("Tools") ' Only for GetFileName
sURL = thisComponent.getURL()
If Not thisComponent.getSheets().hasByName(sSheetName) Then
MsgBox ("Sheet """ & sSheetName & """ Not Found In Current Spreadsheet")
Exit Sub
EndIf
FileN = GetFileNameWithoutExtension(sURL) & ".csv" ' For Data.ods it will be Data.csv
REM Options to StoreTo:
storeParms(0).Name = "FilterName"
storeParms(0).Value = "Text - txt - csv (StarCalc)"
storeParms(1).Name = "FilterOptions"
storeParms(1).Value = "9,34,,65535,1,,0,true,true,true"
REM About this string see https://wiki.openoffice.org/wiki/Documentation/DevGuide/Spreadsheets/Filter_Options
storeParms(2).Name = "Overwrite"
storeParms(2).Value = True
REM Activate sheet for export - select "DataSheet"
thisComponent.getCurrentController().setActiveSheet(thisComponent.getSheets().getByName(sSheetName))
REM storeToURL can raises com.sun.star.io.IOException! Only now:
On Error GoTo Errorhandle
REM Export
thisComponent.storeToURL(FileN,storeParms())
MsgBox ("No Error Found,Upload file is saved : """ + ConvertFromUrl(FileN) + """.")
Exit Sub
Errorhandle:
MsgBox ("Modifications Are Not Saved,Upload File Not Generated" & chr(13) _
& "May be table " & ConvertFromUrl(FileN) & " is open in another window?")
Exit Sub
Resume
End Sub
(It was posted on 18 Nov 2011 there)

Octave: Load all files from specific directory

I used to have Matlab and loaded all txt-files from directory "C:\folder\" into Matlab with the following code:
myFolder = 'C:\folder\';
filepattern = fullfile(myFolder, '*.txt');
files = dir(filepattern);
for i=1:length(files)
eval(['load ' myFolder,files(i).name ' -ascii']);
end
If C:\folder\ contains A.txt, B.txt, C.txt, I would then have matrices A, B and C in the workspace.
The code doesn't work in octave, maybe because of "fullfile"?. Anyway, with the following code I get matrices with the names C__folder_A, C__folder_B, C__folder_C. However, I need matrices called A, B, C.
myFolder = 'C:\folder\';
files = dir(myFolder);
for i=3:length(files)
eval(['load ' myFolder,files(i).name ' -ascii']);
end
Can you help me?
Thanks,
Martin
PS: The loop starts with 3 because files(1).name = . and files(2).name = ..
EDIT:
I have just found a solution. It's not elegant, but it works.
I just add the path in which the files are with "addpath", then I don't have to give the full name of the directory in the loop.
myFolder = 'C:\folder\';
addpath(myFolder)
files = dir(myFolder);
for i=3:length(files)
eval(['load ' files(i).name ' -ascii']);
end
It's usually bad design if you load files to variables which name is generated dynamically and you should load them to a cell array instead but this should work:
files = glob('C:\folder\*.txt')
for i=1:numel(files)
[~, name] = fileparts (files{i});
eval(sprintf('%s = load("%s", "-ascii");', name, files{i}));
endfor
The function scanFiles searches file names with extensions in the current dirrectory (initialPath) and subdirectories recursively. The parameter fileHandler is a function that you can use to process populated file structure (i.e. read text, load image, etc.)
Source
function scanFiles(initialPath, extensions, fileHandler)
persistent total = 0;
persistent depth = 0; depth++;
initialDir = dir(initialPath);
printf('Scanning the directory %s ...\n', initialPath);
for idx = 1 : length(initialDir)
curDir = initialDir(idx);
curPath = strcat(curDir.folder, '\', curDir.name);
if regexp(curDir.name, "(?!(\\.\\.?)).*") * curDir.isdir
scanFiles(curPath, extensions, fileHandler);
elseif regexp(curDir.name, cstrcat("\\.(?i:)(?:", extensions, ")$"))
total++;
file = struct("name",curDir.name,
"path",curPath,
"parent",regexp(curDir.folder,'[^\\\/]*$','match'),
"bytes",curDir.bytes);
fileHandler(file);
endif
end
if!(--depth)
printf('Total number of files:%d\n', total);
total=0;
endif
endfunction
Usage
# txt
# textFileHandlerFunc=#(file)fprintf('%s',fileread(file.path));
# scanFiles("E:\\Examples\\project\\", "txt", textFileHandlerFunc);
# images
# imageFileHandlerFunc=#(file)imread(file.path);
# scanFiles("E:\\Examples\\project\\datasets\\", "jpg|png", imageFileHandlerFunc);
# list files
fileHandlerFunc=#(file)fprintf('path=%s\nname=%s\nsize=%d bytes\nparent=%s\n\n',
file.path,file.name,file.bytes,file.parent);
scanFiles("E:\\Examples\\project\\", "txt", fileHandlerFunc);

NSLocalizedString managing translations over app versions [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
Here is a scenario:
I write an iPhone app using NSLocalizedString incase I decide to release it in different countries.
I decide to release the App over in France.
The translator takes my Localized.strings and does a great job translating
I update the app, and need some more translating.
I'm using genstrings and it overwrites the good work the translator did, is there a easy way for me to manage my translations over App versions?
Check out this project on GitHub, which provides a python scripts which makes genstrings a little bit smarter.
Since I don't like link-only answers (links may die), I'll also drop here the python script (all credits go to the author of the linked project)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Localize.py - Incremental localization on XCode projects
# João Moreno 2009
# http://joaomoreno.com/
# Modified by Steve Streeting 2010 http://www.stevestreeting.com
# Changes
# - Use .strings files encoded as UTF-8
# This is useful because Mercurial and Git treat UTF-16 as binary and can't
# diff/merge them. For use on iPhone you can run an iconv script during build to
# convert back to UTF-16 (Mac OS X will happily use UTF-8 .strings files).
# - Clean up .old and .new files once we're done
# Modified by Pierre Dulac 2012 http://friendcashapp.com
# Changes
# - use logging instead of print
# Adds
# - MIT Licence
# - the first parameter in the command line to specify the path of *.lproj directories
# - an optional paramter to control the debug level (set to info by default)
# Fixes
# - do not convert a file if it is already in utf-8
# - allow multiline translations generated by genstrings by modifing the re_translation regex
# -
# MIT Licence
#
# Copyright (C) 2012 Pierre Dulac
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
# associated documentation files (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or substantial
# portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
# LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
from sys import argv
from codecs import open
from re import compile
from copy import copy
import os
import shutil
import optparse
import logging
logging.getLogger().level = logging.INFO
__version__ = "0.1"
__license__ = "MIT"
USAGE = "%prog [options] <url>"
VERSION = "%prog v" + __version__
re_translation = compile(r'^"((?:[^"]|\\")+)" = "((?:[^"]|\\")+)";(?:\n)?$')
re_comment_single = compile(r'^/\*.*\*/$')
re_comment_start = compile(r'^/\*.*$')
re_comment_end = compile(r'^.*\*/$')
class LocalizedString():
def __init__(self, comments, translation):
self.comments, self.translation = comments, translation
self.key, self.value = re_translation.match(self.translation).groups()
def __unicode__(self):
return u'%s%s\n' % (u''.join(self.comments), self.translation)
class LocalizedFile():
def __init__(self, fname=None, auto_read=False):
self.fname = fname
self.reset()
if auto_read:
self.read_from_file(fname)
def reset(self):
self.strings = []
self.strings_d = {}
def read_from_file(self, fname=None):
self.reset()
fname = self.fname if fname == None else fname
try:
#f = open(fname, encoding='utf_8', mode='r')
f = open(fname, encoding='utf_8', mode='r')
except:
print 'File %s does not exist.' % fname
exit(-1)
try:
line = f.readline()
logging.debug(line)
except:
logging.error("Can't read line for file: %s" % fname)
raise
i = 1
while line:
comments = [line]
if not re_comment_single.match(line):
while line and not re_comment_end.match(line):
line = f.readline()
comments.append(line)
line = f.readline()
i += 1
# handle multi lines
while len(line) > 1 and line[-2] != u';':
line += f.readline()
i += 1
logging.debug("%d %s" % (i, line.rstrip('\n')))
if line and re_translation.match(line):
translation = line
else:
logging.error("Line %d of file '%s' raising the exception: %s" % (i, self.fname, line))
raise Exception('invalid file')
line = f.readline()
i += 1
while line and line == u'\n':
line = f.readline()
i += 1
string = LocalizedString(comments, translation)
self.strings.append(string)
self.strings_d[string.key] = string
f.close()
def save_to_file(self, fname=None):
fname = self.fname if fname == None else fname
try:
f = open(fname, encoding='utf_8', mode='w')
except:
print 'Couldn\'t open file %s.' % fname
exit(-1)
# sort by key
self.strings.sort(key=lambda item: item.key)
for string in self.strings:
f.write(string.__unicode__())
f.close()
def merge_with(self, new):
merged = LocalizedFile()
for string in new.strings:
if self.strings_d.has_key(string.key):
new_string = copy(self.strings_d[string.key])
new_string.comments = string.comments
string = new_string
merged.strings.append(string)
merged.strings_d[string.key] = string
return merged
def update_with(self, new):
for string in new.strings:
if not self.strings_d.has_key(string.key):
self.strings.append(string)
self.strings_d[string.key] = string
def merge(merged_fname, old_fname, new_fname):
try:
old = LocalizedFile(old_fname, auto_read=True)
new = LocalizedFile(new_fname, auto_read=True)
merged = old.merge_with(new)
merged.save_to_file(merged_fname)
except Exception, inst:
logging.error('Error: input files have invalid format.')
raise
STRINGS_FILE = 'Localizable.strings'
def localize(path, excluded_paths):
languages = [os.path.join(path,name) for name in os.listdir(path) if name.endswith('.lproj') and os.path.isdir(os.path.join(path,name))]
print "languages found", languages
for language in languages:
original = merged = language + os.path.sep + STRINGS_FILE
old = original + '.old'
new = original + '.new'
if os.path.isfile(original):
try:
open(original, encoding='utf_8', mode='r').read()
os.rename(original, old)
except:
os.system('iconv -f UTF-16 -t UTF-8 "%s" > "%s"' % (original, old))
# gen
os.system('find %s -name \*.m -not -path "%s" | xargs genstrings -q -o "%s"' % (path, excluded_paths, language))
try:
open(original, encoding='utf_8', mode='r').read()
shutil.copy(original, new)
except:
os.system('iconv -f UTF-16 -t UTF-8 "%s" > "%s"' % (original, new))
# merge
merge(merged, old, new)
logging.info("Job done for language: %s" % language)
else:
os.system('genstrings -q -o "%s" `find %s -name "*.m" -not -path "%s"`' % (language, path, excluded_paths))
os.rename(original, old)
try:
open(old, encoding='utf_8', mode='r').read()
except:
os.system('iconv -f UTF-16 -t UTF-8 "%s" > "%s"' % (old, original))
if os.path.isfile(old):
os.remove(old)
if os.path.isfile(new):
os.remove(new)
def parse_options():
"""parse_options() -> opts, args
Parse any command-line options given returning both
the parsed options and arguments.
"""
parser = optparse.OptionParser(usage=USAGE, version=VERSION)
parser.add_option("-d", "--debug",
action="store_true", default=False, dest="debug",
help="Set to DEBUG the logging level (default to INFO)")
parser.add_option("-p", "--path",
action="store", type="str", default=os.getcwd(), dest="path",
help="Path (relative or absolute) to use for searching for *.lproj directories")
parser.add_option("-e", "--exclude",
action="store", type="str", default=None, dest="excluded_paths",
help="Regex for paths to exclude ex. ``./Folder1/*``")
opts, args = parser.parse_args()
return opts, args
if __name__ == '__main__':
opts, args = parse_options()
if opts.debug:
logging.getLogger().level = logging.DEBUG
if opts.path:
opts.path = os.path.realpath(opts.path)
if opts.excluded_paths:
opts.excluded_paths = os.path.realpath(opts.excluded_paths)
logging.info("Running the script on path %s" % opts.path)
localize(opts.path, opts.excluded_paths)
I use:
http://www.loc-suite.com
To only translate the new parts
I was having a similar issue. I changed a lot of keys for my NSLocalizedString-macros and was frightened that I'd ship the App with missing translations (didn't want to run through the whole App manually and check if everything's there either...).
I tried out the github project that Gabriella Petronella posted but I wasn't really that happy with it, so I wrote my own python module to accomplish what I wanted to do.
(I'm not gonna post the code here, since it's a whole module and not only one script :D)
Here is the couple of options you can chose to go with:
You can use some hand-written solution like the script mentioned above which will not completely rewrite the old files while adding a recently translated strings to them.
You can also create an additional strings.h file which will contain all the strings you do have so you will not need to rewrite them all the time, just in one place. So genstrings is not necessary anymore. However there is a con of using this: the string.h file will be unstructured which is probably not convenient for the big projects.
Thanks to Best practice using NSLocalizedString
// In strings.h
#define YOUR_STRING_KEY NSLocalizedString(#"Cancel", nil)
// Somewhere else in you code
NSLog(#"%#", YOUR_STRING_KEY);
I actually started using a tool called PhraseApp https://phraseapp.com/projects
It's worth looking into if you have to localise an app!

Running command line silently with VbScript and getting output?

I want to be able to run a program through command line and I want to start it with VbScript. I also want to get the output of the command line and assign it to a variable and I want all this to be done silently without cmd windows popping up. I have managed two things separately but not together. Here's what I got so far.
Run the command from cmd and get output:
Dim WshShell, oExec
Set WshShell = WScript.CreateObject("WScript.Shell")
Set oExec = WshShell.Exec("C:\snmpget -c public -v 2c 10.1.1.2 .1.3.6.1.4.1.6798.3.1.1.1.5.1")
x = oExec.StdOut.ReadLine
Wscript.Echo x
The above script works and does what I want except that cmd pops up for a brief moment.
Here's a script that will run silently but won't grab the output
Set WshShell = WScript.CreateObject("WScript.Shell")
Return = WshShell.Run("C:\snmpset -c public -v 2c -t 0 10.1.1.2 .1.3.6.1.4.1.6798.3.1.1.1.7.1 i 1", 0, true)
Is there a way to get these two to work together?
Let me give you a background on why I want do to this. I am basically polling a unit every 5-10 minutes and I am going to get the script to email or throw a message box when a certain condition occurs but I don't want to see cmd line popping up all day long on my computer. Any suggestions?
Thanks
You can redirect output to a file and then read the file:
return = WshShell.Run("cmd /c C:\snmpset -c ... > c:\temp\output.txt", 0, true)
Set fso = CreateObject("Scripting.FileSystemObject")
Set file = fso.OpenTextFile("c:\temp\output.txt", 1)
text = file.ReadAll
file.Close
I have taken this and various other comments and created a bit more advanced function for running an application and getting the output.
Example to Call Function: Will output the DIR list of C:\ for Directories only. The output will be returned to the variable CommandResults as well as remain in C:\OUTPUT.TXT.
CommandResults = vFn_Sys_Run_CommandOutput("CMD.EXE /C DIR C:\ /AD",1,1,"C:\OUTPUT.TXT",0,1)
Function
Function vFn_Sys_Run_CommandOutput (Command, Wait, Show, OutToFile, DeleteOutput, NoQuotes)
'Run Command similar to the command prompt, for Wait use 1 or 0. Output returned and
'stored in a file.
'Command = The command line instruction you wish to run.
'Wait = 1/0; 1 will wait for the command to finish before continuing.
'Show = 1/0; 1 will show for the command window.
'OutToFile = The file you wish to have the output recorded to.
'DeleteOutput = 1/0; 1 deletes the output file. Output is still returned to variable.
'NoQuotes = 1/0; 1 will skip wrapping the command with quotes, some commands wont work
' if you wrap them in quotes.
'----------------------------------------------------------------------------------------
On Error Resume Next
'On Error Goto 0
Set f_objShell = CreateObject("Wscript.Shell")
Set f_objFso = CreateObject("Scripting.FileSystemObject")
Const ForReading = 1, ForWriting = 2, ForAppending = 8
'VARIABLES
If OutToFile = "" Then OutToFile = "TEMP.TXT"
tCommand = Command
If Left(Command,1)<>"""" And NoQuotes <> 1 Then tCommand = """" & Command & """"
tOutToFile = OutToFile
If Left(OutToFile,1)<>"""" Then tOutToFile = """" & OutToFile & """"
If Wait = 1 Then tWait = True
If Wait <> 1 Then tWait = False
If Show = 1 Then tShow = 1
If Show <> 1 Then tShow = 0
'RUN PROGRAM
f_objShell.Run tCommand & ">" & tOutToFile, tShow, tWait
'READ OUTPUT FOR RETURN
Set f_objFile = f_objFso.OpenTextFile(OutToFile, 1)
tMyOutput = f_objFile.ReadAll
f_objFile.Close
Set f_objFile = Nothing
'DELETE FILE AND FINISH FUNCTION
If DeleteOutput = 1 Then
Set f_objFile = f_objFso.GetFile(OutToFile)
f_objFile.Delete
Set f_objFile = Nothing
End If
vFn_Sys_Run_CommandOutput = tMyOutput
If Err.Number <> 0 Then vFn_Sys_Run_CommandOutput = "<0>"
Err.Clear
On Error Goto 0
Set f_objFile = Nothing
Set f_objShell = Nothing
End Function
I am pretty new to all of this, but I found that if the script is started via CScript.exe (console scripting host) there is no window popping up on exec(): so when running:
cscript myscript.vbs //nologo
any .Exec() calls in the myscript.vbs do not open an extra window, meaning
that you can use the first variant of your original solution (using exec).
(Note that the two forward slashes in the above code are intentional, see cscript /?)
Here I found a solution, which works for me:
set wso = CreateObject("Wscript.Shell")
set exe = wso.Exec("cmd /c dir /s /b d:\temp\*.jpg")
sout = exe.StdOut.ReadAll
Look for assigning the output to Clipboard (in your first script) and then in second script parse Clipboard value.
#Mark Cidade
Thanks Mark! This solved few days of research on wondering how should I call this from the PHP WshShell. So thanks to your code, I figured...
function __exec($tmppath, $cmd)
{
$WshShell = new COM("WScript.Shell");
$tmpf = rand(1000, 9999).".tmp"; // Temp file
$tmpfp = $tmppath.'/'.$tmpf; // Full path to tmp file
$oExec = $WshShell->Run("cmd /c $cmd -c ... > ".$tmpfp, 0, true);
// return $oExec == 0 ? true : false; // Return True False after exec
return $tmpf;
}
This is what worked for me in my case. Feel free to use and modify as per your needs. You can always add functionality within the function to automatically read the tmp file, assign it to a variable and/or return it and then delete the tmp file.
Thanks again #Mark!
Dim path As String = GetFolderPath(SpecialFolder.ApplicationData)
Dim filepath As String = path + "\" + "your.bat"
' Create the file if it does not exist.
If File.Exists(filepath) = False Then
File.Create(filepath)
Else
End If
Dim attributes As FileAttributes
attributes = File.GetAttributes(filepath)
If (attributes And FileAttributes.ReadOnly) = FileAttributes.ReadOnly Then
' Remove from Readonly the file.
attributes = RemoveAttribute(attributes, FileAttributes.ReadOnly)
File.SetAttributes(filepath, attributes)
Console.WriteLine("The {0} file is no longer RO.", filepath)
Else
End If
If (attributes And FileAttributes.Hidden) = FileAttributes.Hidden Then
' Show the file.
attributes = RemoveAttribute(attributes, FileAttributes.Hidden)
File.SetAttributes(filepath, attributes)
Console.WriteLine("The {0} file is no longer Hidden.", filepath)
Else
End If
Dim sr As New StreamReader(filepath)
Dim input As String = sr.ReadToEnd()
sr.Close()
Dim output As String = "#echo off"
Dim output1 As String = vbNewLine + "your 1st cmd code"
Dim output2 As String = vbNewLine + "your 2nd cmd code "
Dim output3 As String = vbNewLine + "exit"
Dim sw As New StreamWriter(filepath)
sw.Write(output)
sw.Write(output1)
sw.Write(output2)
sw.Write(output3)
sw.Close()
If (attributes And FileAttributes.Hidden) = FileAttributes.Hidden Then
Else
' Hide the file.
File.SetAttributes(filepath, File.GetAttributes(filepath) Or FileAttributes.Hidden)
Console.WriteLine("The {0} file is now hidden.", filepath)
End If
Dim procInfo As New ProcessStartInfo(path + "\" + "your.bat")
procInfo.WindowStyle = ProcessWindowStyle.Minimized
procInfo.WindowStyle = ProcessWindowStyle.Hidden
procInfo.CreateNoWindow = True
procInfo.FileName = path + "\" + "your.bat"
procInfo.Verb = "runas"
Process.Start(procInfo)
it saves your .bat file to "Appdata of current user" ,if it does not exist and remove the attributes
and after that set the "hidden" attributes to file after writing your cmd code
and run it silently and capture all output saves it to file
so if u wanna save all output of cmd to file just add your like this
code > C:\Users\Lenovo\Desktop\output.txt
just replace word "code" with your .bat file code or command and after that the directory of output file
I found one code recently after searching alot
if u wanna run .bat file in vb or c# or simply
just add this in the same manner in which i have written