gpt4 book ai didi

python + subprocess.check_call : how to call functions in python?

转载 作者:太空宇宙 更新时间:2023-11-03 18:11:34 24 4
gpt4 key购买 nike

所以最初的问题是:

# works(1)
subprocess.check_call(["ls", "-l"])

#works(2), but "-l" argument not passed to called process
subprocess.check_call(["ls", "-l"], shell=True)

#works(3) again
subprocess.check_call("ls -l", shell=True)

#Exception(4): "bufsize must be an integer"
subprocess.check_call("ls", "-l", shell=True)

如果查看文档( https://docs.python.org/2/library/subprocess.html ),subprocess.check_call 具有这样的签名:subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False)

我知道Python中的函数是这样的:def f(*args, **kwargs),但是, * 是什么意思?它与*args相同吗?

无论如何,之后在文档中注意到:

The full function signature is the same as that of the Popen constructor

Popen 构造函数签名是:

Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0)

所以很清楚为什么(4)失败了,但为什么(2)却以错误的方式工作?如何阅读这个奇怪的符号:args, *, stdin=None

更新

我找到了为什么 (2) 不起作用。谢谢回复我明白了从语法的角度来看这是正确的。所以我运行 strace,并看到 python 以错误的方式将参数传递给“/bin/sh”。已知错误:http://bugs.python.org/issue6689并被拒绝。这真是令人悲伤。

最佳答案

(2) 是正确的。列表["ls", "-l"] 作为args 传递给方法(Popen.__init__)。

<小时/>

* 表示后面的参数是 Keyword-only arguments 。它是在 Python 3.x 中引入的。但正如您在源代码中看到的那样,实际签名不使用仅关键字参数。因此,您可以传递 args 以外的参数的位置参数。

关于python + subprocess.check_call : how to call functions in python?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25826098/

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