Эквивалентный из обратных галочек Bash в Python

Найденный чем-то как этот:

//javascript:
function playSound( url ){   
  document.getElementById("sound").innerHTML="<embed src='"+url+"' hidden=true autostart=true loop=false>";
} 
78
задан S471 31 March 2016 в 18:16
поделиться

5 ответов

output = os.popen('cat /tmp/baz').read()
92
ответ дан 24 November 2019 в 10:26
поделиться

Самый гибкий способ - использовать модуль subprocess :

import subprocess

out = subprocess.run(["cat", "/tmp/baz"], capture_output=True)
print("program output:", out)

capture_output был введен в Python 3.7, для более старых версий специальная функция check_output () Вместо этого можно использовать :

out = subprocess.check_output(["cat", "/tmp/baz"])

Вы также можете вручную создать объект подпроцесса, если вам нужен детальный контроль:

proc = subprocess.Popen(["cat", "/tmp/baz"], stdout=subprocess.PIPE)
(out, err) = proc.communicate()

Все эти функции поддерживают параметры ключевого слова для настройки того, как именно выполняется подпроцесс выполнен. Вы можете, например, использовать shell = True для выполнения программы через оболочку, если вам нужны такие вещи, как расширение имени файла * , но это имеет ограничения .

81
ответ дан 24 November 2019 в 10:26
поделиться
import os
foo = os.popen('cat /tmp/baz', 'r').read()
3
ответ дан 24 November 2019 в 10:26
поделиться

sth is right. You can also use os.popen(), but where available (Python 2.4+) subprocess is generally preferable.

However, unlike some languages that encourage it, it's generally considered bad form to spawn a subprocess where you can do the same job inside the language. It's slower, less reliable and platform-dependent. Your example would be better off as:

foo= open('/tmp/baz').read()

eta:

baz is a directory and I'm trying to get the contents of all the files in that directory

? cat on a directory gets me an error.

If you want a list of files:

import os
foo= os.listdir('/tmp/baz')

If you want the contents of all files in a directory, something like:

contents= []
for leaf in os.listdir('/tmp/baz'):
    path= os.path.join('/tmp/baz', leaf)
    if os.path.isfile(path):
        contents.append(open(path, 'rb').read())
foo= ''.join(contents)

or, if you can be sure there are no directories in there, you could fit it in a one-liner:

path= '/tmp/baz'
foo= ''.join(open(os.path.join(path, child), 'rb').read() for child in os.listdir(path))
26
ответ дан 24 November 2019 в 10:26
поделиться

Если вы используете subprocess.Popen, не забудьте указать размер буфера. Значение по умолчанию - 0, что означает «без буферизации», а не «выбрать разумное значение по умолчанию».

1
ответ дан 24 November 2019 в 10:26
поделиться
Другие вопросы по тегам:

Похожие вопросы: