简体   繁体   English

从shell脚本执行python脚本(具有参数)

[英]Executing python script(having arguments) from shell script

myfile.sh 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 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 ? 调用具有shell脚本参数的python脚本的正确语法是什么?

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 与main.py为

#!/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...). 需要具有足够的最新python版本才能正常工作(为了安全起见,请使用2.7或更高版本...)。 Otherwise specify the positional argument numbers. 否则,请指定位置参数编号。

Yes, this is correct. 是的,这是正确的。 Try this for example: 尝试以下示例:

main.py main.py

import sys
print sys.argv[1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM