I have a octave script (script.m) file with the following code:
if length(argv()) > 0
s = argv(){1};
else
s = "";
In octave command window, pwd is set to the script directory. From command window, how can I run script.m with one, two or no arguments?
I am using Octave (GUI) in windows.
An endif is missing at the end but here we go:
if length(argv()) > 0
s = argv(){1};
else
s = "";
endif
s
With no argument:
$ octave script.m
s =
With one argument:
$ octave script.m foobar
s = foobar
With two arguments (the second goes to nirvana because you don't use it in your script):
$ octave script.m foobar baz
s = foobar
Related
I tried to run the example code available here: http://simula.stanford.edu/~alizade/Site/DCTCP_files/dctcp-ns2-rev1.0.tar.gz
As per the readme file, the patch was successfully applied but on executing the example code, the following error was obtained:
ns: myTrace file3: can't read "dctcp_alpha_": no such variable
while executing
"subst $[subst $var]"
(procedure "_o154" line 5)
(Object next line 5)
invoked from within
"_o154 next dctcp_alpha_"
("eval" body line 1)
invoked from within
"eval $self next $args"
(procedure "_o154" line 18)
(Agent set line 18)
invoked from within
"$tcp($i) set dctcp_alpha_"
(procedure "myTrace" line 8)
invoked from within
"myTrace file3"
How could this be solved?
Build example : tar xvf ns-allinone-2.35_gcc482.tar.gz
https://drive.google.com/file/d/0B7S255p3kFXNSGJCZ2YzUGJDVk0/view?usp=sharing
cd ns-allinone-2.35/ns-2.35/
patch -p1 --ignore-whitespace -i dctcp.patch
cd ../
./install
cd ns-2.35/
sudo make install
cp ns ns235-dctcp
sudo cp ns235-dctcp /usr/local/bin/
Run the simulation : ns235-dctcp simpleDumbbell.tcl
.. The files mytracefile.tr 2.1MB, thrfile.tr 10.2kB are created. ( And queue.tr : 0B ).
Your errors : You are probably using a wrong executabe 'ns'.
The safe way is a copy of the DCTCP patched 'ns', with a new name.
And with a location in a system PATH, like /usr/local/bin/ns235-dctcp
-
I used to have exactly the same problem as you mentioned:
ns: myTrace file3: can't read "dctcp_alpha_": no such variable
while executing
st $[subst $var]"
(procedure "_o154" line 5)
(Object next line 5)
invoked from within
...
1.The problem is you needs to compile after running the patch.
as Knud Larsen mentioned in his answer, after running following patch:
cd ns-allinone-2.35/ns-2.35/
patch -p1 --ignore-whitespace -i dctcp.patch
You need to go to the /ns-allinone-2.35/ folder, and do the compiling:
cd ../
./install
cd ns-2.35/
sudo make install
Different from Knud Larsen, I did not rename another ns. I run the simulation directly with ns command:
ns simpleDumbbell.tcl
And it works for me.
Hope this helps : )
ns: _o83 selfish:
(_o83 cmd line 1)
invoked from within
"_o83 cmd selfish"
invoked from within
"catch "$self cmd $args" ret"
invoked from within
"if [catch "$self cmd $args" ret] {
set cls [$self info class]
global errorInfo
set savedInfo $errorInfo
error "error when calling class $cls: $args" $..."
(procedure "_o83" line 2)
(SplitObject unknown line 2)
invoked from within
"_o83 selfish"
I am running a program and want to see what its return code is (since it returns different codes based on different errors).
I know in Bash I can do this by running
echo $?
What do I do when using cmd.exe on Windows?
The "exit code" is stored in a shell variable named errorlevel.
The errorlevel is set at the end of a console application. Windows applications behave a little differently; see #gary's answer below.
Use the if command keyword errorlevel for comparison:
if errorlevel <n> (<statements>)
Which will execute statements when the errorlevel is greater than or equal to n. Execute if /? for details.
A shell variable named errorlevel contains the value as a string and can be dereferenced by wrapping with %'s.
Example script:
my_nifty_exe.exe
rem Give resolution instructions for known exit codes.
rem Ignore exit code 1.
rem Otherwise give a generic error message.
if %errorlevel%==7 (
echo "Replace magnetic tape."
) else if %errorlevel%==3 (
echo "Extinguish the printer."
) else if errorlevel 2 (
echo Unknown Error: %errorlevel% refer to Run Book documentation.
) else (
echo "Success!"
)
Warning: An environment variable named errorlevel, if it exists, will override the shell variable named errorlevel. if errorlevel tests are not affected.
Testing ErrorLevel works for console applications, but as hinted at by dmihailescu, this won't work if you're trying to run a windowed application (e.g. Win32-based) from a command prompt. A windowed application will run in the background, and control will return immediately to the command prompt (most likely with an ErrorLevel of zero to indicate that the process was created successfully). When a windowed application eventually exits, its exit status is lost.
Instead of using the console-based C++ launcher mentioned elsewhere, though, a simpler alternative is to start a windowed application using the command prompt's START /WAIT command. This will start the windowed application, wait for it to exit, and then return control to the command prompt with the exit status of the process set in ErrorLevel.
start /wait something.exe
echo %errorlevel%
Use the built-in ERRORLEVEL Variable:
echo %ERRORLEVEL%
But beware if an application has defined an environment variable named ERRORLEVEL!
If you want to match the error code exactly (eg equals 0), use this:
#echo off
my_nify_exe.exe
if %ERRORLEVEL% EQU 0 (
echo Success
) else (
echo Failure Reason Given is %errorlevel%
exit /b %errorlevel%
)
Note that if errorlevel 0 matches errorlevel >= 0.
See if /?.
Or, if you don't handle success:
if %ERRORLEVEL% NEQ 0 (
echo Failed with exit-code: %errorlevel%
exit /b %errorlevel%
)
It's worth noting that .BAT and .CMD files operate differently.
Reading https://ss64.com/nt/errorlevel.html it notes the following:
There is a key difference between the way .CMD and .BAT batch files set errorlevels:
An old .BAT batch script running the 'new' internal commands: APPEND, ASSOC, PATH, PROMPT, FTYPE and SET will only set ERRORLEVEL if an error occurs. So if you have two commands in the batch script and the first fails, the ERRORLEVEL will remain set even after the second command succeeds.
This can make debugging a problem BAT script more difficult, a CMD batch script is more consistent and will set ERRORLEVEL after every command that you run [source].
This was causing me no end of grief as I was executing successive commands, but the ERRORLEVEL would remain unchanged even in the event of a failure.
It might not work correctly when using a program that is not attached to the console, because that app might still be running while you think you have the exit code.
A solution to do it in C++ looks like below:
#include "stdafx.h"
#include "windows.h"
#include "stdio.h"
#include "tchar.h"
#include "stdio.h"
#include "shellapi.h"
int _tmain( int argc, TCHAR *argv[] )
{
CString cmdline(GetCommandLineW());
cmdline.TrimLeft('\"');
CString self(argv[0]);
self.Trim('\"');
CString args = cmdline.Mid(self.GetLength()+1);
args.TrimLeft(_T("\" "));
printf("Arguments passed: '%ws'\n",args);
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
if( argc < 2 )
{
printf("Usage: %s arg1,arg2....\n", argv[0]);
return -1;
}
CString strCmd(args);
// Start the child process.
if( !CreateProcess( NULL, // No module name (use command line)
(LPTSTR)(strCmd.GetString()), // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
0, // No creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi ) // Pointer to PROCESS_INFORMATION structure
)
{
printf( "CreateProcess failed (%d)\n", GetLastError() );
return GetLastError();
}
else
printf( "Waiting for \"%ws\" to exit.....\n", strCmd );
// Wait until child process exits.
WaitForSingleObject( pi.hProcess, INFINITE );
int result = -1;
if(!GetExitCodeProcess(pi.hProcess,(LPDWORD)&result))
{
printf("GetExitCodeProcess() failed (%d)\n", GetLastError() );
}
else
printf("The exit code for '%ws' is %d\n",(LPTSTR)(strCmd.GetString()), result );
// Close process and thread handles.
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
return result;
}
At one point I needed to accurately push log events from Cygwin to the Windows Event log. I wanted the messages in WEVL to be custom, have the correct exit code, details, priorities, message, etc. So I created a little Bash script to take care of this. Here it is on GitHub, logit.sh.
Some excerpts:
usage: logit.sh [-h] [-p] [-i=n] [-s] <description>
example: logit.sh -p error -i 501 -s myscript.sh "failed to run the mount command"
Here is the temporary file contents part:
LGT_TEMP_FILE="$(mktemp --suffix .cmd)"
cat<<EOF>$LGT_TEMP_FILE
#echo off
set LGT_EXITCODE="$LGT_ID"
exit /b %LGT_ID%
EOF
unix2dos "$LGT_TEMP_FILE"
Here is a function to to create events in WEVL:
__create_event () {
local cmd="eventcreate /ID $LGT_ID /L Application /SO $LGT_SOURCE /T $LGT_PRIORITY /D "
if [[ "$1" == *';'* ]]; then
local IFS=';'
for i in "$1"; do
$cmd "$i" &>/dev/null
done
else
$cmd "$LGT_DESC" &>/dev/null
fi
}
Executing the batch script and calling on __create_event:
cmd /c "$(cygpath -wa "$LGT_TEMP_FILE")"
__create_event
I have following code of Powershell where i am trying to sort lastest backup file of mysql database and then try to import this file
I am using the Powershell script for this according to script till the last i get desired o/p and then i copy this o/p and execute in seprate
cmd window it execute smooth but in power shell when i try to do the same thing it fails with following error please help me
Error message
C:\wamp\bin\mysql\mysql5.5.24\bin\mysql.exe --user=root --password=xxx testdest < "C:\mysqltemp\testsrc_2013-12-23_10-46-AM.sql"
cmd.exe : The system cannot find the file specified.
At C:\Users\IBM_ADMIN\AppData\Local\Temp\8a7b4576-97b2-42aa-a0eb-42bb934833a6.ps1:19 char:4
+ cmd <<<< /c " "$pathtomysqldump" --user=$param1 --password=$param2 $param3 < $param5 "
+ CategoryInfo : NotSpecified: (The system cann...file specified.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
Script is as following
##Select latest file created by Export of mysql dumper
$a=(get-childitem C:\mysqltemp | sort LastWriteTime -Descending | Select-Object Name | select -first 1 -ExpandProperty Name)
$pathtomysqldump = "C:\wamp\bin\mysql\mysql5.5.24\bin\mysql.exe"
#Write-Host "Print variable A -------------"
#$a
$a=$a.Replace(" ", "")
#Write-Host "After Triming ---------------"
#$a
$param1="root"
$param2="xxx"
$param3="testdest"
#$param4="""'<'"""
$param5="""C:\mysqltemp\$a"""
#$p1="$param1 $param2 $param3 < $param5"
# Invoke backup Command. /c forces the system to wait to do the backup
Write-Host " "$pathtomysqldump" --user=$param1 --password=$param2 $param3 < $param5 "
cmd /c " "$pathtomysqldump" --user=$param1 --password=$param2 $param3 < $param5 "
Thanks and Appreciate your help and time for the same.
This is a common misunderstanding involving calling command lines in the Windows operating system, particularly from PowerShell.
I highly recommend using the Start-Process cmdlet to launch a process instead of calling cmd.exe. It's much easier to mentally parse out and understand the path to the executable, and all of the command line parameters separately. The problem with your current script is that you're trying to call an executable file with the following name: C:\wamp\bin\mysql\mysql5.5.24\bin\mysql.exe --user=root --password=xxx testdest < "C:\mysqltemp\testsrc_2013-12-23_10-46-AM.sql", which has been wrapped in a call to cmd.exe. Obviously, that file does not exist, because you're including all of the parameters as part of the filesystem path.
There are too many layers going on here to make it simple to understand. Instead, use Start-Process similar to the following example:
# 1. Define path to mysql.exe
$MySQL = "C:\wamp\bin\mysql\mysql5.5.24\bin\mysql.exe"
# 2. Define some parameters
$Param1 = 'value1';
$Param2 = 'value2';
$Param3 = 'value 3 with spaces';
# 3. Build the command line arguments
# NOTE: Since the value of $Param3 has spaces in it, we must
# surround the value with double quotes in the command line
$ArgumentList = '--user={0} --password={1} "{2}"' -f $Param1, $Param2, $Param3;
Write-Host -Object "Arguments are: $ArgumentList";
# 4. Call Start-Process
# NOTE: The -Wait parameter tells it to "wait"
# The -NoNewWindow parameter prevents a new window from popping up
# for the process.
Start-Process -FilePath $MySQL -ArgumentList $ArgumentList -Wait -NoNewWindow;
I would like to export a variable depending on result of a binary command. My TCL script is this:
set A ""
exec sh -c "export A=\"`/usr/local/cuda/samples/1_Utilities/deviceQuery/deviceQuery -noprompt | grep ^Device | wc -l`\""
puts $A
if { $A == "1" } {
set CUDA_VISIBLES_DEVICES 0
} else {
set CUDA_VISIBLES_DEVICES 1
}
With this script, when I execute puts $A I don't get anything in terminal... so in if command I don't know what I evaluating...
My "export" must return ONLY 1 or 0...
Sorry about my poor TCL level.
Thanks.
I guess what you want is something like this:
set a [exec /usr/local/cuda/samples/1_Utilities/deviceQuery/deviceQuery -noprompt | grep ^Device | wc -l]
You set variable a in TCL context and assign the command's return value (i.e. the output text) to it.
The problem is that your exec'd command runs in its own process, so when you set a variable A, that A only exists as a shell variable for the life of that process. When the process exits, A goes away.
The exec command returns the stdout of the command that was exec'd. If you want the result of the command to be in a Tcl variable, you need to set the variable to be the result of the exec:
set A [exec ...]
For more information on the exec command, see the exec man page.
I'm trying to write a zsh function to get the path to a python module.
This works:
pywhere() {
python -c "import $1; print $1.__file__"
}
However, what I'd really like is the dir path without the filename. This doesn't work:
pywhere() {
dirname $(python -c "import $1; print $1.__file__")
}
Note: it works in bash, but not in zsh!
EDIT this is the error:
~ % pywhere() {
function → dirname $(python -c "import $1; print $1.__file__")
function → }
File "<string>", line 1
import pywhere() {
^
SyntaxError: invalid syntax
Your problem is due to a broken preexec: you aren't quoting the command line properly when you print it for inclusion in the window title.
In the .zshrc you posted, which is not the one you used (don't do that! Always copy-paste the exact file contents and commands that you used), I see:
a=${(V)1//\%/\%\%}
a=$(print -Pn "%40>...>$a" | tr -d "\n")
print -Pn "\ek$a:$3\e\\"
print -P causes prompt expansion. You include the command in the argument. You protect the % characters in the command by doubling them, but that's not enough. You evidently have the prompt_subst option turned on, so print -P causes the $(…) construct in the command line that defines the function to be executed:
python -c "import $1; print $1.__file__"
where $1 is the command line (the function definition: pywhere { … }).
Rather than attempt to parse the command line, print it out literally. This'll also correct other mistakes: beyond not taking prompt_subst into account, you doubled % signs but should have quadrupled them since you perform prompt expansion twice, and you expand \ sequences twice as well.
function title() {
a=${(q)1} # show control characters as escape sequences
if [[ $#a -gt 40 ]]; then a=$a[1,37]...; fi
case $TERM in
screen)
print -Pn "\ek"; print -r -- $a; print -Pn ":$3\e\\";;
xterm*|rxvt)
print -Pn "\e]2;$2 | "; print -r -- $a; print -Pn ":$3\a";;
esac
}
Why not just use this:
python -c "import os, $1; print os.path.dirname($1.__file__)"