简体   繁体   English

Unix shell上的python中的sys.stdin

[英]sys.stdin in python on unix shell

I am writing a python program through a unix shell. 我正在通过unix外壳编写python程序。 While I have written the program, I had to hard code my data in. However my goal is to be able to be able to stdin the data through the shell like this 在编写程序的同时,我不得不对数据进行硬编码。但是,我的目标是能够像这样通过shell编写数据。

python3 sample.py data.txt

Where sample.py is the program and data.txt is the data. 其中sample.py是程序,data.txt是数据。 Data.txt contains two column of data seperated by a tab. Data.txt包含由选项卡分隔的两列数据。 Then I have print to make sure it is working. 然后,我进行打印以确保其正常工作。 The way I wrote the code to read the data in is as follows 我编写代码以读取数据的方式如下

for line in sys.stdin:
    words = re.split(r'\t',line)
    print(words)

Splitting the content of the lines the tab, and printing to make sure it is working. 拆分选项卡行的内容,然后进行打印以确保其正常工作。 When running line "python3 sample.py data.txt", it does nothing, however the program will not exit like there is an infinite loop or something. 当运行“ python3 sample.py data.txt”行时,它什么都不做,但是程序不会像存在无限循环之类的那样退出。 How can I get this to print? 我该如何打印?

With

python3 sample.py data.txt

you are passing data.txt as an argument . 您将data.txt作为参数传递。 To pass its content as input (to stdin), do: 要将其内容作为输入传递给(标准输入),请执行以下操作:

python3 sample.py < data.txt

The redirection operator < is a shell construct and refers to the stdin. 重定向运算符<是一个shell构造,它引用标准输入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM