How do I make intellij Idea to highlight Scala script correctly with #! (shebang) - linux

How do I make intellij Idea to highlight Scala script correctly.
Attempt 1
change filename to 'test.sc' . Intellij does not like the first line i.e it is not valid scala comment syntax
Attempt 2
change filename to 'test.sh' . Intellij thinks all of the syntax is bash script.
filenName = ./test.sh
#!/usr/bin/env amm
import ammonite.ops._ , ImplicitWd._
println("Stop script")
val x = 1 + 1

If you need to preserve .sc extension here is a little trick
change shebang to #! /usr/bin/env amm which is still a valid shebang
put a file named #!.scala next to your script with the content:
class CLZ {
def /(that: CLZ): CLZ = this
def amm: Unit = {}
}
object #! extends CLZ
object usr extends CLZ
object bin extends CLZ
object env extends CLZ
Now, your script is properly highlighted
Update
JetBrains published a blog article about support for Ammonite.

If you have a .scala extension, IDEA recognizes as a valid Scala script file.
Even a multiline shebang line is supported:
#!/bin/sh
DIR=$(cd `dirname "${BASH_SOURCE[0]}"` && pwd)
exec scala -classpath $DIR/scalaj-http_2.11-2.3.0.jar -savecompiled "$0" "$#"
!#
/* Scala code*/
Make sure:
you are using a relatively recent version of IDEA.
Scala plugin is installed.
The script lies in a Scala module.
It works even if the script is outside of a declared source folder.
I can even edit scripts outside of my project.

Related

how to get a variable of a python file from bash script

I have a python file, conf.py which is used to store configuration variables. conf.py is given below:
import os
step_number=100
I have a bash script runner.sh which tries to reach the variables from conf.py:
#! /bin/bash
#get step_number from conf file
step_number_=$(python ./conf.py step_number)
However, if I try to print the step_number_ with echo $step_number_, it returns empty value. Can you please help me to fix it?
$(command) is replaced with the standard output of the command. So the Python script needs to print the variable so you can substitute it this way.
import os
step_number = 100
print(step_number)

Is there a way to know how the user invoked a program from bash?

Here's the problem: I have this script foo.py, and if the user invokes it without the --bar option, I'd like to display the following error message:
Please add the --bar option to your command, like so:
python foo.py --bar
Now, the tricky part is that there are several ways the user might have invoked the command:
They may have used python foo.py like in the example
They may have used /usr/bin/foo.py
They may have a shell alias frob='python foo.py', and actually ran frob
Maybe it's even a git alias flab=!/usr/bin/foo.py, and they used git flab
In every case, I'd like the message to reflect how the user invoked the command, so that the example I'm providing would make sense.
sys.argv always contains foo.py, and /proc/$$/cmdline doesn't know about aliases. It seems to me that the only possible source for this information would be bash itself, but I don't know how to ask it.
Any ideas?
UPDATE How about if we limit possible scenarios to only those listed above?
UPDATE 2: Plenty of people wrote very good explanation about why this is not possible in the general case, so I would like to limit my question to this:
Under the following assumptions:
The script was started interactively, from bash
The script was start in one of these 3 ways:
foo <args> where foo is a symbolic link /usr/bin/foo -> foo.py
git foo where alias.foo=!/usr/bin/foo in ~/.gitconfig
git baz where alias.baz=!/usr/bin/foo in ~/.gitconfig
Is there a way to distinguish between 1 and (2,3) from within the script? Is there a way to distinguish between 2 and 3 from within the script?
I know this is a long shot, so I'm accepting Charles Duffy's answer for now.
UPDATE 3: So far, the most promising angle was suggested by Charles Duffy in the comments below. If I can get my users to have
trap 'export LAST_BASH_COMMAND=$(history 1)' DEBUG
in their .bashrc, then I can use something like this in my code:
like_so = None
cmd = os.environ['LAST_BASH_COMMAND']
if cmd is not None:
cmd = cmd[8:] # Remove the history counter
if cmd.startswith("foo "):
like_so = "foo --bar " + cmd[4:]
elif cmd.startswith(r"git foo "):
like_so = "git foo --bar " + cmd[8:]
elif cmd.startswith(r"git baz "):
like_so = "git baz --bar " + cmd[8:]
if like_so is not None:
print("Please add the --bar option to your command, like so:")
print(" " + like_so)
else:
print("Please add the --bar option to your command.")
This way, I show the general message if I don't manage to get their invocation method. Of course, if I'm going to rely on changing my users' environment I might as well ensure that the various aliases export their own environment variables that I can look at, but at least this way allows me to use the same technique for any other script I might add later.
No, there is no way to see the original text (before aliases/functions/etc).
Starting a program in UNIX is done as follows at the underlying syscall level:
int execve(const char *path, char *const argv[], char *const envp[]);
Notably, there are three arguments:
The path to the executable
An argv array (the first item of which -- argv[0] or $0 -- is passed to that executable to reflect the name under which it was started)
A list of environment variables
Nowhere in here is there a string that provides the original user-entered shell command from which the new process's invocation was requested. This is particularly true since not all programs are started from a shell at all; consider the case where your program is started from another Python script with shell=False.
It's completely conventional on UNIX to assume that your program was started through whatever name is given in argv[0]; this works for symlinks.
You can even see standard UNIX tools doing this:
$ ls '*.txt' # sample command to generate an error message; note "ls:" at the front
ls: *.txt: No such file or directory
$ (exec -a foobar ls '*.txt') # again, but tell it that its name is "foobar"
foobar: *.txt: No such file or directory
$ alias somesuch=ls # this **doesn't** happen with an alias
$ somesuch '*.txt' # ...the program still sees its real name, not the alias!
ls: *.txt: No such file
If you do want to generate a UNIX command line, use pipes.quote() (Python 2) or shlex.quote() (Python 3) to do it safely.
try:
from pipes import quote # Python 2
except ImportError:
from shlex import quote # Python 3
cmd = ' '.join(quote(s) for s in open('/proc/self/cmdline', 'r').read().split('\0')[:-1])
print("We were called as: {}".format(cmd))
Again, this won't "un-expand" aliases, revert to the code that was invoked to call a function that invoked your command, etc; there is no un-ringing that bell.
That can be used to look for a git instance in your parent process tree, and discover its argument list:
def find_cmdline(pid):
return open('/proc/%d/cmdline' % (pid,), 'r').read().split('\0')[:-1]
def find_ppid(pid):
stat_data = open('/proc/%d/stat' % (pid,), 'r').read()
stat_data_sanitized = re.sub('[(]([^)]+)[)]', '_', stat_data)
return int(stat_data_sanitized.split(' ')[3])
def all_parent_cmdlines(pid):
while pid > 0:
yield find_cmdline(pid)
pid = find_ppid(pid)
def find_git_parent(pid):
for cmdline in all_parent_cmdlines(pid):
if cmdline[0] == 'git':
return ' '.join(quote(s) for s in cmdline)
return None
See the Note at the bottom regarding the originally proposed wrapper script.
A new more flexible approach is for the python script to provide a new command line option, permitting users to specify a custom string they would prefer to see in error messages.
For example, if a user prefers to call the python script 'myPyScript.py' via an alias, they can change the alias definition from this:
alias myAlias='myPyScript.py $#'
to this:
alias myAlias='myPyScript.py --caller=myAlias $#'
If they prefer to call the python script from a shell script, it can use the additional command line option like so:
#!/bin/bash
exec myPyScript.py "$#" --caller=${0##*/}
Other possible applications of this approach:
bash -c myPyScript.py --caller="bash -c myPyScript.py"
myPyScript.py --caller=myPyScript.py
For listing expanded command lines, here's a script 'pyTest.py', based on feedback by #CharlesDuffy, that lists cmdline for the running python script, as well as the parent process that spawned it.
If the new -caller argument is used, it will appear in the command line, although aliases will have been expanded, etc.
#!/usr/bin/env python
import os, re
with open ("/proc/self/stat", "r") as myfile:
data = [x.strip() for x in str.split(myfile.readlines()[0],' ')]
pid = data[0]
ppid = data[3]
def commandLine(pid):
with open ("/proc/"+pid+"/cmdline", "r") as myfile:
return [x.strip() for x in str.split(myfile.readlines()[0],'\x00')][0:-1]
pid_cmdline = commandLine(pid)
ppid_cmdline = commandLine(ppid)
print "%r" % pid_cmdline
print "%r" % ppid_cmdline
After saving this to a file named 'pytest.py', and then calling it from a bash script called 'pytest.sh' with various arguments, here's the output:
$ ./pytest.sh a b "c d" e
['python', './pytest.py']
['/bin/bash', './pytest.sh', 'a', 'b', 'c d', 'e']
NOTE: criticisms of the original wrapper script aliasTest.sh were valid. Although the existence of a pre-defined alias is part of the specification of the question, and may be presumed to exist in the user environment, the proposal defined the alias (creating the misleading impression that it was part of the recommendation rather than a specified part of the user's environment), and it didn't show how the wrapper would communicate with the called python script. In practice, the user would either have to source the wrapper or define the alias within the wrapper, and the python script would have to delegate the printing of error messages to multiple custom calling scripts (where the calling information resided), and clients would have to call the wrapper scripts. Solving those problems led to a simpler approach, that is expandable to any number of additional use cases.
Here's a less confusing version of the original script, for reference:
#!/bin/bash
shopt -s expand_aliases
alias myAlias='myPyScript.py'
# called like this:
set -o history
myAlias $#
_EXITCODE=$?
CALL_HISTORY=( `history` )
_CALLING_MODE=${CALL_HISTORY[1]}
case "$_EXITCODE" in
0) # no error message required
;;
1)
echo "customized error message #1 [$_CALLING_MODE]" 1>&2
;;
2)
echo "customized error message #2 [$_CALLING_MODE]" 1>&2
;;
esac
Here's the output:
$ aliasTest.sh 1 2 3
['./myPyScript.py', '1', '2', '3']
customized error message #2 [myAlias]
There is no way to distinguish between when an interpreter for a script is explicitly specified on the command line and when it is deduced by the OS from the hashbang line.
Proof:
$ cat test.sh
#!/usr/bin/env bash
ps -o command $$
$ bash ./test.sh
COMMAND
bash ./test.sh
$ ./test.sh
COMMAND
bash ./test.sh
This prevents you from detecting the difference between the first two cases in your list.
I am also confident that there is no reasonable way of identifying the other (mediated) ways of calling a command.
I can see two ways to do this:
The simplest, as suggested by 3sky, would be to parse the command line from inside the python script. argparse can be used to do so in a reliable way. This only works if you can change that script.
A more complex way, slightly more generic and involved, would be to change the python executable on your system.
Since the first option is well documented, here are a bit more details on the second one:
Regardless of the way your script is called, python is ran. The goal here is to replace the python executable with a script that checks if foo.py is among the arguments, and if it is, check if --bar is as well. If not, print the message and return.
In every other case, execute the real python executable.
Now, hopefully, running python is done trough the following shebang: #!/usr/bin/env python3, or trough python foo.py, rather than a variant of #!/usr/bin/python or /usr/bin/python foo.py. That way, you can change the $PATH variable, and prepend a directory where your false python resides.
In the other case, you can replace the /usr/bin/python executable, at the risk of not playing nice with updates.
A more complex way of doing this would probably be with namespaces and mounts, but the above is probably enough, especially if you have admin rights.
Example of what could work as a script:
#!/usr/bin/env bash
function checkbar
{
for i in "$#"
do
if [ "$i" = "--bar" ]
then
echo "Well done, you added --bar!"
return 0
fi
done
return 1
}
command=$(basename ${1:-none})
if [ $command = "foo.py" ]
then
if ! checkbar "$#"
then
echo "Please add --bar to the command line, like so:"
printf "%q " $0
printf "%q " "$#"
printf -- "--bar\n"
exit 1
fi
fi
/path/to/real/python "$#"
However, after re-reading your question, it is obvious that I misunderstood it. In my opinion, it is all right to just print either "foo.py must be called like foo.py --bar", "please add bar to your arguments" or "please try (instead of )", regardless of what the user entered:
If that's an (git) alias, this is a one time error, and the user will try their alias after creating it, so they know where to put the --bar part
with either with /usr/bin/foo.py or python foo.py:
If the user is not really command line-savvy, they can just paste the working command that is displayed, even if they don't know the difference
If they are, they should be able to understand the message without trouble, and adjust their command line.
I know it's bash task, but i think the easiest way is modify 'foo.py'. Of course it depends on level of script complicated, but maybe it will fit. Here is sample code:
#!/usr/bin/python
import sys
if len(sys.argv) > 1 and sys.argv[1] == '--bar':
print 'make magic'
else:
print 'Please add the --bar option to your command, like so:'
print ' python foo.py --bar'
In this case, it does not matter how user run this code.
$ ./a.py
Please add the --bar option to your command, like so:
python foo.py --bar
$ ./a.py -dua
Please add the --bar option to your command, like so:
python foo.py --bar
$ ./a.py --bar
make magic
$ python a.py --t
Please add the --bar option to your command, like so:
python foo.py --bar
$ /home/3sky/test/a.py
Please add the --bar option to your command, like so:
python foo.py --bar
$ alias a='python a.py'
$ a
Please add the --bar option to your command, like so:
python foo.py --bar
$ a --bar
make magic

can someone tell what this code snippet does

I am trying to understand this below mentioned code snippet, currently i am stuck at line number 3 and after digging alot i got to know that $MYPERL is where perl binaries are defined/located and for $PERLDB is what perl debugger i,e -d:ptkdb and basically this is a perl script and some how person who coded this wrapps it to use the latest perl version. can some one tell me how i can change MYPERL variable value /home/Desktop/goudar/perl/ and execute rest of the script ?
#!/bin/sh
# -*- cperl -*-
exec $MYPERL -x $PERLDB -wS $0 ${1+"$#"}
#!perl
#line 6
### perl
use Cwd;
use Data::Dumper;
use List::MoreUtils qw/ uniq /;
use JSON;
use Mojo::JSON;
#rest of the code go here#
can someone tell what this code snippet does
It executes the embedded Perl script using the Perl interpreter specified by env var MYPERL. Options specified in env var PERLDB (if any) are passed to the interpreter. Warnings are enabled globally.
how i can change MYPERL variable value /home/Desktop/goudar/perl/ and execute rest of the script
If the process that will launch the script is a bourne-based, then
export MYPERL=/home/Desktop/goudar/perl/
That said, I don't know why you want to assign that value to the MYPERL env variable since the script expects it to be the path to a Perl interpreter.

Shell script takes variable as a command

I'm coding an extremely simple shell script and it doesn't really work as it should. Here are the contents:
# Defining base project directory
BASE_DIR=/path/to/proj;
PRODUCTION_DIR = $BASE_DIR/out/production/dir;
# Generating headers
javah -classpath $PRODUCTION_DIR -d $BASE_DIR/jni/include com.my.class.Name
# Building native libs
ndk-build
Paths are correct, it works if I remove $PRODUCTION_DIR, if I'll run it like this, it says:
line 3: PRODUCTION_DIR: command not found
...
Does any one know what's wrong?
Remove whitespace,
PRODUCTION_DIR=$BASE_DIR/out/production/dir
Otherwise you're trying to run PRODUCTION_DIR with parameters = and $BASE_DIR/out/production/dir
Also, remove the ;'s at end of line, they're redundant

How do you configure GroovyConsole so I don't have to import libraries at startup?

I have a groovy script that uses a third party library. Each time I open the application and attempt to run my script I have to import the proper library.
I would like to be able to open GroovyConsole and run my application without having to import the library.
In Linux you also have
/usr/share/groovy/conf/groovy-starter.conf
Here you can add your specific libs:
# load user specific libraries
load !{user.home}/.groovy/lib/*.jar
load /home/squelsh/src/neo4j-community-1.4.M03/lib/*.jar
load /home/squelsh/src/neo4j-community-1.4.M03/system/lib/*.jar
Hope it helps, had to search long time to find this (:
If you just want to add the JARs to the classpath, copy (or symlink) them to ~/.groovy/lib (or %USER_HOME%/.groovy/lib on Windows).
If you want the actual import statements to run every time Groovy Console starts, edit the groovy-starter.conf file as suggested by Squelsh.
At least on Linux groovy GroovyConsole is a Script has the Following command:
startGroovy groovy.ui.Console "$#"
startGroovy itself is a script which starts Java. Within the startGroovy script you should be able to modify your classpath and add the missing librarys.
From startGroovy:
startGroovy ( ) {
CLASS=$1
shift
# Start the Profiler or the JVM
if $useprofiler ; then
runProfiler
else
exec "$JAVACMD" $JAVA_OPTS \
-classpath "$STARTER_CLASSPATH" \
-Dscript.name="$SCRIPT_PATH" \
-Dprogram.name="$PROGNAME" \
-Dgroovy.starter.conf="$GROOVY_CONF" \
-Dgroovy.home="$GROOVY_HOME" \
-Dtools.jar="$TOOLS_JAR" \
$STARTER_MAIN_CLASS \
--main $CLASS \
--conf "$GROOVY_CONF" \
--classpath "$CP" \
"$#"
fi
You can write an external Groovy script that does all the imports, creates a GroovyConsole object, and calls the run() method on this object.
See also http://groovy.codehaus.org/Groovy+Console#GroovyConsole-EmbeddingtheConsole
For example: start.groovy
import groovy.ui.Console;
import com.botkop.service.*
import com.botkop.service.groovy.*
def env = System.getenv()
def service = new ServiceWrapper(
userName:env.userName,
password:env.password,
host:env.host,
port:new Integer(env.port))
service.connect()
Console console = new Console()
console.setVariable("service", service)
console.run()
From a shell script call the groovy executable providing it with the groovy script:
#!/bin/bash
if [ $# -ne 4 ]
then
echo "usage: $0 userName password host port"
exit 10
fi
export userName=$1
export password=$2
export host=$3
export port=$4
export PATH=~/apps/groovy/bin:/usr/bin:$PATH
export CLASSPATH=$(find lib -name '*.jar' | tr '\n' ':')
groovy start.groovy
The code in GroovyConsole can now make use of the imports done in start.groovy, as well as of the variables created and passed with the setVariable method ('service' in the example).
If you are on a Mac, I would highly recommend using SDKMAN to manage Groovy installations.
Once installed via SDKMAN, you can modify ~/.sdkman/candidates/groovy/current/bin/groovy/conf/groovy-starter.conf. Packages you add here will be automatically imported at runtime whenever you start a Groovy Console session. You would want to add them under the section labelled in the example below:
# load user specific libraries
load !{user.home}/.groovy/lib/*.jar
load !{user.home}/.groovy/lib/additional_package.jar

Resources