Using_Python_to_Interact_wi.../module4.ipynb
2025-01-25 02:11:31 +03:00

325 lines
8.1 KiB
Plaintext
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Reading data interactively"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"cat hello.py\n",
"#!/usr/bin/env python3\n",
"\n",
"name = input(\"Please enter your name: \")\n",
"print(\"Hello, \" + name)\n",
"\n",
"# ./hello.py \n",
"# Please enter your name: Roger\n",
"# #Output will be Hello, Roger"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# defining a function called 'to_seconds' which takes hours, minutes and seconds as\n",
"# inputs and returns their total equivalent in seconds by multiplying each with its\n",
"# corresponding factor (3600 for hours, 60 for minutes) and then summing them up.\n",
"def to_seconds(hours, minutes, seconds):\n",
" return hours*3600+minutes*60+seconds\n",
"\n",
"# Print a welcome message to the user\n",
"print(\"Welcome to this time converter\")\n",
"\n",
"# set 'cont' variable to \"y\" initially for entering into while loop.\n",
"cont = \"y\"\n",
"\n",
"# while condition is true (user wants to continue), keep asking the\n",
"# number of hours, minutes and seconds from the user and print their total equivalent\n",
"# in seconds by calling 'to_seconds' function. Ask if they want to do another conversion.\n",
"# If not, break the loop.\n",
"while(cont.lower() == \"y\"):\n",
" hours = int(input(\"Enter the number of hours: \"))\n",
" minutes = int(input(\"Enter the number of minutes: \"))\n",
" seconds = int(input(\"Enter the number of seconds: \"))\n",
"\n",
" print(\"That's {} seconds\".format(to_seconds(hours, minutes, seconds)))\n",
" print()\n",
" cont = input(\"Do you want to do another conversion? [y to continue] \")\n",
" \n",
"# print a goodbye message when user decides to stop the program.\n",
"print(\"Goodbye!\")\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Standard streams\n",
"I/O Streams"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"cat streams.py\n",
"#!/usr/bin/env python3\n",
"\n",
"data = input(\"This will come from STDIN: \")\n",
"print(\"Now we write it to STDOUT: \" + data)\n",
"print(\"Now we generate an error to STDERR: \" + data + 1)\n",
"\n",
"./streams.py \n",
"This will come from STDIN: Python Rocks!\n",
"Now we write it to STDOUT: Python Rocks!\n",
"\n",
"cat greeting.txt \n",
"Well hello there, STDOUT\n",
"\n",
"cat greeting.txt \n",
"Well hello there, STDOUT\n",
"\n",
"ls -z"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Environment variables"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"HOME: /config\n",
"SHELL: \n",
"FRUIT: \n"
]
}
],
"source": [
"# echo $PATH\n",
"# /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\n",
"# cat variables.py\n",
"#!/usr/bin/env python3\n",
"import os\n",
"print(\"HOME: \" + os.environ.get(\"HOME\", \"\"))\n",
"print(\"SHELL: \" + os.environ.get(\"SHELL\", \"\"))\n",
"print(\"FRUIT: \" + os.environ.get(\"FRUIT\", \"\"))\n",
"# ./variables.py\n",
"# export FRUIT=Pineapple\n",
"# ./variables.py"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Command-Line Arguments and Exit Status"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"cat parameters.py \n",
"#!/usr/bin/env python3\n",
"import sys\n",
"print(sys.argv)\n",
"\n",
"./parameters.py\n",
"['./parameters.py'] \n",
"\n",
"./parameters.py one two three\n",
"['./parameters.py', 'one', 'two', 'three']\n",
"\n",
"\n",
"wc variables.py\n",
"7 19 174 variables.py \t\n",
"echo $?\n",
"0\n",
"\n",
"wc notpresent.sh\n",
"wc: notpresent.sh: No such file or directory\n",
"echo $?\n",
"1\n",
"\n",
"#!/usr/bin/env python3\n",
"\n",
"import os\n",
"import sys\n",
"\n",
"filename = sys.argv[1]\n",
"\n",
"if not os.path.exists(filename):\n",
" with open(filename, \"w\") as f:\n",
" f.write(\"New file created\\n\")\n",
"else:\n",
" print(\"Error, the file {} already exists!\".format(filename))\n",
" sys.exit(1)\n",
"\n",
"./create_file.py example\n",
"echo $?\n",
"0\n",
"\n",
"cat example \n",
"New file created\n",
"./create_file.py example\n",
"Error, the file example already exists!\n",
"echo $?\n",
"1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Python 2 and Python 3 handle input and raw_input differently.\n",
"\n",
"In Python 2\n",
"\n",
"- input(x) is roughly the same as eval(raw_input(x))\n",
"- raw_input() is preferred, unless the author wants to support evaluating string expressions.\n",
"- eval() is used to evaluate string expressions."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
">>> my_number = input('Please Enter a Number: \\n')\n",
"Please Enter a Number: \n",
"123 + 1\n",
">>> print(my_number)\n",
"123 + 1\n",
">>> type(my_number)\n",
"<class 'str'>\n",
"\n",
"\n",
">>> my_number = input('Please Enter a Number: \\n')\n",
"Please Enter a Number: \n",
"123 + 1\n",
">>> print(my_number)\n",
"123 + 1\n",
">>> eval(my_number)\n",
"124"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Subprocesses"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Running system commands in Python"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import subprocess\n",
"subprocess.run([\"date\"])\n",
"subprocess.run([\"sleep\", \"2\"])\n",
"result = subprocess.run([\"ls\", \"this_file_does_not_exist\"])\n",
"print(result.returncode)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Obtaining the output of a system command"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"result = subprocess.run([\"host\", \"8.8.8.8\"], capture_output=True)\n",
"\n",
"result = subprocess.run([\"host\", \"8.8.8.8\"], capture_output=True)\n",
"print(result.returncode)\n",
"\n",
"result = subprocess.run([\"host\", \"8.8.8.8\"], capture_output=True)\n",
"print(result.stdout)\n",
"\n",
"result = subprocess.run([\"host\", \"8.8.8.8\"], capture_output=True)\n",
"print(result.stdout.decode().split())"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import subprocess\n",
"result = subprocess.run([\"rm\", \"does_not_exist\"], capture_output=True)\n",
"\n",
"import subprocess\n",
"result = subprocess.run([\"rm\", \"does_not_exist\"], capture_output=True)\n",
"print(result.returncode)\n",
"\n",
"import subprocess\n",
"result = subprocess.run([\"rm\", \"does_not_exist\"], capture_output=True)\n",
"print(result.returncode)\n",
"print(result.stdout)\n",
"print(result.stderr)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.3"
}
},
"nbformat": 4,
"nbformat_minor": 2
}