Skip to content

Instantly share code, notes, and snippets.

@PythonDotLand
PythonDotLand / example.yaml
Created April 19, 2021 18:07
Example of a YAML config file
rest:
url: "https://example.org/primenumbers/v1"
port: 8443
prime_numbers: [2, 3, 5, 7, 11, 13, 17, 19]
@PythonDotLand
PythonDotLand / open_yaml.py
Created April 19, 2021 18:08
How to read YAML with Python
>>> import yaml
>>> with open('config.yml', 'r') as file
... prime_service = yaml.safe_load(file)
>>> prime_service
{'rest':
{ 'url': 'https://example.org/primenumbers/v1',
'port': 8443
},
'prime_numbers': [2, 3, 5, 7, 11, 13, 17, 19]}
@PythonDotLand
PythonDotLand / parse_yaml_string.py
Created April 19, 2021 18:09
How to parse a YAML string with Python
>>> import yaml
>>>
>>> names_yaml = """
... - 'eric'
... - 'justin'
... - 'mary-kate'
... """
>>>
>>> names = yaml.safe_load(names_yaml)
>>> names
import yaml
names_yaml = """
- 'eric'
- 'justin'
- 'mary-kate'
"""
with open('names.yaml', 'w') as file:
yaml.dump(names, file)
>>> import subprocess
>>> result = subprocess.run(['python3', '--version'])
Python 3.8.5
>>> result
CompletedProcess(args=['python3', '--version'], returncode=0)
>>> import subprocess
>>> result = subprocess.run(['python3', '--version'], capture_output=True, encoding='UTF-8')
>>> result
CompletedProcess(args=['python3', '--version'], returncode=0, stdout='Python 3.8.5\n', stderr='')
>>> import subprocess
>>> code = """
... for i in range(1, 3):
... print(f"Hello world {i}")
... """
>>> result = subprocess.run(['python3'], input=code, capture_output=True, encoding='UTF-8')
>>> print(result.stdout)
>>> print(result.stdout)
Hello world 1
>>> import subprocess
>>> subprocess.run(['ls', '-al'])
(a list of your directories will be printed)
>>> import subprocess
>>> result = subprocess.run(['ls -al | head -n 1'], shell=True)
total 396
>>> result
CompletedProcess(args=['ls -al | head -n 1'], returncode=0)
import subprocess
thedir = input()
# Don't do this:
result = subprocess.run([f'ls -al {thedir}'], shell=True)