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

标签 python bash popen tab-completion

一般来说,我尝试使用 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/

相关文章:

php - 如何从 php 中的 popen 打开的进程中获取输出?

php - 尝试在 PHP 中将 mysqldump -v 弹出并没有得到输出

python - 你能让 subprocess.Popen 在 stdout/stderr 中保留颜色吗?

Python pandas - 特定的合并/替换

python - 我可以在 Windows 上监控系统音频并进行分析吗?

bash - 奇怪的(无限)while 循环,代码在 "do"之前

linux - 检查 bash 脚本(由 cron 作业运行)是否在 Openshift 中运行

linux - 从 ping -c 中提取平均时间

.net - 从多页 TIFF 文件中删除/删除页面

python - XOR 运算符没有给出预期的结果?