For a Bash completion script I need to get all the variables from an installed Python module that match a pattern. I want to use only Python-aware functionality, to avoid having to parse comments and such.
You can use python -c to execute a one-line Python script if you want. For example:
bash$ python -c "import os; print dir(os)"
If you want to filter by a pattern, you could do:
bash$ python -c "import os; print [x for x in dir(os) if x.startswith('r')]"
['read', 'readlink', 'remove', 'removedirs', 'rename', 'renames', 'rmdir']
Related
I am trying to write this small python program to execute with python through the -c option:
python -c "import sys;if 2==sys.version_info.major: raise RuntimeError('Must use python3')"
However, this is raising a syntax error:
File "<string>", line 1
import sys;if 2==sys.version_info.major: raise RunTimeError('Must use python3')
^
SyntaxError: invalid syntax
is there a way to write this such that it does work in the above? And if it's invalid, is there a canonical reference to what syntaxes are allowed in -c executed code?
I am doing this in a Makefile.
Literal newlines are perfectly valid inside single-quoted strings in POSIX shells:
python -c '
import sys
if 2 == sys.version_info.major:
raise RuntimeError("Must use python3")
'
This means you aren't dependent on having bash, ksh93 or zsh with the $'' extension.
If this is in a Makefile:
define python_script
import sys
if 2 == sys.version_info.major:
raise RuntimeError("Must use python3")
endef
test:
python -c "$$python_script"
You can use \n.
python -c "import sys"$'\n'"if 2 == sys.version_info.major:"$'\n'" raise RuntimeError('Must use python3')"
...this assumes you're using bash or some closely related shell. But otherwise obviously you can still just have newlines in the string, especially if you're calling python -c from a program using exec or something.
how can i run an easy python script and save it in a file but directly in linux command line:
fox#fox:/opt/gera# python -c print "aaaaa" > myfileName
but it is just print nothing instead of "aaaaa".
You have to quote the whole command:
python -c 'print "aaaaa"' > myfileName
Otherwise you execute print in Python (which, in Python 2 prints a linebreak and in Python 3 does nothing since you'd just evaluate the function print without calling it) and pass aaaaa as an argument to the script.
You need to put quotes around the code.
python -c 'print "aaaaa"' > myfileName
python -c 'print "aaaaa"' > myfileName
in your example python is running python -c print and giving "aaaaa" as an argument.
man python:
-c command
Specify the command to execute. This terminates the option list (following options are passed as arguments to the command).
passed as arguments to the command -- means everything after the command is available as sys.argv:
$ python -c 'import sys; print sys.argv' -a -b -c -d
['-c', '-a', '-b', '-c', '-d']
To make a single argument (command in terms of the man excerpt above) out of a list of arguments you just take these in quotes:
$ python -c 'print "aaaaa"'
aaaaa
I am trying to use python -c command line option but cannot seem to make it work.
What is the right way to use it?
Sometime it is really useful to store the whole command and one line and make an alias for it then going into the interactive mode.
The following gives no output
-bash-3.2$ python -c "
import hashlib
hashlib.md5('test').hexdigest()"
But of course following works
-bash-3.2$ python
>>> import hashlib
>>> hashlib.md5('test').hexdigest()
'098f6bcd4621d373cade4e832627b4f6'
>>>
you've got to print what you want to see if in non-interactive mode.
python -c "import hashlib
print hashlib.md5('test').hexdigest()"
the interactive mode always prints the return values, but this is just a gimmick of the CLI
python -c "import hashlib; print(hashlib.md5('test').hexdigest())"
>python -c "import hashlib; print hashlib.md5('test').hexdigest()"
098f6bcd4621d373cade4e832627b4f6
You are missing the print, which is why you don't see anything.
I am generating command passed to python -c like this
'python -c "import '+impMod+'; help('+module+'.'+method+') if \''+method+'\' in dir('+module+') else from '+impMod+' import '+method+' help('+method+')"'
and get output like this:
python -c "import os; help(os.path.pathconf) if 'pathconf' in dir(os.path) else from os import pathconf help(pathconf)"
even if i try
python -c "import os; help(os.path.pathconf) if 'pathconf' in dir(os.path) else from os import pathconf; help(pathconf)"
but don't know why I get SyntaxError: invalid syntax
Any help will be appreciated,
Regards.
You are mixing up statements and expressions. The from .. import .. syntax is a statement, and cannot appear inside an expression, but you are using it inside a ... if ... else ... expression. Also, you can use newlines inside a shell string.
python -c "import os
if 'pathconf' in dir(os.path):
help(os.path.pathconf)
else:
from os import pathconf
help(pathconf)"
To do that in Python, you might want to use triple quotes.
I have an "alarm email" function inside a python module. I want to be able to call this function from a bash script. I know you can call a module using 'python ' in the script, but I'm not if you can or how you would call a specific function within the module.
python -c'import themodule; themodule.thefunction("boo!")'
You can use the -c option:
python -c "import random; print random.uniform(0, 1)"
Modify as you need.
To call a specific function in a module, assure that the module has the following:
if __name__ == "__main__":
the_function_to_call( )
Then you can simply do this in your shell script.
python module.py
Or
python -m module
Depending on whether or not the module's on the PYTHONPATH.
To supplements others' answers with two notes:
If you need to feed environment variables as parameters, use double quotes;
The parameters are not necessarily str.
Here is an example:
# test.py
def call(param):
print(f'{param} with type={type(param)}')
print('hi')
Execute from shell:
PARAM=10
python3 -c "import test; test.call(${PARAM})"
You can read:
hi
10 with type=<class 'int'>