gpt4 book ai didi

python - Python 中的 subprocess.call 没有此类文件或目录错误

转载 作者:行者123 更新时间:2023-11-30 22:33:00 25 4
gpt4 key购买 nike

一般来说,我尝试使用 Bash 而不是 Python 来从命令行读取,以便具有制表符补全功能。我想以最简单的方式做到这一点。但是,我无法让以下代码正常工作,我想了解导致问题的原因。

Python 脚本:

from subprocess import call
call(['read', '-ep', 'Path:', 'temporaryPath'])
print temporaryPath

错误回溯:

Traceback (most recent call last):
File "tmp.py", line 2, in <module>
call(['read', '-ep', 'Path:', 'temporaryPath'])
File "/usr/lib64/python2.6/subprocess.py", line 478, in call
p = Popen(*popenargs, **kwargs)
File "/usr/lib64/python2.6/subprocess.py", line 642, in __init__
errread, errwrite)
File "/usr/lib64/python2.6/subprocess.py", line 1238, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory

最佳答案

您正在尝试调用 shell 内置函数 read:

$ type read
read is a shell builtin

这个特定的 shell 内置程序没有等效的程序:

$ which read
$

根据 strace,Python 将无法在您的 PATH 环境变量中找到它:

[pid 17266] execve("/usr/local/bin/read", ["read", "-ep", "Path:", "temporaryPath"], [/* 70 vars */]) = -1 ENOENT (No such file or directory)
[pid 17266] execve("/usr/bin/read", ["read", "-ep", "Path:", "temporaryPath"], [/* 70 vars */]) = -1 ENOENT (No such file or directory)
[pid 17266] execve("/bin/read", ["read", "-ep", "Path:", "temporaryPath"], [/* 70 vars */]) = -1 ENOENT (No such file or directory)
[pid 17266] execve("/usr/local/games/read", ["read", "-ep", "Path:", "temporaryPath"], [/* 70 vars */]) = -1 ENOENT (No such file or directory)
[pid 17266] execve("/usr/games/read", ["read", "-ep", "Path:", "temporaryPath"], [/* 70 vars */]) = -1 ENOENT (No such file or directory)
[…]
[pid 17266] write(4, "OSError:", 8 <unfinished ...>

但是如果你明确要求 Python 使用 shell 来执行你的命令,shell 本身将能够运行其内置的read:

$ python3
Python 3.5.3 (default, Jan 19 2017, 14:11:04)
[GCC 6.3.0 20170118] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> subprocess.call('read', shell=True)
/bin/sh: 1: read: arg count
2
>>> subprocess.call('read foo', shell=True)
hello world
0

您现在遇到了一个新问题:shell 内置 read 将读取的值存储为 shell 变量,该变量将在调用 subprocess.call< 后随着 shell 的终止而消失。/.

哦,在内置的 read shell 中,你也没有完成功能。您可能应该只使用 input如果您想以交互方式向用户询问某些内容,或者不需要交互,只需使用 argparse解析用户作为命令行参数给出的内容,这样用户在键入参数时将有一些 shell 完成,通常不是在标志上,因为用户 shell 不知道它们,而是在路径上。

关于python - Python 中的 subprocess.call 没有此类文件或目录错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45284402/

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