redigomock | Easy way to unit test projects using redigo library | Command Line Interface library
kandi X-RAY | redigomock Summary
Support
Quality
Security
License
Reuse
Currently covering the most popular Java, JavaScript and Python libraries. See a Sample Here
redigomock Key Features
redigomock Examples and Code Snippets
Trending Discussions on Command Line Interface
Trending Discussions on Command Line Interface
QUESTION
After an hour googling, I can't find anybody who has had anything resembling this issue besides myself. I created a command line interface with argparse. Originally I had tried to leverage argparse's built in help text behavior. But my boss isn't satisfied with the default help text, so he is having me write up the full usage/help text in a text file and just display the entire file.
For some reason, in a certain case, its outputting the text twice.
Here is the basics of how my program is broken down:
I have a top level parser. I read in my help text file, set it to a string help_text, and then set "usage=help_text" on the parser. Then I create subparsers (4 of them and then a base case) to create subcommands. Only one of those subparsers has any additional arguments (one positional, one optional). Before I reworked the help text, I had help text for each individual subcommand by using "help=" but now those are all blank. Lastly, I have set up a base case to display the help text whenever no subcommands are given.
Here is the behavior I'm getting:
When I call the main function with no subcommands and no arguments, my help_text from the text file outputs, and then like 2-3 additional lines of boiler plate I can't seem to get rid of. Also because the word usage appears in my text file, it says "usage: usage"
When I call the main command and then type --help, the exact same thing happens as above.
When I call the one subcommand that has a required positional argument and I don't include that argument... it spits out the entire help text twice. Right above the second time it prints, it prints the default usage line for that subcommand.
Lastly, when I use a different subcommand that has no arguments and give it an argument (one too many) it spits out everything completely correctly without even the extra couple lines at the end.
I don't know how to make heads or tales about this. Here is the main function of the script (I can verify that this problem occurs only in the main function where argparse is used, not the other functions that the main function calls):
def main():
# Import help text from file
p = Path(__file__).with_name("help_text.txt")
with p.open() as file:
help_text = file.read()
# Configure the top level Parser
parser = argparse.ArgumentParser(prog='hubmap-clt', description='Name of cli', usage=help_text)
subparsers = parser.add_subparsers()
# Create Subparsers to give subcommands
parser_transfer = subparsers.add_parser('subcommandone')
parser_transfer.add_argument('argument1', type=str)
parser_transfer.add_argument('--optionalargument', default='mydefault')
parser_login = subparsers.add_parser('subcommandtwo')
parser_whoami = subparsers.add_parser('subcommandthree')
parser_logout = subparsers.add_parser('subcommandfour')
# Assign subparsers to their respective functions
parser_subcommandone.set_defaults(func=subcommandone)
parser_subcommandtwo.set_defaults(func=subcommandtwo)
parser_subcommandthree.set_defaults(func=subcommandthree)
parser_subcommandfour.set_defaults(func=subcommandfour)
parser.set_defaults(func=base_case)
# Parse the arguments and call appropriate functions
args = parser.parse_args()
if len(sys.argv) == 1:
args.func(args, parser)
else:
args.func(args)
So to clarify:
Why does the extra couple lines of boiler-plat help text appear sometimes which looks like this:
name of cli
positional arguments:
{subcommandone,subcommandtwo,subcommandthree,subcommandfour}
optional arguments:
-h, --help show this help message and exit
Why does using subcommandone with too few arguments print out the help text twice (but NOT the extra lines of boiler-plate help text.
why does using subcommandtwo with one too MANY arguments print everything perfectly without any extra lines?
ANSWER
Answered 2022-Feb-25 at 21:44With a modification of your main
:
def foo():
# Import help text from file
# p = Path(__file__).with_name("help_text.txt")
# with p.open() as file:
# help_text = file.read()
help_text = "cli usage: foobar\n morebar"
# Configure the top level Parser
parser = argparse.ArgumentParser(
prog="hubmap-clt", description="Name of cli", usage=help_text
)
subparsers = parser.add_subparsers()
# Create Subparsers to give subcommands
parser_transfer = subparsers.add_parser("subcommandone")
parser_transfer.add_argument("argument1", type=str)
parser_transfer.add_argument("--optionalargument", default="mydefault")
parser_login = subparsers.add_parser("subcommandtwo")
# parser_whoami = subparsers.add_parser("subcommandthree")
# parser_logout = subparsers.add_parser("subcommandfour")
# Assign subparsers to their respective functions
parser_transfer.set_defaults(func="subcommandone")
parser_login.set_defaults(func="subcommandtwo")
# parser_subcommandthree.set_defaults(func="subcommandthree")
# parser_subcommandfour.set_defaults(func="subcommandfour")
parser.set_defaults(func="base_case")
return parser
in an iteractive ipython session:
In [8]: p = foo()
In [9]: p.print_usage()
usage: cli usage: foobar
morebar
Usage is exactly as I specified. And the help for the main parser:
In [10]: p.print_help()
usage: cli usage: foobar
morebar
Name of cli
positional arguments:
{subcommandone,subcommandtwo}
optional arguments:
-h, --help show this help message and exit
That's what I expect given the arguments.
Help for a subparser:
In [11]: p.parse_args(["subcommandone", "-h"])
usage: cli usage: foobar
morebar subcommandone [-h] [--optionalargument OPTIONALARGUMENT] argument1
positional arguments:
argument1
optional arguments:
-h, --help show this help message and exit
--optionalargument OPTIONALARGUMENT
Usage is like the main's but with some added info on how to call this subparser and its arguments.
Error when calling the subparsers without enough values:
In [15]: p.parse_args(["subcommandone"])
usage: cli usage: foobar
morebar subcommandone [-h] [--optionalargument OPTIONALARGUMENT] argument1
cli usage: foobar
morebar subcommandone: error: the following arguments are required: argument1
Is this repeat of cli usage
that bothering you? This error is raised by the subparser, and I suspect the extra comes from the prog
of that subparser. I think I saw something like this on the Python bug/issues for argparse
.
error with too much:
In [17]: p.parse_args(["subcommandone", "test", "extra"])
usage: cli usage: foobar
morebar
hubmap-clt: error: unrecognized arguments: extra
In this case error is produced by the main parser, hence the "hubmat-clt" prog
.
change prog
:
...: parser_transfer = subparsers.add_parser( ...: "subcommandone", prog="hubmap-clt sobcommandone" ...: )
In [21]: p.parse_args(["subcommandone", "test", "extra"])
usage: cli usage: foobar
morebar
hubmap-clt: error: unrecognized arguments: extra
In [22]: p.parse_args(["subcommandone"])
usage: hubmap-clt sobcommandone [-h] [--optionalargument OPTIONALARGUMENT] argument1
hubmap-clt sobcommandone: error: the following arguments are required: argument1
[21] is as before [17]. But [22] is now showing the prog
that I set. I could also have specified a custom usage
for the subparser.
If I modify the function to use default usage and prog, but also display the subparser's prog. And I gave the main an "main_foo" positional argument:
In [30]: p = foo()
hubmap-clt main_foo subcommandone
In [31]: p.parse_args(["subcommandone"])
Out[31]: Namespace(main_foo='subcommandone')
In [32]: p.parse_args(["foo", "subcommandone"])
usage: hubmap-clt main_foo subcommandone [-h] [--optionalargument OPTIONALARGUMENT] argument1
hubmap-clt main_foo subcommandone: error: the following arguments are required: argument1
Notice how the main's usage has been incorporated into the 'prog' for the subparser.
In the bug/issue I found the main parser's usage
gets incorporated into the prog
of the subparser. That's why you see the duplicate.
https://bugs.python.org/issue42297 [argparse] Bad error message formatting when using custom usage text
The relatively recent date of this bug issue indicates that custom usage is not that common, and even less so when used with subparsers. As my post on this issue indicates, the relation between the main parser, the "subparsers" command, and individual subparsers gets complicated.
QUESTION
I'm trying to install conda environment using the command:
conda env create -f devenv.yaml
My .yaml file is
name: myname
channels:
- conda-forge
- bioconda
dependencies:
# Package creation and environment management
- conda-build
# Automation control (command line interface, workflow and multi-process management)
- python-dotenv
- click
- snakemake-minimal
- joblib
- numba
# Workspace
- notebook
# Visualization
- plotly
- plotly-orca
- matplotlib
- seaborn
- shap
- openpyxl
- ipywidgets
- tensorboard
# Data manipulation
- numpy
- pandas
- pyarrow
# Functional style tools
- more-itertools
- toolz
# Machine learning
- scikit-learn
- imbalanced-learn
- scikit-image
- statsmodels
- catboost
- hyperopt
- tsfresh
# Deep learning
- pytorch
# code checking and formatting
- pylint
- black
- flake8
- mypy
# Python base
- python
- pip
- pip:
I've tried to update conda but it doesn't help. It just stuck on solving the environment.
conda version: 4.11.0 c OS: Ubuntu 18.04.5 LTS
The exact same environment works fine on my mac, but not on that server. What could be the issue? I appreciate any suggestions. Thx.
ANSWER
Answered 2021-Dec-22 at 18:02This solves fine (), but is indeed a complex solve mainly due to:
- underspecification
- lack of modularization
This particular environment specification ends up installing well over 300 packages. And there isn't a single one of those that are constrained by the specification. That is a huge SAT problem to solve and Conda will struggle with this. Mamba will help solve faster, but providing additional constraints can vastly reduce the solution space.
At minimum, specify a Python version (major.minor), such as python=3.9
. This is the single most effective constraint.
Beyond that, putting minimum requirements on central packages (those that are dependencies of others) can help, such as minimum NumPy.
Lack of ModularizationI assume the name "devenv" means this is a development environment. So, I get that one wants all these tools immediately at hand. However, Conda environment activation is so simple, and most IDE tooling these days (Spyder, VSCode, Jupyter) encourages separation of infrastructure and the execution kernel. Being more thoughtful about how environments (emphasis on the plural) are organized and work together, can go a long way in having a sustainable and painless data science workflow.
The environment at hand has multiple red flags in my book:
conda-build
should be in base and only in basesnakemake
should be in a dedicated environmentnotebook
(i.e., Jupyter) should be in a dedicated environment, co-installed withnb_conda_kernels
; all kernel environments need areipykernel
I'd probably also have the linting/formatting packages separated, but that's less an issue. The real killer though is snakemake
- it's just a massive piece of infrastructure and I'd strongly encourage keeping that separated.
QUESTION
I have a strange error here. The command I am executing is this:
mysqldump -u root -ppass kodi_video119 | mysql -h192.168.178.73 -u kodi -ppass kodi_video119
When I execute it over SSH it all works fine, but when I save it to a file and execute this file I get the following error:
mysqldump: [Warning] Using a password on the command line interface can be insecure.
mysql: [Warning] Using a password on the command line interface can be insecure.
'RROR 1102 (42000): Incorrect database name 'kodi_video119
mysqldump: Got errno 11 on write
I can't find any results using google on that error number. The user is allowed to write and it all works fine when I execute it direcly from SSH. But using the same SSH session (as root user) just executing the command embedded in the file it does not work.
Whats going wrong here? I created the file using nano and saved it using nano. Then chmod +x and execute ./test
ANSWER
Answered 2021-Nov-28 at 19:48By default, when you use mysqldump DB
, the output includes table-creation statements, but no CREATE DATABASE
statement. It just assumes you have created an empty schema first.
So you could do this to create the schema first:
mysqladmin -h192.168.178.73 create kodi_video119
mysqldump kodi_video119 | mysql -h192.168.178.73 kodi_video119
(I left out the -u and -p options for brevity)
Alternatively, you can use the -B
option, aka --databases
. This option allows you to specify one or more databases, and the output includes CREATE DATABASE
statements for each one before it then creates and populates tables. You can use it with a single database argument:
mysqldump -B kodi_video119 | mysql -h192.168.178.73 kodi_video119
QUESTION
I am trying to create a shell script that will pull row counts in all tables from multiple databases. All of the databases follow the same naming convention "the_same_databasename_<%>" except the final layer in the name, which varies. I am trying to run the following:
use ;
show tables;
select count(*) from ;
Since I have 40 different databases, I would need to run the first two queries for each database 40 different times, plus the select count query even more depending on how many table in the database (very time consuming). I have my PuTTy configuration settings set to save my PuTTy sessions into a .txt on my local directory, so I can have the row count results displayed right in my command line interface. So far this is what I have but not sure how to include the final commands to get the actual row counts from the tables in each database.
#!/bin/bash
for db in $(hive -e "show databases like 'the_same_databasename_*;")
do
tbl_count=$(hive -S -e "use $db; show tables;" | wc -l)
echo "Database $db contains $tbl_count tables."
done
I'm not very experienced in shell scripting so any guidance/help is greatly appreciated. Thanks in advance.
ANSWER
Answered 2021-Nov-22 at 07:57You can use nested for-loop:
#!/bin/bash
for db in $(hive -e "show databases like 'the_same_databasename_*;")
do
tbl_count=$(hive -S -e "use $db; show tables;" | wc -l)
echo "Database $db contains $tbl_count tables."
for table in $(hive -S -e "use $db; show tables;")
do
count=$(hive -S -e "use $db; select count(*) from $table;")
echo "Table $db.$table contains $count rows."
done
done
Or you can use variable to increment count of tables
#!/bin/bash
for db in $(hive -e "show databases like 'the_same_databasename_*;")
do
tbl_count=0
for table in $(hive -S -e "use $db; show tables;")
do
(( tbl_count++ ))
count=$(hive -S -e "use $db; select count(*) from $table;")
echo "Table $db.$table contains $count rows."
done
echo "Database $db contains $tbl_count tables."
done
QUESTION
Is there any command to see all variable names, types and values in command line interface? Similar to Matlab's Workspace? I already know about command whos
but it doesn't show the values, It just shows names and types.
Thanks :)
ANSWER
Answered 2021-Nov-20 at 09:18try this:
vals = who;
for val = vals
eval(val.name)
end
QUESTION
I am trying to use a React web app to read and write stuff in a Firebase realtime database. Every time I run "npm run start", I get this error message.
Failed to compile
src/index.js
Line 25:1: 'firebase' is not defined no-undef
Line 28:16: 'firebase' is not defined no-undef
Search for the keywords to learn more about each error.
This error occurred during the build time and cannot be dismissed.
This is what package.json, src/index.js, build/index.html, and public/index.html looked like when I first got this error. (is it bad to have 2 index.html files?)
{
"name": "my-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"@material-ui/core": "^4.12.2",
"@testing-library/jest-dom": "^5.14.1",
"@testing-library/react": "^11.2.7",
"@testing-library/user-event": "^12.8.3",
"firebase": "^9.0.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-router-config": "^5.1.1",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.3",
"web-vitals": "^1.1.2"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
import React from 'react';
import ReactDOM from 'react-dom';
//import './index.css';
//import App from './App';
//import reportWebVitals from './reportWebVitals';
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const config = {
apiKey: "AIzaSyBk5lf0WtiZPs1ZQkA48OfXpzW7P_RCrZk",
authDomain: "test-c2ec9.firebaseapp.com",
projectId: "test-c2ec9",
storageBucket: "test-c2ec9.appspot.com",
messagingSenderId: "11138018851",
appId: "1:11138018851:web:ecfb63337ca11f62028b96",
measurementId: "G-3S1M3601YR"
};
// Initialize Firebase
firebase.initializeApp(config);
// Get a reference to the database service
var database = firebase.database();
const app = initializeApp(config);
const analytics = getAnalytics(app);
ReactDOM.render(
,
document.getElementById('root')
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint.
//reportWebVitals();
Welcome to Firebase Hosting
Welcome
Firebase Hosting Setup Complete
You're seeing this because you've successfully setup Firebase Hosting. Now it's time to go build something extraordinary!
Open Hosting Documentation
Firebase SDK Loading…
React App
You need to enable JavaScript to run this app.
Lines 25 and 28 in src/index.js are "firebase.initializeApp(config);" and "var database = firebase.database();", respectively. You should be able to reproduce this error by following these steps:
create test/package.json, test/src/index.js, test/build/index.html, and test/public/index.html
copy and paste the above 4 snippets into their respective files
save the 4 files
open a command line interface
use cd to navigate to the test folder
run "npm install"
run "npm run start"
Commenting out lines 25 and 28 causes a much longer error message that starts with "Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app)." When I searched that error message, I got results telling me to add those lines back into index.js, which leads me back to this "'firebase' is not defined" error. Additionally, I tried each of these things, and I still got the same error message.
restarting my computer
following this tutorial
changing line 28 to "var rootref = firebase.database().ref();"
running "npm start" instead of "npm run start"
pasting this snippet in the head part of build/index.html and public/index.html
pasting this snippet in the head part of build/index.html and public/index.html
pasting this snippet in the head part of build/index.html and public/index.html
pasting this snippet in the head part of build/index.html and public/index.html
copying this snippet from the head part of build/index.html and pasting it in public/index.html
Is there anything else that I can try?
ANSWER
Answered 2021-Nov-12 at 21:59Recently, Firebase announced that version 9 of Firebase SDK JS is generally available. This was done to do some optimisations. Try using:
import { initializeApp } from 'firebase/app';
import { getAuth, onAuthStateChanged } from 'firebase/auth';
and
const firebaseApp = initializeApp({ /* config */ });
const auth = getAuth();
onAuthStateChanged(auth, user => { console.log(user); });
instead of
import firebase from 'firebase/app';
import 'firebase/auth';
and
const firebaseApp = firebase.initializeApp({ /* config */ });
const auth = firebaseApp.auth();
auth.onAuthStateChanged(user => { console.log(user); });
Refer to this link for further reference: https://firebase.google.com/docs/web/modular-upgrade
QUESTION
I'm trying to make a simple command line interface, but i'm having a probleme for parsing commands :
process_t is a structure contient the path of the command with arguments to be stored in the variable argv.
int parse_cmd(char* tokens[], process_t* commands) {
assert(tokens!=NULL);
assert(commands!=NULL);
int position = 0;
int commandNumber = 0;
for(int i=0; tokens[i] != NULL; i++){
if(is_reserved(tokens[i]) == 0 && tokens[i+1] != NULL) continue;
int end = is_reserved(tokens[i]) == 0 ? i+1 : i;
int argc = position;
int count = 0;
process_t newProcess;
char* argv[MAX_CMD_SIZE] = {NULL};
for(argc; argc < end; argc++) {
argv[count] = tokens[argc];
count = count + 1;
}
newProcess.path = tokens[position];
newProcess.argv = argv;
position = i + 1;
commands[commandNumber] = newProcess;
commandNumber = commandNumber + 1;
}
}
int main(int argc, char* argv[]) {
char path[MAX_LINE_SIZE];
char line[MAX_LINE_SIZE];
char* cmdline[MAX_CMD_SIZE];
process_t cmds[MAX_CMD_SIZE];
getcwd(path, MAX_LINE_SIZE);
while (1) {
printf("mini@shell:%s$ ", path);
scanf("%[^\n]%*c", line);
trim(line);
clean(line);
tokenize(line, cmdline);
parse_cmd(cmdline, cmds);
toString(cmds);
break;.
}
return -1;
}
Input: ls -l ; grep ^a
Why the array contain only the value of argv of the last iteration ?
Output :
path : ls => argv = {grep, ^a, (null)} path : grep => argv = {grep, ^a, (null)}
ANSWER
Answered 2021-Nov-05 at 11:12You're trying to use the block-local array argv
, which is recreated for every command and, what's worse, doesn't even exist any longer after parse_cmd
has returned. An array object with sufficient lifetime has to be used; you can do this by changing
char* argv[MAX_CMD_SIZE] = {NULL};
to
char **argv = calloc(end-position+1, sizeof *argv);
Note that you'd have to free
this object when no longer needed.
Also note that you forgot to return commandNumber;
from parse_cmd
; without that, you have no way of knowing how many commands were found.
QUESTION
I'd like to give my Python scripts the ability to detect whether it was executed in a Git Bash terminal, or the Windows cmd command line interface. For example, I'm trying to write a function to clear the terminal (regardless of which terminal it is), e.g. echoes the clear
command if in Git Bash, or cls
if in cmd.
I've tried using sys.platform to detect this, but it returns win32
regardless of which type of terminal it was ran in.
ANSWER
Answered 2021-Oct-17 at 05:23I don't believe what you're asking for is possible, but there are several answers here that show all the detections you can do to use the correct type of clear. Usually, it's just best to either make your own window or not clear the screen, sadly.
QUESTION
I'm trying to write a bash script which will install and set up a MySQL server automatically. The problem is that when my script executes the following command:
mysql --socket=/mysql/socket -u root -p"$pass"
I get the following error:
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '//mysql/socket' (2)
Yet when I run the same command in my bash terminal, it works fine:
$ mysql --socket=socket -u root -p'random-init-pass'
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.7.18
Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
Here's the set-up:
I have a script called sourceme.bash
. I source sourceme.bash
in order to set up the server. Here's what it looks like (everything in <>
is unimportant):
mysql/sourceme.bash
:
source //bash
module load
SQLDIR="/"
cd $SQLDIR
# Kill the existing MySQL server (for testing purposes as I'm re-running this script multiple times)
# Do so by locating its process ID and terminating that ID, waiting until it's killed before proceeding.
ps -aux | grep mysql | grep -v grep
mysqlps=`ps -aux | grep mysql | grep -v grep | sed -e 's/ \{2,\}/ /g' | cut -f2 -d' '`
if [[ -n $mysqlps ]]; then
kill $mysqlps
while kill -0 $mysqlps; do
sleep 0.5
done
echo "MySQL process successfully killed. Status $?"
else
echo "No MySQL process to kill. Status $?"
fi
rm -rf $SQLDIR/mysql
# Set up MySQL server directory
mkdir -p $SQLDIR/mysql
pushd $SQLDIR/mysql
# Copy setup files stored in $SQLDIR in order to install MySQL
# The my.cnf config file contains the string "$USER" which should be replaced with a Unix username.
cat $SQLDIR/setup_files/my.cnf | awk -v user=`whoami` '{ sub(/\$USER/, user); print }' > my.cnf
cp -t . $SQLDIR/setup_files/loadmodules.bash $SQLDIR/setup_files/mysql_*
chmod +x mysql_*
# Load modules necessary to run the server
source loadmodules.bash
# Initialise MySQL server, kill the script if this step fails.
# NB thanks to Raman Sailopal for helping me with this bit: https://stackoverflow.com/questions/69406526/start-a-mysql-server-pipe-the-output-to-a-file
./mysql_init.sh 2>&1 | tee mysql_init.log
init_status=${PIPESTATUS[0]}
if [[ $init_status -ne 0 ]]; then
echo "Init script failed - kill script"
return 1
fi
# Grab the setup password from the log produced by mysql_init.sh. Copy into variable.
line=`tail -n1 mysql_init.log`
pass="${line##* }"
# Launch MySQL server now that it's been initialised
./mysql_start.sh
# Create a .my.cnf config file in the user's home area, set to user-access only
user=`whoami`
cat << EOT > ~/.my.cnf
[mysqld]
user=$user
password=$pass
socket=$SQLDIR/mysql/socket
EOT
chmod 700 ~/.my.cnf
# Fire up the MySQL server command line
# THIS IS THE BIT THAT DOESN'T WORK
mysql --socket=$SQLDIR/mysql/socket -u root -p"$pass"
If I comment out the last line and copy the exact same thing into my terminal, it will start the MySQL server without complaint. I've also tried using the -e option to feed a command into the CLI and then quit, but that doesn't work either.
For completeness, here are the setup files that will be in the location $SQLDIR/mysql - which the script runs in order to start the MySQL server.
mysql/my.cnf
:
[mysqld]
user=lou-unix-username
socket=socket
mysql/mysql_init.sh
:
#! /bin/sh
export MYSQL_HOME=$PWD
# Change lc-messages-dir if running on RHE6 host
mysqld \
--defaults-file=$MYSQL_HOME/my.cnf \
--lc-messages-dir="//mysql/5.7.18/rhe7-x86_64/share/english/" \
--datadir=$MYSQL_HOME/data \
--basedir=$MYSQL_HOME \
--pid-file=$MYSQL_HOME/mysql.pid \
--socket=$MYSQL_HOME/socket \
--port=3307 \
--initialize
mysql/mysql_start.sh
:
#! /bin/sh
echo $DATADIR
export MYSQL_HOME=$PWD
mysqld \
--defaults-file=$MYSQL_HOME/my.cnf \
--log-error \
--lc-messages-dir="//mysql/5.7.18/rhe7-x86_64/share/english/" \
--datadir=$MYSQL_HOME/data \
--basedir=$MYSQL_HOME \
--pid-file=$MYSQL_HOME/mysql.pid \
--socket=$MYSQL_HOME/socket \
--port=3307 &
~/.my.cnf
:
[mysqld]
user=lou-unix-username
password=random-init-password
socket=//mysql/socket
Is anyone able to suggest why I can launch the CLI on the terminal but not in a script? I know that I need to reset the randomly initialised password after starting up the MySQL CLI, but it won't even let me do that using the script. What could I be doing wrong?
ANSWER
Answered 2021-Oct-12 at 15:28Well, I'm not entirely sure what was wrong, but I think it came down to one process not finishing before another process started. I inserted a sleep 5
in the script - just before the last line where I'm trying to connect to the server, and that worked. I also wrapped the line in a while loop, giving it up to 5 attempts to connect to the server, and if it fails, it will wait a further 5 seconds. Currently this seems to work fairly reliably and I am able to connect to the MySQL server.
So either way the problem appears to be solved.
QUESTION
I am using Python 3.9 and Click to build a small command line interface utility, but I am getting strange errors, specifically when I attempt to call one function decorated as a @click.command()
from another function that is also decorated the same way.
I have distilled my program down to the bare minimum to explain what I mean.
This is my program
import click
@click.group()
def cli():
pass
@click.command()
@click.argument('id')
def outer(id):
print('outer id',id,type(id))
inner(id) # run inner() from within outer(), pass argument unchanged
@click.command() # *
@click.argument('id') # *
def inner(id):
print('inner id',id,type(id))
cli.add_command(outer)
cli.add_command(inner) # *
if __name__ == '__main__':
cli()
This is the CLI result when I run my script using both the inner
and outer
commands:
% python3 test.py inner 123
inner id 123
% python3 test.py outer 123
outer id 123
Usage: test.py [OPTIONS] ID
Try 'test.py --help' for help.
Error: Got unexpected extra arguments (2 3)
%
Interestingly, it works when I use a single character argument:
% python3 test.py outer 1
outer id 1
inner id 1
%
If I comment out the three lines marked with # *
, running the outer
command behaves as expected, passing on the id
argument to inner()
without changes or issues, no matter the length of the argument:
% python3 test.py outer 123
outer id 123
inner id 123
%
Clearly, the decorators are somehow messing with the arguments. Can anybody explain why this is, and how I can achieve the desired behavior of passing on the arguments unchanged? Maybe I am missing something super obvious?
Thanks in advance!
ANSWER
Answered 2021-Sep-10 at 16:18Use the context operations to invoke other commands
import click
@click.group()
def cli():
pass
@click.command()
@click.argument('id')
@click.pass_context
def outer(ctx, id):
print('outer id',id,type(id))
ctx.forward(inner) # run inner(), pass argument unchanged
ctx.invoke(inner, id=id+1) # run inner(), pass modified argument
@click.command() # *
@click.argument('id') # *
def inner(id):
print('inner id',id,type(id))
cli.add_command(outer)
cli.add_command(inner) # *
if __name__ == '__main__':
cli()
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install redigomock
Support
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesExplore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits
Save this library and start creating your kit
Share this Page