len*_*klb 7 python stdin pipe variadic-functions eof
我有一个问题,涉及从Unix终端运行Python脚本时传递多个stdin参数.请考虑以下命令:
$ cat file.txt | python3.1 pythonfile.py
Run Code Online (Sandbox Code Playgroud)
然后,file.txt (通过"cat"命令访问)的内容将作为标准输入传递给python脚本.这很好(虽然更优雅的方式会很好).但是现在我必须传递另一个参数,这个参数只是一个将用作查询的单词(以及后来的两个单词).但我无法找到如何正确地做到这一点,因为猫管会产生错误.并且您不能input()在Python中使用该标准,因为它将导致EOF错误(您无法组合stdin和input()Python).
我有理由相信stdin标记可以做到这一点:
cat file.txt | python3.1 prearg - postarg
Run Code Online (Sandbox Code Playgroud)
更优雅的方法可能是将file.txt作为参数传递然后打开并阅读它.
ree*_*eem -1
虽然史蒂夫·巴恩斯的答案会起作用,但这并不是真正最“Pythonic”的做事方式。一种更优雅的方法是使用 sys 参数并在脚本本身中打开并读取文件。这样您就不必通过管道传输文件的输出并找出解决方法,您只需将文件名作为另一个参数传递即可。
类似于(在 python 脚本中):
import sys
with open(sys.argv[1].strip) as f:
file_contents = f.readlines()
# Do basic transformations on file contents here
transformed_file_contents = format(file_contents)
# Do the rest of your actions outside the with block,
# this will allow the file to close and is the idiomatic
# way to do this in python
Run Code Online (Sandbox Code Playgroud)
所以(在命令行中):
python3.1 pythonfile.py file.txt postarg1 postarg2
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5041 次 |
| 最近记录: |