gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:37:15 25 4
gpt4 key购买 nike

我的文件.sh

#!/bin/bash
echo -e "\n starting python script"
python main.py arg1
echo -e "\n done"

这不起作用。

以上文件给出了以下错误

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

主.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)

调用具有 shell 脚本参数的 python 脚本的正确语法是什么?

最佳答案

您的脚本应该可以正常工作。这是一个玩具样本:

#!/bin/bash
echo -e "\n starting python script"
python main.py arg1 arg2 arg3
echo -e "\n done"

以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))

错误可能是由“{}”引起的。需要有一个足够新的 python 版本才能工作(2.7 或更高版本以确保安全......)。否则指定位置参数编号。

关于python - 从 shell 脚本执行 python 脚本(有参数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25243365/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com