Python: jak przekierować wyjście z Podprocesem?

Co robię w wierszu poleceń:

cat file1 file2 file3 > myfile

Co chcę zrobić z Pythonem:

import subprocess, shlex
my_cmd = 'cat file1 file2 file3 > myfile'
args = shlex.split(my_cmd)
subprocess.call(args) # spits the output in the window i call my python program
Author: ferkulat, 2011-02-11

5 answers

Aktualizacja: os.system jest zniechęcany, choć nadal dostępny w Pythonie 3.


Użycie os.system:

os.system(my_cmd)

Jeśli naprawdę chcesz użyć podprocesu, oto rozwiązanie (w większości usunięte z dokumentacji podprocesu):

p = subprocess.Popen(my_cmd, shell=True)
os.waitpid(p.pid, 0)

OTOH, możesz całkowicie uniknąć wywołań systemowych:

import shutil

with open('myfile', 'w') as outfile:
    for infile in ('file1', 'file2', 'file3'):
        shutil.copyfileobj(open(infile), outfile)
 23
Author: Marcelo Cantos,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-17 01:02:08

Aby odpowiedzieć na oryginalne pytanie, aby przekierować wyjście, po prostu przekaż uchwyt otwartego pliku dla argumentu stdout na subprocess.call:

# Use a list of args instead of a string
input_files = ['file1', 'file2', 'file3']
my_cmd = ['cat'] + input_files
with open('myfile', "w") as outfile:
    subprocess.call(my_cmd, stdout=outfile)

Ale jak zauważyli inni, użycie w tym celu zewnętrznego polecenia, takiego jak cat, jest całkowicie obce.

 191
Author: Ryan Thompson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-11 20:56:41

@PoltoS chcę dołączyć kilka plików, a następnie przetworzyć plik wynikowy. Myślałem, że używanie cat to najprostsza alternatywa. Czy jest na to lepszy/lepszy sposób?

Oczywiście:

with open('myfile', 'w') as outfile:
    for infilename in ['file1', 'file2', 'file3']:
        with open(infilename) as infile:
            outfile.write(infile.read())
 4
Author: SingleNegationElimination,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-02-11 03:51:26

Interesującym przypadkiem byłoby uaktualnienie pliku poprzez dodanie do niego podobnego pliku. Wtedy nie trzeba by tworzyć nowego pliku w procesie. Jest to szczególnie przydatne w przypadku, gdy konieczne jest dołączenie dużego pliku. Oto jedna z możliwości korzystania z wiersza poleceń teminal bezpośrednio z Pythona.

import subprocess32 as sub

with open("A.csv","a") as f:
    f.flush()
    sub.Popen(["cat","temp.csv"],stdout=f)
 0
Author: DJJ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-06 19:47:57
size = 'ffprobe -v error -show_entries format=size -of default=noprint_wrappers=1:nokey=1 dump.mp4 > file'
proc = subprocess.Popen(shlex.split(size), shell=True)
time.sleep(1)
proc.terminate() #proc.kill() modify it by a suggestion
size = ""
with open('file', 'r') as infile:
    for line in infile.readlines():
        size += line.strip()

print(size)
os.remove('file')

Kiedy używasz podprocesu , proces musi zostać zabity.To jest przykład.Jeśli nie zabijesz procesu, Plik będzie pusty i możesz przeczytać nothing.It może działać na Windows .Nie mogę się upewnić, że działa na Unixie.

 0
Author: wyx,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-10 10:03:18