簡體   English   中英

我已經將bash命令集成到了我的Python代碼中-如何獲取此命令以從Shell中獲取輸入?

[英]I have integrated a bash command into my Python code - how can I get this command to take an input from the shell?

我已經在我的Python腳本中添加了一個bash命令-該bash命令用於線性化一個輸入文件(即,獲取一個包含多行的文件,然后將其合並為一行)。 當我手動為命令寫入文件名時(在本示例中,輸入文件稱為input.txt),它會起作用:

import subprocess

holder = subprocess.Popen('perl -ne "chomp;print;" input.txt', shell=True, stdout=subprocess.PIPE).stdout.read()

print(holder)

但是,我希望此bash命令采用用戶在命令行中指定的文件名稱,並將其線性化。

我已經嘗試使用%s實現此目的:

import subprocess
import sys
import os

path = sys.argv[1]
file = open(path, 'r')
inp = file.read()

holder = subprocess.Popen('perl -ne "chomp;print;" %s' % inp, shell=True, stdout=subprocess.PIPE).stdout.read()

print(holder)

但是,當我嘗試這樣做時,shell凍結並且不顯示任何輸出,並且bash $提示符也不顯示,沒有錯誤消息。

我想知道在這種情況下是否有添加用戶輸入的有效方法,希望能對您有所幫助。

編輯:只是為了澄清,這是我在shell中鍵入的內容以第二個示例運行程序:

$ python3 program.py input.txt

為什么不像這樣將輸入路徑直接輸入到子流程呢? 但是我對為什么要在python中使用perl感到有些困惑。

import subprocess
import sys
import os

path = sys.argv[1]

holder = subprocess.Popen('perl -ne "chomp;print;" %s' % path, shell=True, stdout=subprocess.PIPE).stdout.read()

print(holder)

輸入以下示例:

test.txt
i
i
i
i
i

該程序將輸出:

python linearize.py test.txt
b'iiiii'
import subprocess
import sys
import os

holder = subprocess.Popen('perl -ne "chomp;print;" {}'.format(sys.argv[1]), shell=True, stdout=subprocess.PIPE).stdout.read()

print(holder)

但為什么 ? 為什么要使用python調用perl腳本? Python具有在同一進程中使用本機,可調試和跨平台代碼進行相同操作所需的所有工具。 這沒有道理,這是一個壞習慣。

import sys

with open(sys.argv[1]) as input_file:
    holder = ''.join(input_file.read().splitlines())

print(holder)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM