myfile.sh
#!/bin/bash
echo -e "\n starting python script"
python main.py arg1
echo -e "\n done"
This is not working.
Above file has given following error
starting python script
Traceback (most recent call last):
File "main.py", line 97, in <module>
main()
File "main", line 80, in main
header = "arg1: {}\n\n".format(sys.argv[1])
ValueError: zero length field name in format
done
main.py
...
...
def main():
""" main function
"""
header = "arg1: {}\n\n".format(sys.argv[1])
...
...
if __name__ == "__main__":
if len(sys.argv) == 2:
main()
else:
print "\n Invalid no. of arguments"
print "\n Usage:"
print "\n python {} <date>\n".format(sys.argv[0])
exit(1)
Whats the correct syntax to call a python script having arguments from shell script ?
asked Aug 11, 2014 at 12:30
Patrick
2,5543 gold badges34 silver badges48 bronze badges
-
Could you please be a little more precise? Maybe with a toy example?user189– user1892014年08月11日 12:31:57 +00:00Commented Aug 11, 2014 at 12:31
-
2Yes it is correct, what do you mean for not working? bash throws an error, python throws an error?enrico.bacis– enrico.bacis2014年08月11日 12:32:43 +00:00Commented Aug 11, 2014 at 12:32
-
What is your Python version? Could we please get the python script?user189– user1892014年08月11日 12:39:46 +00:00Commented Aug 11, 2014 at 12:39
-
@user189 updated question with main.py contents and my python version is 2.6.2Patrick– Patrick2014年08月11日 12:44:43 +00:00Commented Aug 11, 2014 at 12:44
-
2Change {} --> {0}, or maybe upgrade to 2.7 if possible. So this is not problem of calling python, but a rather a problem of using the wrong syntax for the your python version.FredrikHedman– FredrikHedman2014年08月11日 12:59:54 +00:00Commented Aug 11, 2014 at 12:59
2 Answers 2
Your script should work fine. Here is a toy sample:
#!/bin/bash
echo -e "\n starting python script"
python main.py arg1 arg2 arg3
echo -e "\n done"
with main.py as
#!/usr/bin/env python
from __future__ import print_function
import sys
print("In python pgm called from shell script with args:")
for i, a in enumerate(sys.argv):
print("argument {0} is {1}".format(i, a))
The error is probably caused by the '{}'. Need to have a recent enough python version for that to work (2.7 or better to be on the safe side...). Otherwise specify the positional argument numbers.
answered Aug 11, 2014 at 12:48
FredrikHedman
1,2637 silver badges14 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Yes, this is correct. Try this for example:
main.py
import sys
print sys.argv[1]
answered Aug 11, 2014 at 12:35
enrico.bacis
31.9k10 gold badges90 silver badges116 bronze badges
Comments
default