KR_ProgramIO - somaz94/python-study GitHub Wiki
ํ์ด์ฌ ํ๋ก๊ทธ๋จ์ sys.argv
๋ฅผ ํตํด ๋ช
๋ น์ค ์ธ์๋ฅผ ๋ฐ์ ์ ์๋ค.
# ๊ธฐ๋ณธ ๋ช
๋ น์ค ์ธ์ ์ฒ๋ฆฌ
import sys
def main():
# argv[0]์ ์คํฌ๋ฆฝํธ ์ด๋ฆ
# argv[1:]์ ์ค์ ์ธ์๋ค
args = sys.argv[1:]
print(f"ํ๋ก๊ทธ๋จ ์ด๋ฆ: {sys.argv[0]}")
print(f"์ ๋ฌ๋ ์ธ์ ๊ฐ์: {len(args)}")
for i, arg in enumerate(args, 1):
print(f"์ธ์ {i}: {arg}")
if __name__ == "__main__":
main()
# example_args.py
import sys
def main():
if len(sys.argv) < 2:
print("์ฌ์ฉ๋ฒ: python example_args.py [์ธ์1] [์ธ์2] ...")
sys.exit(1)
args = sys.argv[1:]
# ์ธ์์ ํฉ๊ณ ๊ณ์ฐ (๋ชจ๋ ์ธ์๋ฅผ ์ซ์๋ก ๋ณํ ์๋)
try:
numbers = [float(arg) for arg in args]
total = sum(numbers)
print(f"์ธ์ ํฉ๊ณ: {total}")
except ValueError:
print("์ซ์๊ฐ ์๋ ์ธ์๊ฐ ํฌํจ๋์ด ์์ต๋๋ค.")
if __name__ == "__main__":
main()
์คํ ์์:
$ python example_args.py 10 20 30
ํ๋ก๊ทธ๋จ ์ด๋ฆ: example_args.py
์ ๋ฌ๋ ์ธ์ ๊ฐ์: 3
์ธ์ ํฉ๊ณ: 60.0
๋ ๋ณต์กํ ๋ช
๋ น์ค ์ธ์ ์ฒ๋ฆฌ๋ฅผ ์ํด argparse
๋ชจ๋์ ์ฌ์ฉํ ์ ์๋ค.
import argparse
def main():
# ํ์ ์์ฑ
parser = argparse.ArgumentParser(description='ํ๋ก๊ทธ๋จ ์ค๋ช
')
# ์ธ์ ์ถ๊ฐ
parser.add_argument('--name', type=str, help='์ด๋ฆ์ ์
๋ ฅํ์ธ์')
parser.add_argument('--age', type=int, help='๋์ด๋ฅผ ์
๋ ฅํ์ธ์')
# ์ธ์ ํ์ฑ
args = parser.parse_args()
# ์ธ์ ์ฌ์ฉ
if args.name:
print(f"์ด๋ฆ: {args.name}")
if args.age:
print(f"๋์ด: {args.age}")
if __name__ == "__main__":
main()
import argparse
def main():
# ํ์ ์์ฑ (ํ๋ก๊ทธ๋จ ์ค๋ช
๋ฐ ์ํ๋ก๊ทธ ์ถ๊ฐ)
parser = argparse.ArgumentParser(
description='์ฌ์ฉ์ ์ ๋ณด๋ฅผ ์ฒ๋ฆฌํ๋ ํ๋ก๊ทธ๋จ',
epilog='์์: python program.py --name ํ๊ธธ๋ --age 30 --hobbies ๋
์ ๋ฑ์ฐ'
)
# ํ์ ์์น ์ธ์
parser.add_argument('command', choices=['create', 'update', 'delete'],
help='์ํํ ๋ช
๋ น (create, update, delete)')
# ์ต์
์ธ์ (์ ํ์ )
parser.add_argument('--name', '-n', type=str, help='์ฌ์ฉ์ ์ด๋ฆ')
parser.add_argument('--age', '-a', type=int, help='์ฌ์ฉ์ ๋์ด')
# ๊ธฐ๋ณธ๊ฐ์ด ์๋ ์ธ์
parser.add_argument('--language', default='Python', help='์ ํธํ๋ ํ๋ก๊ทธ๋๋ฐ ์ธ์ด (๊ธฐ๋ณธ๊ฐ: Python)')
# bool ํ์์ ํ๋๊ทธ ์ธ์
parser.add_argument('--verbose', '-v', action='store_true', help='์์ธ ์ถ๋ ฅ ๋ชจ๋ ํ์ฑํ')
# ํ์ผ ํ์
์ธ์
parser.add_argument('--output', type=argparse.FileType('w'), help='์ถ๋ ฅ ํ์ผ')
# ์ฌ๋ฌ ๊ฐ์ ๋ฐ๋ ์ธ์
parser.add_argument('--hobbies', nargs='+', help='์ทจ๋ฏธ ๋ชฉ๋ก (๊ณต๋ฐฑ์ผ๋ก ๊ตฌ๋ถ)')
# ๊ณ ์ ๋ ๊ฐ์์ ์ธ์
parser.add_argument('--coordinates', nargs=2, type=float, help='x, y ์ขํ (2๊ฐ์ ๊ฐ)')
# ์ธ์ ํ์ฑ
args = parser.parse_args()
# ์์ธ ์ถ๋ ฅ ๋ชจ๋์ผ ๊ฒฝ์ฐ ๋ชจ๋ ์ธ์ ์ถ๋ ฅ
if args.verbose:
print("ํ๋ก๊ทธ๋จ ์คํ ์ ๋ณด:")
for arg, value in vars(args).items():
print(f" {arg}: {value}")
# ๋ช
๋ น ์ฒ๋ฆฌ
print(f"๋ช
๋ น '{args.command}' ์คํ ์ค...")
# ์ด๋ฆ๊ณผ ๋์ด๊ฐ ๋ชจ๋ ์ ๊ณต๋ ๊ฒฝ์ฐ์๋ง ์ฌ์ฉ์ ์ ๋ณด ์ถ๋ ฅ
if args.name and args.age:
print(f"์ฌ์ฉ์: {args.name}, {args.age}์ธ")
print(f"์ ํธ ์ธ์ด: {args.language}")
if args.hobbies:
print(f"์ทจ๋ฏธ: {', '.join(args.hobbies)}")
if args.coordinates:
print(f"์ขํ: ({args.coordinates[0]}, {args.coordinates[1]})")
# ์ถ๋ ฅ ํ์ผ์ด ์ ๊ณต๋ ๊ฒฝ์ฐ ํ์ผ์ ์ถ๋ ฅ
if args.output:
args.output.write(f"์ฒ๋ฆฌ๋ ๋ช
๋ น: {args.command}\n")
if args.name:
args.output.write(f"์ฌ์ฉ์: {args.name}\n")
args.output.close()
print(f"์ถ๋ ฅ์ด ํ์ผ์ ์ ์ฅ๋์์ต๋๋ค.")
if __name__ == "__main__":
main()
import argparse
def create_user(args):
print(f"์ฌ์ฉ์ ์์ฑ: {args.name}, {args.age}์ธ")
def update_user(args):
print(f"์ฌ์ฉ์ ์
๋ฐ์ดํธ: ID {args.id}")
if args.name:
print(f"์ด๋ฆ ๋ณ๊ฒฝ: {args.name}")
if args.age:
print(f"๋์ด ๋ณ๊ฒฝ: {args.age}")
def delete_user(args):
print(f"์ฌ์ฉ์ ์ญ์ : ID {args.id}")
if args.force:
print("๊ฐ์ ์ญ์ ๋ชจ๋")
def main():
# ๋ฉ์ธ ํ์ ์์ฑ
parser = argparse.ArgumentParser(description='์ฌ์ฉ์ ๊ด๋ฆฌ ์์คํ
')
subparsers = parser.add_subparsers(dest='command', help='์ํํ ๋ช
๋ น')
# create ์๋ธ๋ช
๋ น์ด ์ค์
create_parser = subparsers.add_parser('create', help='์ฌ์ฉ์ ์์ฑ')
create_parser.add_argument('--name', required=True, help='์ฌ์ฉ์ ์ด๋ฆ')
create_parser.add_argument('--age', type=int, required=True, help='์ฌ์ฉ์ ๋์ด')
create_parser.set_defaults(func=create_user)
# update ์๋ธ๋ช
๋ น์ด ์ค์
update_parser = subparsers.add_parser('update', help='์ฌ์ฉ์ ์ ๋ณด ์
๋ฐ์ดํธ')
update_parser.add_argument('--id', type=int, required=True, help='์ฌ์ฉ์ ID')
update_parser.add_argument('--name', help='์ ์ด๋ฆ')
update_parser.add_argument('--age', type=int, help='์ ๋์ด')
update_parser.set_defaults(func=update_user)
# delete ์๋ธ๋ช
๋ น์ด ์ค์
delete_parser = subparsers.add_parser('delete', help='์ฌ์ฉ์ ์ญ์ ')
delete_parser.add_argument('--id', type=int, required=True, help='์ฌ์ฉ์ ID')
delete_parser.add_argument('--force', '-f', action='store_true', help='ํ์ธ ์์ด ๊ฐ์ ์ญ์ ')
delete_parser.set_defaults(func=delete_user)
# ์ธ์ ํ์ฑ
args = parser.parse_args()
# ์๋ธ๋ช
๋ น์ด์ ๋ฐ๋ฅธ ํจ์ ์คํ
if hasattr(args, 'func'):
args.func(args)
else:
parser.print_help()
if __name__ == "__main__":
main()
import os
# ํ๊ฒฝ ๋ณ์ ์ฝ๊ธฐ
path = os.environ.get('PATH')
home = os.environ.get('HOME')
# ๊ธฐ๋ณธ๊ฐ์ผ๋ก ํ๊ฒฝ ๋ณ์ ์ฝ๊ธฐ
user = os.environ.get('USER', 'unknown')
debug = os.environ.get('DEBUG', 'False')
# ํ๊ฒฝ ๋ณ์ ์ค์
os.environ['MY_VAR'] = 'value'
os.environ['APP_ENV'] = 'development'
# ํ๊ฒฝ ๋ณ์ ์ญ์
if 'TEMP_VAR' in os.environ:
del os.environ['TEMP_VAR']
# ํ๊ฒฝ ๋ณ์ ํ์ฉ ์์
debug_mode = os.environ.get('DEBUG', 'False').lower() in ('true', '1', 'yes')
if debug_mode:
print("๋๋ฒ๊ทธ ๋ชจ๋๊ฐ ํ์ฑํ๋์์ต๋๋ค.")
# ํ๊ฒฝ ๋ณ์์ ๋ฐ๋ฅธ ์ค์ ๋ณ๊ฒฝ
env = os.environ.get('APP_ENV', 'development')
if env == 'production':
db_host = os.environ.get('DB_HOST_PROD')
log_level = 'ERROR'
elif env == 'staging':
db_host = os.environ.get('DB_HOST_STAGING')
log_level = 'WARNING'
else: # development
db_host = os.environ.get('DB_HOST_DEV', 'localhost')
log_level = 'DEBUG'
print(f"ํ๊ฒฝ: {env}, ๋ฐ์ดํฐ๋ฒ ์ด์ค ํธ์คํธ: {db_host}, ๋ก๊ทธ ๋ ๋ฒจ: {log_level}")
# ๋ชจ๋ ํ๊ฒฝ ๋ณ์ ์ถ๋ ฅ
print("\n--- ํ๊ฒฝ ๋ณ์ ๋ชฉ๋ก ---")
for key, value in sorted(os.environ.items()):
# ๊ฐ์ด ๋๋ฌด ๊ธธ๋ฉด ์๋ผ์ ํ์
if len(value) > 50:
value = value[:47] + "..."
print(f"{key}: {value}")
# pip install python-dotenv๋ก ๋จผ์ ์ค์น ํ์
from dotenv import load_dotenv
import os
# .env ํ์ผ ๋ก๋
load_dotenv() # ํ๋ก์ ํธ ๋ฃจํธ์ .env ํ์ผ ๋ก๋
# load_dotenv("/path/to/specific/.env") # ํน์ ๊ฒฝ๋ก์ .env ํ์ผ ๋ก๋
# ํ๊ฒฝ ๋ณ์ ์ฌ์ฉ
database_url = os.environ.get("DATABASE_URL")
api_key = os.environ.get("API_KEY")
debug = os.environ.get("DEBUG", "False").lower() == "true"
print(f"๋ฐ์ดํฐ๋ฒ ์ด์ค URL: {database_url}")
print(f"API ํค: {api_key}")
print(f"๋๋ฒ๊ทธ ๋ชจ๋: {debug}")
# .env ํ์ผ ์์:
# DATABASE_URL=postgresql://user:password@localhost/dbname
# API_KEY=your_secret_api_key
# DEBUG=True
import sys
# ํ์ค ์ถ๋ ฅ์ ํ์ผ๋ก ๋ฆฌ๋ค์ด๋ ์
with open('output.txt', 'w', encoding='utf-8') as f:
# ์๋ ํ์ค ์ถ๋ ฅ ์ ์ฅ
original_stdout = sys.stdout
sys.stdout = f
print("์ด ๋ด์ฉ์ ํ์ผ๋ก ์ ์ฅ๋ฉ๋๋ค.")
print("์ฌ๋ฌ ์ค์ ์ถ๋ ฅ์ด")
print("๋ชจ๋ ํ์ผ์ ๊ธฐ๋ก๋ฉ๋๋ค.")
# ํ์ค ์ถ๋ ฅ ๋ณต๊ตฌ
sys.stdout = original_stdout
print("์ด์ ์ฝ์์ ์ถ๋ ฅ๋ฉ๋๋ค.")
# ํ์ค ์ค๋ฅ ๋ฆฌ๋ค์ด๋ ์
with open('error.log', 'w', encoding='utf-8') as f:
original_stderr = sys.stderr
sys.stderr = f
print("์๋ฌ ๋ฉ์์ง", file=sys.stderr)
sys.stderr = original_stderr
# ํ์ค ์
๋ ฅ์ ํ์ผ์์ ์ฝ๊ธฐ
with open('input.txt', 'r', encoding='utf-8') as f:
original_stdin = sys.stdin
sys.stdin = f
# ํ์ผ์์ ์
๋ ฅ ์ฝ๊ธฐ
line = input("ํ๋กฌํํธ๋ ๋ฌด์๋ฉ๋๋ค: ")
print(f"ํ์ผ์์ ์ฝ์ ์ค: {line}")
# ์ฌ๋ฌ ์ค ์ฝ๊ธฐ
lines = []
try:
while True:
line = input()
lines.append(line)
except EOFError:
pass
sys.stdin = original_stdin
print(f"ํ์ผ์์ ์ด {len(lines)}์ค์ ์ฝ์์ต๋๋ค.")
import sys
import contextlib
# ํ์ค ์ถ๋ ฅ ๋ฆฌ๋ค์ด๋ ์
์ปจํ
์คํธ ๊ด๋ฆฌ์
@contextlib.contextmanager
def redirect_stdout(new_target):
old_target = sys.stdout
sys.stdout = new_target
try:
yield new_target
finally:
sys.stdout = old_target
# ํ์ค ์
๋ ฅ ๋ฆฌ๋ค์ด๋ ์
์ปจํ
์คํธ ๊ด๋ฆฌ์
@contextlib.contextmanager
def redirect_stdin(new_target):
old_target = sys.stdin
sys.stdin = new_target
try:
yield new_target
finally:
sys.stdin = old_target
# ์ฌ์ฉ ์์
with open('output.txt', 'w', encoding='utf-8') as f:
with redirect_stdout(f):
print("์ด ๋ด์ฉ์ ํ์ผ๋ก ๋ฆฌ๋ค์ด๋ ์
๋ฉ๋๋ค.")
print("์ปจํ
์คํธ๊ฐ ์ข
๋ฃ๋๋ฉด ์๋์ผ๋ก ๋ณต๊ตฌ๋ฉ๋๋ค.")
print("์ด์ ๋ค์ ์ฝ์์ ์ถ๋ ฅ๋ฉ๋๋ค.")
# ๋ฌธ์์ด ๋ฒํผ๋ก ํ์ค ์ถ๋ ฅ ๋ฆฌ๋ค์ด๋ ์
from io import StringIO
output_buffer = StringIO()
with redirect_stdout(output_buffer):
print("์ด ๋ด์ฉ์ ๋ฒํผ์ ์ ์ฅ๋ฉ๋๋ค.")
print("๋์ค์ ์ฒ๋ฆฌํ ์ ์์ต๋๋ค.")
# ์บก์ณ๋ ์ถ๋ ฅ ๊ฐ์ ธ์ค๊ธฐ
captured_output = output_buffer.getvalue()
print(f"์บก์ณ๋ ์ถ๋ ฅ: {captured_output}")
import logging
# ๊ธฐ๋ณธ ๋ก๊น
์ค์
logging.basicConfig(
level=logging.INFO, # ๋ก๊น
๋ ๋ฒจ ์ค์
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
# ๋ก๊ทธ ๋ฉ์์ง ์ถ๋ ฅ
logging.debug("๋๋ฒ๊ทธ ๋ฉ์์ง - ๊ฐ๋ฐ ์ค์๋ง ํ์ํ ์ธ๋ถ ์ ๋ณด")
logging.info("์ ๋ณด ๋ฉ์์ง - ์ ์ ์๋ ํ์ธ")
logging.warning("๊ฒฝ๊ณ ๋ฉ์์ง - ์ ์ฌ์ ๋ฌธ์ ์๋ฆผ")
logging.error("์ค๋ฅ ๋ฉ์์ง - ํ๋ก๊ทธ๋จ์ด ์์
์ ์ํํ ์ ์์")
logging.critical("์ฌ๊ฐํ ์ค๋ฅ - ํ๋ก๊ทธ๋จ์ด ๊ณ์ ์คํ๋ ์ ์์")
# ๋ก๊ทธ ๋ ๋ฒจ (๋ฎ์ ๊ฒ๋ถํฐ ๋์ ์)
# DEBUG(10) < INFO(20) < WARNING(30) < ERROR(40) < CRITICAL(50)
import logging
import logging.handlers
import os
from datetime import datetime
# ๋ก๊ทธ ๋๋ ํ ๋ฆฌ ์์ฑ
log_dir = 'logs'
if not os.path.exists(log_dir):
os.makedirs(log_dir)
# ํ์ฌ ๋ ์ง๋ก ๋ก๊ทธ ํ์ผ ์ด๋ฆ ์์ฑ
today = datetime.now().strftime('%Y-%m-%d')
log_file = os.path.join(log_dir, f'app_{today}.log')
# ๋ก๊ฑฐ ์์ฑ
logger = logging.getLogger('my_app')
logger.setLevel(logging.DEBUG) # ๋ก๊ฑฐ ์์ฒด์ ๋ ๋ฒจ ์ค์
# ํ์ผ ํธ๋ค๋ฌ ์์ฑ (ํ์ผ์ ๋ก๊ทธ ๊ธฐ๋ก)
file_handler = logging.FileHandler(log_file, encoding='utf-8')
file_handler.setLevel(logging.DEBUG) # ๋ชจ๋ ๋ก๊ทธ ์ ์ฅ
# ํ์ ํ์ผ ํธ๋ค๋ฌ (ํ์ผ ํฌ๊ธฐ์ ๋ฐ๋ผ ๋ก๊ทธ ํ์ผ ๋ถํ )
# max_bytes: ์ต๋ ํ์ผ ํฌ๊ธฐ, backup_count: ๋ณด๊ดํ ์ด์ ๋ก๊ทธ ํ์ผ ์
rotating_handler = logging.handlers.RotatingFileHandler(
os.path.join(log_dir, 'rotating.log'),
maxBytes=10000, # 10KB
backupCount=5,
encoding='utf-8'
)
rotating_handler.setLevel(logging.INFO)
# ์๊ฐ ๊ธฐ๋ฐ ํ์ ํธ๋ค๋ฌ (๋งค์ผ ์์ ์ ์ ๋ก๊ทธ ํ์ผ ์์ฑ)
timed_handler = logging.handlers.TimedRotatingFileHandler(
os.path.join(log_dir, 'daily.log'),
when='midnight',
interval=1, # 1์ผ๋ง๋ค
backupCount=7, # 1์ฃผ์ผ์น ๋ณด๊ด
encoding='utf-8'
)
timed_handler.setLevel(logging.WARNING)
# ์ฝ์ ํธ๋ค๋ฌ (ํฐ๋ฏธ๋์ ๋ก๊ทธ ์ถ๋ ฅ)
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO) # ์ ๋ณด ๋ ๋ฒจ ์ด์๋ง ์ฝ์์ ์ถ๋ ฅ
# ํฌ๋งทํฐ ์์ฑ
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(filename)s:%(lineno)d - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
# ํธ๋ค๋ฌ์ ํฌ๋งทํฐ ์ถ๊ฐ
file_handler.setFormatter(formatter)
rotating_handler.setFormatter(formatter)
timed_handler.setFormatter(formatter)
console_handler.setFormatter(formatter)
# ๋ก๊ฑฐ์ ํธ๋ค๋ฌ ์ถ๊ฐ
logger.addHandler(file_handler)
logger.addHandler(rotating_handler)
logger.addHandler(timed_handler)
logger.addHandler(console_handler)
# ๋ก๊ทธ ๋ฉ์์ง ์ถ๋ ฅ
logger.debug("๋๋ฒ๊ทธ ๋ฉ์์ง - ํ์ผ์๋ง ๊ธฐ๋ก")
logger.info("์ ๋ณด ๋ฉ์์ง - ํ์ผ๊ณผ ์ฝ์์ ์ถ๋ ฅ")
logger.warning("๊ฒฝ๊ณ ๋ฉ์์ง - ๋ชจ๋ ํธ๋ค๋ฌ์ ์ถ๋ ฅ")
logger.error("์ค๋ฅ ๋ฉ์์ง")
logger.critical("์ฌ๊ฐํ ์ค๋ฅ ๋ฉ์์ง")
# ์์ธ ์ ๋ณด ํฌํจ
try:
result = 10 / 0
except Exception as e:
logger.exception("์์ธ ๋ฐ์: 0์ผ๋ก ๋๋๊ธฐ ์๋") # traceback ์๋ ํฌํจ
import subprocess
# ๊ฐ๋จํ ๋ช
๋ น ์คํ
result = subprocess.run(['echo', 'Hello, World!'], capture_output=True, text=True)
print(f"๋ฐํ ์ฝ๋: {result.returncode}")
print(f"ํ์ค ์ถ๋ ฅ: {result.stdout}")
print(f"ํ์ค ์ค๋ฅ: {result.stderr}")
# ์ ๋ช
๋ น ์คํ
result = subprocess.run('ls -l | grep ".py"', shell=True, capture_output=True, text=True)
print(f"ํ์ด์ฌ ํ์ผ ๋ชฉ๋ก:\n{result.stdout}")
# ๋ช
๋ น ์คํ ์ ์
๋ ฅ ์ ๊ณต
input_data = "Hello from Python"
result = subprocess.run(['cat'], input=input_data, capture_output=True, text=True)
print(f"'cat' ๋ช
๋ น ๊ฒฐ๊ณผ: {result.stdout}")
# ์์ธ ์ฒ๋ฆฌ
try:
result = subprocess.run(['non_existent_command'], check=True) # check=True๋ ์ค๋ฅ ์ ์์ธ ๋ฐ์
except subprocess.CalledProcessError as e:
print(f"๋ช
๋ น ์คํ ์ค ์ค๋ฅ ๋ฐ์: {e}")
except FileNotFoundError as e:
print(f"๋ช
๋ น์ ์ฐพ์ ์ ์์: {e}")
# ํ์ฌ ํ๊ฒฝ ๋ณ์๋ฅผ ์์๋ฐ์ ํน์ ๋ณ์๋ง ์ถ๊ฐ ๋๋ ๋ณ๊ฒฝ
import os
env = os.environ.copy()
env['CUSTOM_VAR'] = 'value'
result = subprocess.run(['env'], env=env, capture_output=True, text=True)
print("ํ๊ฒฝ ๋ณ์ ๋ชฉ๋ก ์ค ์ฌ์ฉ์ ์ ์ ๋ณ์:")
for line in result.stdout.splitlines():
if line.startswith('CUSTOM_VAR='):
print(line)
import subprocess
import time
# Popen์ผ๋ก ํ๋ก์ธ์ค ์์
process = subprocess.Popen(
['ping', 'localhost'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True
)
# ๋น๋๊ธฐ์ ์ผ๋ก ๋ค๋ฅธ ์์
์ํ ๊ฐ๋ฅ
print("ํ๋ก์ธ์ค๊ฐ ์คํ ์ค์
๋๋ค...")
time.sleep(2)
# ํ๋ก์ธ์ค ์ํ ํ์ธ
if process.poll() is None:
print("ํ๋ก์ธ์ค๊ฐ ์์ง ์คํ ์ค์
๋๋ค.")
# ์คํ ์ค์ธ ํ๋ก์ธ์ค์์ ์ค์๊ฐ์ผ๋ก ์ถ๋ ฅ ์ฝ๊ธฐ
for i in range(5): # 5์ค๋ง ์ฝ๊ธฐ
output = process.stdout.readline()
if output:
print(f"์ค์๊ฐ ์ถ๋ ฅ: {output.strip()}")
else:
break
# ํ์ํ๋ฉด ํ๋ก์ธ์ค ์ข
๋ฃ
process.terminate()
try:
process.wait(timeout=5) # 5์ด ๋์ ์ข
๋ฃ ๋๊ธฐ
except subprocess.TimeoutExpired:
print("ํ๋ก์ธ์ค๊ฐ ์ ์์ ์ผ๋ก ์ข
๋ฃ๋์ง ์์ ๊ฐ์ ์ข
๋ฃํฉ๋๋ค.")
process.kill()
# ํ๋ก์ธ์ค ์๋ฃ ๊ธฐ๋ค๋ฆฌ๊ธฐ ๋ฐ ์ถ๋ ฅ ์ฝ๊ธฐ
stdout, stderr = process.communicate()
print(f"๋ฐํ ์ฝ๋: {process.returncode}")
print(f"ํ์ค ์ถ๋ ฅ ์ผ๋ถ: {stdout[:100]}") # ์ฒ์ 100์๋ง ํ์
print(f"ํ์ค ์ค๋ฅ: {stderr}")
# ํ์ดํ๋ผ์ธ ๊ตฌํ (์ฌ๋ฌ ๋ช
๋ น ์ฐ๊ฒฐ)
ps_process = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE, text=True)
grep_process = subprocess.Popen(['grep', 'python'], stdin=ps_process.stdout, stdout=subprocess.PIPE, text=True)
ps_process.stdout.close() # ps_process์ stdout์ ๋ซ์์ EOF ์ ํธ ์ ๋ฌ
output, _ = grep_process.communicate()
print("\nPython ๊ด๋ จ ํ๋ก์ธ์ค:")
print(output)
โ ํ๋ก๊ทธ๋จ ์ ์ถ๋ ฅ ๋ชจ๋ฒ ์ฌ๋ก:
- ๋ช
๋ น์ค ์ธ์๋
argparse
๋ฅผ ์ฌ์ฉํ์ฌ ์ฒด๊ณ์ ์ผ๋ก ๊ตฌ์ฑํ๋ค - ๊ฐ ์ธ์์ ๋์๋ง ๋ฉ์์ง๋ฅผ ํญ์ ์ ๊ณตํ๋ค
- ๋ฏผ๊ฐํ ์ ๋ณด(๋น๋ฐ๋ฒํธ, API ํค ๋ฑ)๋ ํ๊ฒฝ ๋ณ์๋ก ๊ด๋ฆฌํ๋ค
- ํ๊ฒฝ ๋ณ์๋ ํญ์ ๊ธฐ๋ณธ๊ฐ๊ณผ ํจ๊ป ์ฌ์ฉํ๋ค (
os.environ.get('VAR', 'default')
) - ๋ก๊น
์
print
๋์logging
๋ชจ๋์ ํ์ฉํ๋ค - ๋ก๊ทธ ๋ ๋ฒจ์ ์ ์ ํ ๊ตฌ๋ถํ์ฌ ๋๋ฒ๊น ๊ณผ ์ด์์ ๊ตฌ๋ถํ๋ค
- ์ธ๋ถ ํ๋ก์ธ์ค ์คํ ์
subprocess.run()
์check=True
์ต์ ์ ์ฌ์ฉํ์ฌ ์ค๋ฅ๋ฅผ ํ์ธํ๋ค - ์ธ๋ถ ๋ช ๋ น ์คํ ์ ์ฌ์ฉ์ ์ ๋ ฅ์ ์ง์ ์ ๋ฌํ์ง ์๊ณ ์ธ์ ๋ฆฌ์คํธ๋ฅผ ์ฌ์ฉํ๋ค (๋ช ๋ น์ด ์ฃผ์ ๊ณต๊ฒฉ ๋ฐฉ์ง)
- ํ์ค ์ ์ถ๋ ฅ ๋ฆฌ๋ค์ด๋ ์ ํ์๋ ๋ฐ๋์ ์๋ ์ํ๋ก ๋ณต๊ตฌํ๋ค
- ์ฅ๊ธฐ ์คํ ํ๋ก์ธ์ค๋ ์๊ฐ ์ด๊ณผ ์ฒ๋ฆฌ ๋ก์ง์ ๊ตฌํํ๋ค