From 98f1cf845dbb8d6f4c29a51801fb529ceb9efeb5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 11 Jan 2020 20:11:43 +0100 Subject: [PATCH] Shell commands --- README.md | 23 +++++++++++++++-------- index.html | 17 +++++++++++------ 2 files changed, 26 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 948342a..fee1720 100644 --- a/README.md +++ b/README.md @@ -1677,14 +1677,21 @@ import os = os.popen('').read() ``` -#### Using subprocess: -```python ->>> import subprocess, shlex ->>> a = subprocess.run(shlex.split('ls -a'), stdout=subprocess.PIPE) ->>> a.stdout -b'.\n..\nfile1.txt\nfile2.txt\n' ->>> a.returncode -0 +#### Sends '1 + 1' to calculator and captures its output: +```python +>>> from subprocess import run +>>> run('bc', input='1 + 1\n', capture_output=True, encoding='utf-8') +CompletedProcess(args='bc', returncode=0, stdout='2\n', stderr='') +``` + +#### Sends 'test.in' to calculator running in standard mode and saves its output to 'test.out': +```python +>>> from shlex import split +>>> os.popen('echo 1 + 1 > test.in') +>>> run(split('bc -s'), stdin=open('test.in'), stdout=open('test.out', 'w')) +CompletedProcess(args=['bc', '-s'], returncode=0) +>>> os.popen('cat test.out').read() +'2\n' ``` diff --git a/index.html b/index.html index efbfcf4..7ef0cea 100644 --- a/index.html +++ b/index.html @@ -1522,12 +1522,17 @@ shutil.rmtree(<path>) # Deletes n <str> = os.popen('<shell_command>').read() -

Using subprocess:

>>> import subprocess, shlex
->>> a = subprocess.run(shlex.split('ls -a'), stdout=subprocess.PIPE)
->>> a.stdout
-b'.\n..\nfile1.txt\nfile2.txt\n'
->>> a.returncode
-0
+

Sends '1 + 1' to calculator and captures its output:

>>> from subprocess import run
+>>> run('bc', input='1 + 1\n', capture_output=True, encoding='utf-8')
+CompletedProcess(args='bc', returncode=0, stdout='2\n', stderr='')
+
+ +

Sends 'test.in' to calculator running in standard mode and saves its output to 'test.out':

>>> from shlex import split
+>>> os.popen('echo 1 + 1 > test.in')
+>>> run(split('bc -s'), stdin=open('test.in'), stdout=open('test.out', 'w'))
+CompletedProcess(args=['bc', '-s'], returncode=0)
+>>> os.popen('cat test.out').read()
+'2\n'
 

#JSON

Text file format for storing collections of strings and numbers.

import json