一般来说,我试图使用 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
您正在尝试调用read
which 是内置的 shell:
$ type read
read is a shell builtin
并且这个特定的 shell 内置程序没有等效的程序:
$ which read
$
因此PATH
,根据以下内容,Python 将无法在您的环境变量中找到它strace
:
[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
.
哦,在read
内置的shell 中,你也没有完成。如果您想以交互方式向用户询问某些内容,或者如果不需要交互,您可能应该只使用输入,只需使用argparse来解析用户作为命令行参数提供的内容,这样用户在键入时将有一些 shell 完成参数,通常不在标志上,因为用户 shell 不知道它们,但在路径上。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句