I want to run my python script through the shell, passing variable a
.
Here is my code:
else
a=0
osascript -e 'tell application "Terminal" to activate' \
-e 'tell application "System Events" to keystroke "n" using {command down}' \
-e 'tell application "Terminal" to do script "python /Users/kacperXXX/instagram_bot.py \"$a\"" in front window'
sleep 5
exit
fi
My script just prints its arguments. When I run it I got empty list only with file path.
Output
['/Users/kacperleczynski/Desktop/instagram_bot.py', '']
Thanks for advice.
CodePudding user response:
You can pass arguments as input using the sys
module.
When using your script, you call:
python test.py var1
Inside test.py, in the first lines you must import sys
:
import sys
print(sys.argv[0]) # prints test.py
print(sys.argv[1]) # prints var1
You can use a
instead of var1
as input.
CodePudding user response:
There are a couple of ways of approaching this. The reason your script is not currently working is that variables aren't interpolated (substituted in) inside strings that have single quotes around them. Variables are only substituted in within strings surrounded in double quotes. So you need to have the string with your variable a
in it surrounded by double quotes. But if you do that, the double quotes in there already will end your string, so you need to escape them with a backslash.
Here's one way - notice the last line is in double quotes:
#!/bin/bash
a=42
# Method 1
osascript -e 'tell application "Terminal" to activate' \
-e 'tell application "System Events" to keystroke "n" using {command down}' \
-e "tell application \"Terminal\" to do script \"python3 /path/to/script.py $a\" in front window"
And here's another way using a here-doc
, i.e. "here's the stuff to execute":
# Method 2
osascript <<EOF
tell application "Terminal" to activate
tell application "System Events" to keystroke "n" using {command down}
tell application "Terminal" to do script "python3 /path/to/script.py $a" in front window
EOF