Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/360.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将sys.argv用作函数中的参数时出现语法错误_Python_Sys - Fatal编程技术网

Python 将sys.argv用作函数中的参数时出现语法错误

Python 将sys.argv用作函数中的参数时出现语法错误,python,sys,Python,Sys,获取由此行代码导致的语法错误 def load(sys.argv): with open(sys.argv[1]) as file: reader = json.load(file) return reader['json'] 来自stderr的消息: def load(sys.argv): ^ SyntaxError: invalid syntax 当然,我已经导入了sys 实际上,函数中使用sys.arg

获取由此行代码导致的语法错误

def load(sys.argv):
    with open(sys.argv[1]) as file:
        reader = json.load(file)
        return reader['json']

来自stderr的消息:

    def load(sys.argv):
                ^
SyntaxError: invalid syntax

当然,我已经导入了sys


实际上,函数中使用sys.argv的参数工作正常。有人知道这个问题的解决方案吗?

函数传入参数和变量名,而不在其中声明它们。您的代码应该如下所示

def load(arguments):
    # Your Code
    firstArg = arguments[0]

load(sys.argv)

不能将
sys.argv
用作函数参数。 只需重命名参数,它就会工作:

import sys
def load(args):
    # your logic

print(load(sys.argv))

如果要在函数中指定sys.argv[1],则不需要任何类型的参数。您可以使它成为一个不需要参数的函数

import sys

def load():
    with open(sys.argv[1]) as file:
        # code to execute...
        # code to execute...

load()
我的建议仅适用于只想使用一个命令行参数(在索引1处)打开一个文件的情况。如果希望使用其他命令行参数打开其他函数,则需要在函数中使用参数“args”(如David Teather所说)使代码更加灵活。
参数被设置为新的变量名,以便在函数范围内使用。在您的代码中,这就像您试图将“sys.argv”设置为函数名一样,因为它已经是一个函数,所以无法工作。

这没有意义。可以定义将sys.argv传递给的参数,但不能定义名为sys.argv的参数。