ã¯ããã«
ã·ã¹ãã éçºãããŒã¿åŠçãæ¥ã ã®èªååã¿ã¹ã¯ã«ãããŠãPythonãšã·ã§ã«ã¹ã¯ãªããïŒsh/BashïŒã¯éåžžã«åŒ·åãªããŒã«ã§ããPythonã¯ãã®è±å¯ãªã©ã€ãã©ãªãšé«ãå¯èªæ§ã§è€éãªããžãã¯ãããŒã¿åŠçãåŸæãšããäžæ¹ã·ã§ã«ã¹ã¯ãªããã¯ãã¡ã€ã«æäœãã³ãã³ãå®è¡ããã€ãã©ã€ã³åŠçãªã©ãOSã¬ãã«ã®ã¿ã¹ã¯ãç°¡æœã«èšè¿°ã§ããŸãã
ãããäºã€ã®èšèªã¯ãããããåŸæåéãç°ãªããŸãããçµã¿åãããããšã§äºãã®çæãè£ããããå¹ççã§ãã¯ãã«ãªãœãªã¥ãŒã·ã§ã³ãæ§ç¯ã§ããŸããäŸãã°ãã·ã§ã«ã¹ã¯ãªããã§ãã¡ã€ã«ã®äžæ¬åŠçãè¡ãããã®çµæãPythonã§è©³çŽ°ã«åæããããããã¯Pythonã§çæããããŒã¿ãã·ã§ã«ã³ãã³ãã§ä»ã®ã·ã¹ãã ã«é£æºãããªã©ãæ§ã ãªå¿çšãèããããŸããð§
ãã®ããã°ã§ã¯ãPythonãšã·ã§ã«ã¹ã¯ãªãããé£æºãããããã®å
·äœçãªæ¹æ³ãç¹ã«Pythonã®æšæºã©ã€ãã©ãªã§ããsubprocess
ã¢ãžã¥ãŒã«ã®äœ¿ãæ¹ããé£æºãããã«å®¹æã«ãã䟿å©ãªPythonã©ã€ãã©ãªsh
ã«ã€ããŠè©³ãã解説ããŸãããŸããã·ã§ã«ã¹ã¯ãªããåŽããPythonã¹ã¯ãªãããå®è¡ããæ¹æ³ããé£æºãã¹ã ãŒãºã«è¡ãããã®å®è·µçãªãã¯ããã¯ã泚æç¹ã«ã觊ããŠãããŸãã
Pythonããã·ã§ã«ã³ãã³ããå®è¡ããæ¹æ³
Pythonã¹ã¯ãªããå ããå€éšã®ã·ã§ã«ã³ãã³ããå®è¡ããå¿ èŠãããå Žé¢ã¯å€ã ãããŸããããã§ã¯ããã®ããã®äž»èŠãªæ¹æ³ãããã€ã玹ä»ããŸãã
1. os.system (éæšå¥š)
æãç°¡åãªæ¹æ³ã®äžã€ã§ãããçŸåšã§ã¯éæšå¥šãšãããŠããŸãã
import os
# äŸ: ã«ã¬ã³ããã£ã¬ã¯ããªã®å
容ã衚瀺
return_code = os.system("ls -l")
print(f"çµäºã³ãŒã: {return_code}")
- ã»ãã¥ãªãã£ãªã¹ã¯: ãŠãŒã¶ãŒããã®å ¥åãã³ãã³ãæååã«å«ããå Žåãã·ã§ã«ã€ã³ãžã§ã¯ã·ã§ã³æ»æã«å¯ŸããŠè匱ã§ãã
- æè»æ§ã®æ¬ åŠ: ã³ãã³ãã®æšæºåºåãæšæºãšã©ãŒåºåãç°¡åã«ååŸã»å¶åŸ¡ããããšãã§ããŸãããæ»ãå€ãšããŠåŸãããã®ã¯çµäºã³ãŒãã®ã¿ã§ãã
- ãšã©ãŒãã³ããªã³ã°: ã³ãã³ãå®è¡æã®ãšã©ãŒã詳现ã«ãã³ããªã³ã°ããã®ãé£ããã§ãã
subprocess
ã¢ãžã¥ãŒã«ã®äœ¿çšãæšå¥šãããŠããŸãã2. subprocessã¢ãžã¥ãŒã« (æšå¥š) âš
Python 3.5以éã§æšå¥šããããå€éšããã»ã¹ãèµ·åã»ç®¡çããããã®æšæºã¢ãžã¥ãŒã«ã§ããos.system
ãããã¯ããã«é«æ©èœã§å®å
šã§ãã
2.1. subprocess.run()
ã·ã³ãã«ã«ã³ãã³ããå®è¡ãããã®å®äºãåŸ ã€å Žåã«æããã䜿ãããé¢æ°ã§ããPython 3.5ã§å°å ¥ãããŸããã
import subprocess
# ã³ãã³ãããªã¹ã圢åŒã§æž¡ãã®ãå®å
š
try:
# capture_output=True ã§æšæºåºåãšæšæºãšã©ãŒãååŸ
# text=True ã§åºåãæååãšããŠãã³ãŒã (Python 3.7+)
# check=True ã§çµäºã³ãŒããéãŒãã®å Žåã« CalledProcessError äŸå€ãçºçããã
result = subprocess.run(["ls", "-l"], capture_output=True, text=True, check=True)
print("ã³ãã³ãæåïŒ")
print("æšæºåºå:")
print(result.stdout)
print("æšæºãšã©ãŒ:")
print(result.stderr) # æåæã¯é垞空
print(f"çµäºã³ãŒã: {result.returncode}")
except FileNotFoundError:
print("ãšã©ãŒ: ã³ãã³ããèŠã€ãããŸããã")
except subprocess.CalledProcessError as e:
print(f"ãšã©ãŒ: ã³ãã³ãå®è¡ã«å€±æããŸãã (çµäºã³ãŒã: {e.returncode})")
print("æšæºåºå:")
print(e.stdout)
print("æšæºãšã©ãŒ:")
print(e.stderr)
except Exception as e:
print(f"äºæãã¬ãšã©ãŒãçºçããŸãã: {e}")
# ååšããªããã¡ã€ã«ã衚瀺ããããšããŠãšã©ãŒãèµ·ããäŸ
try:
subprocess.run(["ls", "ååšããªããã¡ã€ã«"], capture_output=True, text=True, check=True)
except subprocess.CalledProcessError as e:
print("\n--- ãšã©ãŒçºçæã®äŸ ---")
print(f"ãšã©ãŒ: ã³ãã³ãå®è¡ã«å€±æããŸãã (çµäºã³ãŒã: {e.returncode})")
print("æšæºãšã©ãŒ:")
print(e.stderr)
äž»ãªåŒæ°:
args
: å®è¡ããã³ãã³ããšåŒæ°ããªã¹ããŸãã¯æååã§æå®ããŸãããªã¹ã圢åŒãæšå¥šãããŸãïŒã·ã§ã«ã€ã³ãžã§ã¯ã·ã§ã³å¯ŸçïŒãcapture_output
(bool):True
ã«ãããšãæšæºåºå(stdout
)ãšæšæºãšã©ãŒåºå(stderr
)ããã£ããã£ããŸããããã©ã«ãã¯False
ãtext
(bool):True
ã«ãããšãstdout
ãšstderr
ãã·ã¹ãã ã®ããã©ã«ããšã³ã³ãŒãã£ã³ã°ã§ãã³ãŒãããæååãšããŠæ±ããŸã (Python 3.7+)ãencoding
åŒæ°ã§ãšã³ã³ãŒãã£ã³ã°ãæå®ããããšãå¯èœã§ããããã©ã«ãã¯False
ïŒãã€ãåïŒãcheck
(bool):True
ã«ãããšãã³ãã³ãã®çµäºã³ãŒãã0以å€ïŒãšã©ãŒçµäºïŒã®å Žåã«CalledProcessError
äŸå€ãéåºããŸããããã©ã«ãã¯False
ãshell
(bool):True
ã«ãããšãã·ã§ã«çµç±ã§ã³ãã³ããå®è¡ããŸããã³ãã³ããæååã§æž¡ãããšãå¿ é ã«ãªããŸããã»ãã¥ãªãã£ãªã¹ã¯ãé«ãŸããããä¿¡é Œã§ããªãå ¥åãæ±ãå Žåã¯False
ïŒããã©ã«ãïŒã®ãŸãŸã«ããåŒæ°ããªã¹ãã§æž¡ãããšã匷ãæšå¥šãããŸããinput
(bytes or str): ãµãããã»ã¹ã®æšæºå ¥åã«æž¡ãããŒã¿ãæå®ããŸããtext=True
ã®å Žåã¯æååãããã§ãªããã°ãã€ãåã§æž¡ããŸããtimeout
(int or float): ã³ãã³ãã®å®è¡ã¿ã€ã ã¢ãŠãæéãç§æ°ã§æå®ããŸããã¿ã€ã ã¢ãŠãããå ŽåãTimeoutExpired
äŸå€ãçºçããŸããcwd
(str): ã³ãã³ããå®è¡ããéã®ã¯ãŒãã³ã°ãã£ã¬ã¯ããªãæå®ããŸããenv
(dict): ãµãããã»ã¹ã®ç°å¢å€æ°ãæå®ããŸããããã©ã«ãã§ã¯èŠªããã»ã¹ã®ç°å¢å€æ°ãåŒãç¶ããŸãã
2.2. subprocess.Popen()
ããäœã¬ãã«ãªã€ã³ã¿ãŒãã§ãŒã¹ã§ãããã»ã¹ã®çæãšç®¡çãããæè»ã«è¡ãããå Žåã«äœ¿çšããŸããéåæå®è¡ããã€ãã©ã€ã³ã®æ§ç¯ãããã»ã¹ãšã®å¯Ÿè©±çãªéä¿¡ãªã©ãå¯èœã§ãã
import subprocess
# ãã€ãã©ã€ã³åŠçã®äŸ: ls -l | grep ".py"
try:
# Popenã§æåã®ããã»ã¹ãéå§ (ls -l)
# stdout=subprocess.PIPE ã§æšæºåºåããã€ãã«æ¥ç¶
p1 = subprocess.Popen(["ls", "-l"], stdout=subprocess.PIPE, text=True)
# 2çªç®ã®ããã»ã¹ãéå§ (grep ".py")
# stdin=p1.stdout 㧠p1 ã®æšæºåºåã p2 ã®æšæºå
¥åã«æ¥ç¶
# stdout=subprocess.PIPE ã§æšæºåºåããã£ããã£
p2 = subprocess.Popen(["grep", ".py"], stdin=p1.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
# p1 ã®æšæºåºåãã€ããéãã (p2 ã EOF ãåãåããããã«)
p1.stdout.close()
# p2 ã®å®äºãåŸ
ã¡ãåºåãååŸ
stdout, stderr = p2.communicate()
print("ãã€ãã©ã€ã³åŠçæåïŒ")
print("æçµåºå (stdout):")
print(stdout)
if stderr:
print("æçµåºå (stderr):")
print(stderr)
print(f"grepã®çµäºã³ãŒã: {p2.returncode}")
except FileNotFoundError as e:
print(f"ãšã©ãŒ: ã³ãã³ããèŠã€ãããŸããã {e.filename}")
except Exception as e:
print(f"äºæãã¬ãšã©ãŒãçºçããŸãã: {e}")
# éåæå®è¡ã®äŸ
print("\n--- éåæå®è¡ã®äŸ ---")
try:
# ããã¯ã°ã©ãŠã³ã㧠sleep 5 ãå®è¡
process = subprocess.Popen(["sleep", "5"])
print(f"ããã»ã¹ãéå§ããŸãã (PID: {process.pid})ãå®äºãåŸ
ããã«æ¬¡ã®åŠçãžé²ã¿ãŸãã")
# ... ããã§ä»ã®åŠçãå®è¡ ...
print("ä»ã®åŠçãå®è¡äž...")
# ããã»ã¹ã®å®äºãåŸ
〠(ä»»æ)
return_code = process.wait() # ãŸã㯠communicate()
print(f"ããã»ã¹ (PID: {process.pid}) ãçµäºããŸãããçµäºã³ãŒã: {return_code}")
except Exception as e:
print(f"ãšã©ãŒ: {e}")
Popen
ã¯run()
ãããè€éã§ããã以äžã®ãããªé«åºŠãªå¶åŸ¡ãå¯èœã§ãã
- ããã»ã¹ã®å®è¡äžã«æšæºå ¥åãžããŒã¿ãéã蟌ãã ããæšæºåºå/ãšã©ãŒåºåããªã¢ã«ã¿ã€ã ã§èªã¿åã£ããããã
- è€æ°ã®ããã»ã¹ããã€ãïŒ
|
ïŒã§æ¥ç¶ããã - ããã»ã¹ãããã¯ã°ã©ãŠã³ãã§å®è¡ããå®äºãåŸ ããã«Pythonã¹ã¯ãªããã®ä»ã®åŠçãç¶ããïŒéåæå®è¡ïŒã
ã»ãã¥ãªãã£äžã®æ³šæç¹: ã·ã§ã«ã€ã³ãžã§ã¯ã·ã§ã³ ð«
subprocess.run()
ã subprocess.Popen()
㧠shell=True
ãæå®ãããšãã³ãã³ããã·ã¹ãã ã®ã·ã§ã«ïŒäŸ: /bin/sh
ïŒãä»ããŠè§£éã»å®è¡ãããŸããããã¯ã;
ã &&
ã||
ãšãã£ãã·ã§ã«ã®ã¡ã¿æåã䜿ã£ãè€éãªã³ãã³ããåäžã®æååãšããŠç°¡åã«å®è¡ã§ããåé¢ãé倧ãªã»ãã¥ãªãã£ãªã¹ã¯ã䌎ããŸãã
ããããŠãŒã¶ãŒå ¥åãªã©ã®ä¿¡é Œã§ããªãå€éšããã®å€ãã³ãã³ãæååã«çŽæ¥åã蟌ãã§ããå Žåãæªæã®ãããŠãŒã¶ãŒãäºæããªãã³ãã³ããæ¿å ¥ããŠå®è¡ã§ããŠããŸãå¯èœæ§ããããŸãïŒã·ã§ã«ã€ã³ãžã§ã¯ã·ã§ã³ïŒã
import subprocess
# å±éºãªäŸ: ãŠãŒã¶ãŒå
¥åããã®ãŸãŸã³ãã³ãæååã«åã蟌ã
user_input = "legit_file.txt; rm -rf /" # æªæã®ããå
¥åäŸ
# subprocess.run(f"ls {user_input}", shell=True) # 絶察ã«ãã£ãŠã¯ãããªãïŒ
# å®å
šãªæ¹æ³: shell=False (ããã©ã«ã) ã䜿ããåŒæ°ããªã¹ãã§æž¡ã
# ããã«ãããååŒæ°ã¯ã·ã§ã«ã«ãã£ãŠè§£éãããããã®ãŸãŸã³ãã³ãã«æž¡ããã
try:
# user_input ããã¡ã€ã«åãšããŠæ±ããã (äžã«ã¡ã¿æåããã£ãŠãå®å
š)
subprocess.run(["ls", user_input], check=True)
except subprocess.CalledProcessError as e:
print(f"ls ã³ãã³ãããšã©ãŒçµäº: {e}") # ãããããã¡ã€ã«ãèŠã€ãããªããšã©ãŒ
except FileNotFoundError:
print("ls ã³ãã³ããèŠã€ãããŸããã")
# ã©ãããŠã shell=True ãå¿
èŠãªå Žå (éæšå¥š) ã¯ãshlex.quote() ã§ãšã¹ã±ãŒããã
import shlex
safe_user_input = shlex.quote(user_input)
# print(f"ãšã¹ã±ãŒããããå
¥å: {safe_user_input}")
# subprocess.run(f"ls {safe_user_input}", shell=True, check=True) # ããã§ããªã¹ã¯ã¯æ®ãå Žåããã
ãã¹ããã©ã¯ãã£ã¹: å¯èœãªéã shell=False
(ããã©ã«ã) ã䜿çšããã³ãã³ããšåŒæ°ã¯ãªã¹ã圢åŒã§ subprocess.run()
ã Popen()
ã«æž¡ããŠãã ãããããã«ãããåŒæ°ãã·ã§ã«ã«ãã£ãŠè§£éãããã®ãé²ããã·ã§ã«ã€ã³ãžã§ã¯ã·ã§ã³ã®ãªã¹ã¯ã倧å¹
ã«äœæžã§ããŸãã
ã·ã§ã«ã¹ã¯ãªããããPythonã¹ã¯ãªãããå®è¡ããæ¹æ³
éã«ãã·ã§ã«ã¹ã¯ãªããããPythonã¹ã¯ãªãããåŒã³åºãããã®æ©èœãå©çšããããšãäžè¬çã§ãã
1. åçŽãªå®è¡
ã·ã§ã«ããPythonã€ã³ã¿ããªã¿ã«ã¹ã¯ãªãããã¡ã€ã«ãæå®ããŠå®è¡ããŸãã
#!/bin/bash
echo "Pythonã¹ã¯ãªãããå®è¡ããŸã..."
python3 my_script.py
# ããã㯠python my_script.py (ç°å¢ã«ãã)
echo "Pythonã¹ã¯ãªããã®å®è¡ãå®äºããŸããã"
my_script.py
ã®å
容ã¯ä»¥äžã®ããã«ãªããŸãã
# my_script.py
print("ããã«ã¡ã¯ãPythonã¹ã¯ãªããããã§ãïŒ")
# ... äœããã®åŠç ...
2. åŒæ°ãæž¡ã
ã·ã§ã«ã¹ã¯ãªããããPythonã¹ã¯ãªãããžæ å ±ãæž¡ãããå Žåãã³ãã³ãã©ã€ã³åŒæ°ã䜿çšããŸãã
#!/bin/bash
name="ã·ã§ã«"
count=5
echo "Pythonã¹ã¯ãªããã«åŒæ°ãæž¡ããŠå®è¡ããŸã..."
python3 process_data.py "$name" "$count" # å€æ°ã¯ããã«ã¯ã©ãŒãã§å²ãã®ãå®å
š
echo "Pythonã¹ã¯ãªããã®å®è¡ãå®äºããŸããã"
PythonåŽã§ã¯sys.argv
ãŸãã¯argparse
ã¢ãžã¥ãŒã«ã䜿ã£ãŠåŒæ°ãåãåããŸãã
# process_data.py
import sys
import argparse
print(f"åãåã£ãåŒæ°ã®ãªã¹ã (sys.argv): {sys.argv}")
if len(sys.argv) > 2:
name_arg = sys.argv[1]
count_arg = sys.argv[2]
print(f"sys.argv ããååŸ: åå={name_arg}, åæ°={count_arg}")
else:
print("åŒæ°ãäžè¶³ããŠããŸã (sys.argv)")
print("-" * 20)
# argparse ã䜿ãæ¹ãããå
ç¢ã§åããããã
parser = argparse.ArgumentParser(description='ã·ã§ã«ããããŒã¿ãåãåãPythonã¹ã¯ãªãã')
parser.add_argument('name', type=str, help='åŠç察象ã®åå')
parser.add_argument('count', type=int, help='åŠçåæ°')
# ãªãã·ã§ãã«ãªåŒæ°ãå®çŸ©ã§ãã
parser.add_argument('--verbose', '-v', action='store_true', help='詳现ãªãã°ãåºåãã')
try:
args = parser.parse_args() # sys.argv[1:] ãèªåçã«è§£æ
print(f"argparse ããååŸ: åå={args.name}, åæ°={args.count}, Verbose={args.verbose}")
print(f"\n'{args.name}' ã {args.count} ååŠçããŸã...")
for i in range(args.count):
if args.verbose:
print(f" åŠç {i+1}...")
# ... äœããã®åŠç ...
print("åŠçå®äºïŒ")
except SystemExit:
# argparse ã¯åŒæ°ãšã©ãŒæã«èªåã§ãã«ãã衚瀺ãçµäºãã
print("åŒæ°ã®è§£æã«å€±æããŸããã")
except Exception as e:
print(f"ãšã©ãŒãçºçããŸãã: {e}")
Tips: ã·ã§ã«ã¹ã¯ãªããããPythonã«åŒæ°ãæž¡ãéã¯ãã¹ããŒã¹ãå«ãå¯èœæ§ã®ããå€æ°ã¯ããã«ã¯ã©ãŒãïŒ"
ïŒã§å²ãç¿æ
£ãã€ããŸããããPythonåŽã§ã¯argparse
ã䜿ããšãåŒæ°ã®åãã§ãã¯ããã«ãã¡ãã»ãŒãžã®èªåçæãªã©ãã§ããéåžžã«äŸ¿å©ã§ããð
3. Pythonã¹ã¯ãªããã®åºåãã·ã§ã«å€æ°ã«æ ŒçŽ
Pythonã¹ã¯ãªãããæšæºåºåã«æžãåºããçµæããã·ã§ã«ã¹ã¯ãªããåŽã§å€æ°ãšããŠåãåãããå Žåã¯ãã³ãã³ã眮æïŒ$(...)
ïŒã䜿ããŸãã
#!/bin/bash
input_value=10
echo "Pythonã¹ã¯ãªãããå®è¡ããçµæãå€æ°ã«æ ŒçŽããŸã..."
# python_calculator.py ãæšæºåºåã«èšç®çµæãåºåãããšä»®å®
result=$(python3 python_calculator.py "$input_value")
# ãšã©ãŒãã§ã㯠(Pythonã¹ã¯ãªããã倱æããå Žåãªã©)
if [ $? -ne 0 ]; then
echo "Pythonã¹ã¯ãªããã®å®è¡ã«å€±æããŸããã" >&2
exit 1
fi
echo "Pythonã¹ã¯ãªããããã®çµæ: $result"
# çµæã䜿ã£ãŠããã«åŠç
processed_result=$((result * 2))
echo "ã·ã§ã«ã§ããã«åŠçããçµæ: $processed_result"
察å¿ããPythonã¹ã¯ãªããïŒäŸ: python_calculator.py
ïŒ:
# python_calculator.py
import sys
if len(sys.argv) > 1:
try:
input_num = int(sys.argv[1])
# èšç®çµæãæšæºåºåã«æžãåºã
print(input_num * input_num)
except ValueError:
print("ãšã©ãŒ: æ°å€ãå
¥åããŠãã ããã", file=sys.stderr)
sys.exit(1)
except Exception as e:
print(f"ãšã©ãŒ: {e}", file=sys.stderr)
sys.exit(1)
else:
print("ãšã©ãŒ: åŒæ°ããããŸããã", file=sys.stderr)
sys.exit(1)
Tips: Pythonã¹ã¯ãªããåŽã§ã¯ãã·ã§ã«ã§åãåãããçµæã®ã¿ãæšæºåºåïŒprint()
ïŒã«åºåãããšã©ãŒã¡ãã»ãŒãžããããã°æ
å ±ã¯æšæºãšã©ãŒåºåïŒprint(..., file=sys.stderr)
ïŒã«åºåããããã«åºå¥ãããšãã·ã§ã«åŽã§ã®ãã³ããªã³ã°ã容æã«ãªããŸãã
Pythonã©ã€ãã©ãªã®æŽ»çš ð§©
Pythonãšã·ã§ã«ã®é£æºãããã«ã¹ã ãŒãºã«ããããã®äŸ¿å©ãªã©ã€ãã©ãªã玹ä»ããŸãã
1. sh ã©ã€ãã©ãª
sh
ã¯ãå€éšã³ãã³ãããŸãã§Pythonã®é¢æ°ã®ããã«åŒã³åºããããã«ãããµãŒãããŒãã£ã©ã€ãã©ãªã§ããsubprocess
ãããçŽæçã§ç°¡æœãªèšè¿°ãå¯èœã«ãªãå ŽåããããŸããUnixç³»OSïŒLinux, macOSãªã©ïŒã§ã®ã¿åäœããWindowsã¯ãµããŒããããŠããŸããã
ã€ã³ã¹ããŒã«: pip install sh
import sh
import sys
try:
# ã³ãã³ããé¢æ°ã®ããã«åŒã³åºã
print("--- ls ã³ãã³ã ---")
# åŒæ°ã¯éåžžã®é¢æ°åŒã³åºãã®ããã«æž¡ãã
# ããŒã¯ãŒãåŒæ°ã¯ãã€ãã³ä»ããªãã·ã§ã³ã«å¯Ÿå¿ (äŸ: _long=True 㯠-l)
# sh.ls("-l", "/tmp", color="never") ãšåç
ls_output = sh.ls("-l", "/tmp", color="never")
print(ls_output) # stdout ãæååãšããŠè¿ã
print("\n--- git status ---")
# git status ãå®è¡
git_status = sh.git.status() # ãµãã³ãã³ãã¯å±æ§ã¢ã¯ã»ã¹ã§
print(git_status)
print("\n--- ãã€ãåŠç (ls -1 | wc -l) ---")
# ãã€ã㯠_in ããŒã¯ãŒãåŒæ°ã§å®çŸ
file_count = sh.wc("-l", _in=sh.ls("-1"))
print(f"ãã¡ã€ã«æ°: {file_count.strip()}") # strip() ã§æ«å°Ÿã®æ¹è¡ãåé€
print("\n--- åºåãªãã€ã¬ã¯ã ---")
# ãã¡ã€ã«ãžã®ãªãã€ã¬ã¯ã
sh.echo("shã©ã€ãã©ãªãããã¡ã€ã«ã«æžã蟌ã¿", _out="sh_output.txt")
print("sh_output.txt ã«æžã蟌ã¿ãŸããã")
print(sh.cat("sh_output.txt"))
sh.rm("sh_output.txt")
print("\n--- ãšã©ãŒãã³ããªã³ã° ---")
# ååšããªããã¡ã€ã«ã ls ããããšãããš ErrorReturnCode äŸå€ãçºç
sh.ls("/ååšããªããã¹")
except sh.ErrorReturnCode as e:
print(f"\nãšã©ãŒçºçïŒ")
print(f"ã³ãã³ã: {e.full_cmd}")
print(f"çµäºã³ãŒã: {e.exit_code}")
print(f"æšæºåºå:\n{e.stdout.decode()}") # ãã€ãåãªã®ã§ãã³ãŒã
print(f"æšæºãšã©ãŒ:\n{e.stderr.decode()}") # ãã€ãåãªã®ã§ãã³ãŒã
except sh.CommandNotFound as e:
print(f"\nãšã©ãŒ: ã³ãã³ã '{e.cmd}' ãèŠã€ãããŸããã")
except Exception as e:
print(f"äºæãã¬ãšã©ãŒ: {e}")
# ããã¯ã°ã©ãŠã³ãå®è¡
print("\n--- ããã¯ã°ã©ãŠã³ãå®è¡ ---")
try:
# _bg=True ã§ããã¯ã°ã©ãŠã³ãå®è¡
process = sh.sleep(3, _bg=True)
print(f"sleep 3 ãããã¯ã°ã©ãŠã³ãã§éå§ (PID: {process.pid})")
# ... ä»ã®åŠç ...
print("ä»ã®åŠçãå®è¡äž...")
process.wait() # å®äºãåŸ
ã€
print("sleep ããã»ã¹ãå®äºããŸããã")
except Exception as e:
print(f"ãšã©ãŒ: {e}")
sh
ã©ã€ãã©ãªã®ã¡ãªãã:
- ã·ã§ã«ã³ãã³ããPythonã®é¢æ°ã®ããã«çŽæçã«èšè¿°ã§ããã
- åŒæ°ããªãã·ã§ã³ã®æž¡ãæ¹ãã·ã³ãã«ã
- ãã€ãåŠçããªãã€ã¬ã¯ããæ¯èŒçç°¡åã«æžããã
- ãµãã³ãã³ãïŒäŸ:
git status
ïŒãã¡ãœãããã§ãŒã³ã®ããã«èšè¿°å¯èœã
sh
ã©ã€ãã©ãªã®ãã¡ãªãã/泚æç¹:
- Unixç³»OSå°çšã§ãããWindowsã§ã¯åäœããªãã
- ãµãŒãããŒãã£ã©ã€ãã©ãªã®ãããå¥éã€ã³ã¹ããŒã«ãå¿ èŠã
subprocess
ã»ã©çŽ°ããå¶åŸ¡ïŒäŸ: stdin/stdout/stderrã®ã¹ããªãŒãã³ã°åŠçïŒã¯åŸæã§ã¯ãªãå Žåãããã- ã³ãã³ãåãPythonã®äºçŽèªãæ¢åã®å€æ°åãšè¡çªããå¯èœæ§ãããïŒãã®å Žåã¯
sh.Command("command-name")(...)
ã®ããã«åŒã³åºãïŒã
2. argparse ã©ã€ãã©ãª
ããã¯ã·ã§ã«é£æºã«ç¹åããã©ã€ãã©ãªã§ã¯ãããŸãããããã·ã§ã«ã¹ã¯ãªããããPythonã¹ã¯ãªãããå®è¡ããæ¹æ³ãã§è§Šããããã«ãPythonã¹ã¯ãªãããã³ãã³ãã©ã€ã³åŒæ°ãåãåãéã®ããã¡ã¯ãã¹ã¿ã³ããŒãã§ããã·ã§ã«ããæž¡ãããåŒæ°ãããŒã¹ããåãã§ãã¯ããã«ãã¡ãã»ãŒãžçæãè¡ãã®ã«éåžžã«åœ¹ç«ã¡ãŸãã
# (åæ²) process_data.py ã® argparse éšå
import argparse
parser = argparse.ArgumentParser(description='ã·ã§ã«ããããŒã¿ãåãåãPythonã¹ã¯ãªãã')
parser.add_argument('name', type=str, help='åŠç察象ã®åå')
parser.add_argument('count', type=int, help='åŠçåæ°')
parser.add_argument('--verbose', '-v', action='store_true', help='詳现ãªãã°ãåºåãã')
parser.add_argument('--output-file', '-o', type=str, default='output.txt', help='åºåãã¡ã€ã«å (ããã©ã«ã: output.txt)')
try:
args = parser.parse_args()
print(f"åå: {args.name}")
print(f"åæ°: {args.count}")
print(f"Verbose: {args.verbose}")
print(f"åºåãã¡ã€ã«: {args.output_file}")
# ... args ã䜿ã£ãŠåŠç ...
except Exception as e:
print(f"åŒæ°è§£æãšã©ãŒ: {e}")
# parser.print_help() # ãã«ãã衚瀺ãããªã©
ã·ã§ã«ã¹ã¯ãªãããã python3 process_data.py ã·ã§ã« 10 -v -o result.log
ã®ããã«åŒã³åºããšããããã®åŒæ°ãé©åã«ããŒã¹ãããŸãã
3. pathlib ã©ã€ãã©ãª
Python 3.4 ã§æšæºã©ã€ãã©ãªã«è¿œå ãããpathlib
ã¯ããã¡ã€ã«ã·ã¹ãã ãã¹ããªããžã§ã¯ãæåçã«æ±ãããã®ã¢ãžã¥ãŒã«ã§ããåŸæ¥ã®os.path
ãããçŽæçã§ã³ãŒããèªã¿ããããªãããšãå€ããã·ã§ã«ã¹ã¯ãªããã§è¡ããã¡ãªãã¡ã€ã«ããã£ã¬ã¯ããªã®æäœïŒååšç¢ºèªãäœæãåé€ã移åãäžèŠ§ååŸãªã©ïŒãPythonåŽã§ãšã¬ã¬ã³ãã«èšè¿°ã§ããŸãã
from pathlib import Path
import os # æ¯èŒçš
# ã«ã¬ã³ããã£ã¬ã¯ããª
current_dir = Path.cwd()
print(f"ã«ã¬ã³ããã£ã¬ã¯ããª: {current_dir}")
# ããŒã ãã£ã¬ã¯ããª
home_dir = Path.home()
print(f"ããŒã ãã£ã¬ã¯ããª: {home_dir}")
# ãã¹ã®çµå ( / æŒç®åã䜿ãã)
config_path = home_dir / ".config" / "my_app" / "settings.ini"
print(f"èšå®ãã¡ã€ã«ã®ãã¹: {config_path}")
# ãã£ã¬ã¯ããªã®äœæ (mkdir)
# exist_ok=True: æ¢ã«ååšããŠããšã©ãŒã«ããªã
# parents=True: äžéãã£ã¬ã¯ããªããŸãšããŠäœæãã
config_path.parent.mkdir(parents=True, exist_ok=True)
print(f"{config_path.parent} ãã£ã¬ã¯ããªãäœæ (ãŸãã¯ååšã確èª)")
# ãã¡ã€ã«ã®ååšç¢ºèª (exists)
if config_path.exists():
print(f"{config_path} ã¯ååšããŸãã")
else:
print(f"{config_path} ã¯ååšããŸããã")
# ãã¡ã€ã«ãžã®æžã蟌㿠(touch + write_text)
config_path.touch() # 空ãã¡ã€ã«äœæ (ã·ã§ã«ã³ãã³ãã® touch)
config_path.write_text("[General]\nsetting1 = value1", encoding='utf-8')
print(f"{config_path} ã«æžã蟌ã¿ãŸããã")
# ãã¡ã€ã«ã®èªã¿èŸŒã¿ (read_text)
if config_path.is_file():
content = config_path.read_text(encoding='utf-8')
print(f"\n{config_path} ã®å
容:")
print(content)
# ãã£ã¬ã¯ããªå
ã®ãã¡ã€ã«/ãã£ã¬ã¯ããªäžèŠ§ (iterdir, glob)
print(f"\n{home_dir} çŽäžã®å
容:")
for item in home_dir.iterdir():
# is_dir(), is_file() ã§çš®é¡ãå€å¥
item_type = "ãã£ã¬ã¯ããª" if item.is_dir() else "ãã¡ã€ã«" if item.is_file() else "ãã®ä»"
# print(f" - {item.name} ({item_type})") # å
šãŠè¡šç€ºãããšå€ãã®ã§ã³ã¡ã³ãã¢ãŠã
print(f"\n{current_dir} å
ã® Python ãã¡ã€ã« (*.py):")
# glob ã§ãã¿ãŒã³ãããã³ã° (ã·ã§ã«ã® *)
for py_file in current_dir.glob("*.py"):
print(f" - {py_file.name}")
# ãã¡ã€ã«ã®åé€ (unlink)
# config_path.unlink(missing_ok=True) # missing_ok=True: ãã¡ã€ã«ãååšããªããŠããšã©ãŒã«ããªã
# print(f"{config_path} ãåé€ããŸããã")
# ãã£ã¬ã¯ããªã®åé€ (rmdir - 空ã§ããå¿
èŠãã)
# config_path.parent.rmdir() # settings.ini ããããšãšã©ãŒã«ãªã
# print(f"{config_path.parent} ãåé€ããŸããã")
# shutil ã¢ãžã¥ãŒã«ãšçµã¿åããããšããã«åŒ·å (ã³ããŒã移åãããªãŒåé€ãªã©)
# import shutil
# shutil.rmtree(config_path.parent) # ãã£ã¬ã¯ããªããªãŒããšåé€
pathlib
ã䜿ãããšã§ããã¡ã€ã«ãã¹ã«é¢é£ããå€ãã®æäœãPythonicã«èšè¿°ã§ããã·ã§ã«ã³ãã³ãã®åŒã³åºãåæ°ãæžãããå¯èœæ§ããããŸãã
4. ãã®ä»ïŒPandas, Requestsãªã©ïŒ
ã·ã§ã«ã¹ã¯ãªããã ãã§ã¯æ±ãã«ããããããã¯å¹çãæªãã¿ã¹ã¯ã¯ãPythonã®åŸæåéã§ãã
- ããŒã¿åŠçã»åæ: CSVãExcelãJSONãªã©ã®è€éãªããŒã¿æ§é ãæ±ãå ŽåãPandasã©ã€ãã©ãªã䜿ãã°åŒ·åãªããŒã¿æäœã»åæãå¯èœã§ããã·ã§ã«ã¹ã¯ãªããïŒ
awk
,sed
,grep
ãªã©ïŒã§ãå¯èœã§ãããã³ãŒããè€éã«ãªããã¡ã§ãã - Web APIé£æº: Requestsã©ã€ãã©ãªã䜿ãã°ãWeb APIããã®ããŒã¿ååŸãéä¿¡ãéåžžã«ç°¡åã«ãªããŸãã
curl
ã³ãã³ãã§ãå¯èœã§ãããèªèšŒåŠçãã¬ã¹ãã³ã¹ã®ããŒã¹ãªã©ãPythonã§è¡ãæ¹ãæè»ãªå Žåãå€ãã§ãã - è€éãªããžãã¯: ã·ã§ã«ã¹ã¯ãªããã¯æç¶ãçãªåŠçãäž»ã§ãããPythonãªããªããžã§ã¯ãæåããã°ã©ãã³ã°ãè±å¯ãªå¶åŸ¡æ§æããšã©ãŒãã³ããªã³ã°æ©æ§ã掻çšããŠãããè€éã§ã¡ã³ããã³ã¹æ§ã®é«ãããžãã¯ãå®è£ ã§ããŸãã
ãããã®ã©ã€ãã©ãªã掻çšããã·ã§ã«ã¹ã¯ãªããã§ã¯é£ããåŠçãPythonã«ä»»ãããã®çµæãã·ã§ã«ã¹ã¯ãªããã§å©çšããããšãã£ãåæ¥ãå¹æçã§ãã
å®è·µçãªé£æºãã¯ããã¯ãšTips ð¡
1. ç°å¢å€æ°ã®å ±æ
ã·ã§ã«ã¹ã¯ãªãããšPythonã¹ã¯ãªããéã§æ å ±ãããåãããç°¡åãªæ¹æ³ã®äžã€ãç°å¢å€æ°ã§ãã
- ã·ã§ã« â Python: ã·ã§ã«ã§
export MY_VAR="value"
ã®ããã«ç°å¢å€æ°ãèšå®ãããšãPythonã¹ã¯ãªããå ã§ã¯os.environ.get('MY_VAR')
ã§ãã®å€ãååŸã§ããŸããsubprocess
ã§PythonãåŒã³åºãéãããã©ã«ãã§èŠªïŒã·ã§ã«ïŒã®ç°å¢å€æ°ãåŒãç¶ãããŸãã - Python â ã·ã§ã« (ãµãããã»ã¹):
subprocess.run()
ãPopen()
ã®env
åŒæ°ã䜿ã£ãŠãèµ·åãããµãããã»ã¹ïŒã·ã§ã«ã³ãã³ããå¥ã®ã¹ã¯ãªããïŒã«ç¹å®ã®ç°å¢å€æ°ãæž¡ãããšãã§ããŸãã
#!/bin/bash
# ã·ã§ã«ã§ç°å¢å€æ°ãèšå®
export SHARED_SECRET="abc123xyz"
export PROCESS_MODE="production"
echo "ã·ã§ã«ããPythonã«ç°å¢å€æ°ãæž¡ããŠå®è¡..."
python3 env_reader.py
echo "Pythonããã·ã§ã«ã«ç°å¢å€æ°ãæž¡ããŠå®è¡..."
python3 env_setter.py # ãã®äžã§ subprocess ã䜿ã£ãŠã·ã§ã«ã³ãã³ããå®è¡
# env_reader.py
import os
secret = os.environ.get('SHARED_SECRET')
mode = os.environ.get('PROCESS_MODE', 'development') # ããã©ã«ãå€ãèšå®å¯èœ
if secret:
print(f"PythonåŽã§ç°å¢å€æ° SHARED_SECRET ãåãåããŸãã: {secret[:3]}*** (é èœ)")
else:
print("ç°å¢å€æ° SHARED_SECRET ãèšå®ãããŠããŸããã")
print(f"åŠçã¢ãŒã: {mode}")
# env_setter.py
import subprocess
import os
print("Pythonãããµãããã»ã¹ïŒã·ã§ã«ã³ãã³ãïŒã«ç°å¢å€æ°ãæž¡ããŸãã")
# çŸåšã®ç°å¢å€æ°ãã³ããŒããè¿œå ã»å€æŽãã
child_env = os.environ.copy()
child_env["PYTHON_VAR"] = "Set by Python"
child_env["PROCESS_MODE"] = "testing" # ã·ã§ã«ã§èšå®ãããã®ãäžæžã
try:
# env åŒæ°ã§ã«ã¹ã¿ã ç°å¢å€æ°ãæž¡ã
# ã·ã§ã«ã³ãã³ã `env | grep -E 'PYTHON_VAR|PROCESS_MODE'` ãå®è¡
result = subprocess.run(
"env | grep -E 'PYTHON_VAR|PROCESS_MODE'",
shell=True, # ãã®äŸã§ã¯ãã€ãã䜿ããã shell=True ãäœ¿çš (泚æãå¿
èŠ)
capture_output=True,
text=True,
check=True,
env=child_env
)
print("ãµãããã»ã¹ã«æž¡ãããé¢é£ç°å¢å€æ°:")
print(result.stdout)
except Exception as e:
print(f"ãµãããã»ã¹ã®å®è¡ãšã©ãŒ: {e}")
2. ãšã©ãŒãã³ããªã³ã°
- PythonåŽ (subprocess):
subprocess.run()
ã§check=True
ã䜿ãããPopen
ã®çµæã®returncode
ã確èªããéãŒãã®å Žåã¯ãšã©ãŒãšããŠæ±ããŸããtry...except subprocess.CalledProcessError
ã§ãšã©ãŒæã®åŠçãèšè¿°ããŸããæšæºãšã©ãŒåºåïŒstderr
ïŒã®å 容ã確èªãããšãããã°ã«åœ¹ç«ã¡ãŸãã - ã·ã§ã«åŽ: ã³ãã³ãå®è¡çŽåŸã«ç¹æ®å€æ°
$?
ã§çµäºã³ãŒãã確èªããŸãïŒ0ãæåããã以å€ããšã©ãŒïŒãset -e
ãªãã·ã§ã³ã䜿ããšãã³ãã³ãããšã©ãŒçµäºããå Žåã«ã¹ã¯ãªããå šäœãå³åº§ã«çµäºãããããšãã§ããŸããset -o pipefail
ã䜿ããšããã€ãã©ã€ã³ã®éäžã§ãšã©ãŒãçºçããå Žåãæ€ç¥ã§ããŸãã
#!/bin/bash
# ãšã©ãŒçºçæã«ã¹ã¯ãªãããçµäº (-e)
# ãã€ãã©ã€ã³ã®éäžã§ã®ãšã©ãŒãæ€ç¥ (-o pipefail)
set -eo pipefail
echo "ãšã©ãŒãã³ããªã³ã°ã®ãã¹ã"
python3 non_existent_script.py # ååšããªãã¹ã¯ãªãããå®è¡ããããšãã
# set -e ã«ãããäžã®è¡ã§ãšã©ãŒãçºçãããšã以äžã®è¡ã¯å®è¡ãããã«ã¹ã¯ãªãããçµäºãã
echo "ãã®ã¡ãã»ãŒãžã¯è¡šç€ºãããŸããã"
é©åãªãšã©ãŒãã³ããªã³ã°ã¯ãã¹ã¯ãªããã®ä¿¡é Œæ§ãé«ããäžã§éåžžã«éèŠã§ãã
3. äžæãã¡ã€ã«ã®æ±ã
ã·ã§ã«ãšPythonéã§å€§éã®ããŒã¿ãããåãããå Žåãæšæºå ¥åºåã ãã§ã¯æ±ãã«ããããšããããŸãããã®å Žåãäžæãã¡ã€ã«ãå©çšããæ¹æ³ããããŸãã
- Pythonã®
tempfile
ã¢ãžã¥ãŒã«ã䜿ããšãå®å šãªäžæãã¡ã€ã«ãäžæãã£ã¬ã¯ããªãç°¡åã«äœæã»ç®¡çã§ããŸãã - ã·ã§ã«ã¹ã¯ãªããããã¯ããã®äžæãã¡ã€ã«ã®ãã¹ãåŒæ°ãªã©ã§åãåããèªã¿æžããè¡ããŸãã
- åŠçãçµãã£ãããPythonåŽã§å¿ããã«äžæãã¡ã€ã«ãåé€ããŸãïŒ
tempfile
ã®ã³ã³ããã¹ããããŒãžã£ã䜿ããšèªååé€ã容æïŒã
import tempfile
import subprocess
from pathlib import Path
# 倧éã®ããŒã¿ãçæ (äŸ)
large_data = "\n".join([f"Data line {i}" for i in range(10000)])
# äžæãã¡ã€ã«ãäœæ (ã³ã³ããã¹ããããŒãžã£ã䜿çš)
with tempfile.NamedTemporaryFile(mode='w+', encoding='utf-8', delete=False) as temp_file:
temp_filepath = Path(temp_file.name)
print(f"äžæãã¡ã€ã«ãäœæ: {temp_filepath}")
temp_file.write(large_data)
# ãã¡ã€ã«ãã€ã³ã¿ãå
é ã«æ»ããªããšãçŽåŸã®èªã¿èŸŒã¿ã§ç©ºã«ãªãå Žåããã
temp_file.seek(0)
# ã·ã§ã«ã¹ã¯ãªããã«äžæãã¡ã€ã«ã®ãã¹ãæž¡ããŠå®è¡ (äŸ: wc -l)
try:
print("ã·ã§ã«ã¹ã¯ãªãã (wc -l) ãå®è¡ããŠè¡æ°ãã«ãŠã³ã...")
result = subprocess.run(["wc", "-l", str(temp_filepath)], capture_output=True, text=True, check=True)
print(f"ã·ã§ã«ããã®çµæ:\n{result.stdout.strip()}")
except Exception as e:
print(f"ã·ã§ã«ã³ãã³ãã®å®è¡ãšã©ãŒ: {e}")
finally:
# finally ãããã¯ã§ç¢ºå®ã«äžæãã¡ã€ã«ãåé€
# ã³ã³ããã¹ããããŒãžã£ã® delete=True ã§ãè¯ãããã·ã§ã«é£æºæ㯠False ã«ããŠæ瀺çã«æ¶ãæ¹ãå®å
šãªå Žåã
print(f"äžæãã¡ã€ã«ãåé€: {temp_filepath}")
temp_filepath.unlink()
4. åŠçã®åæ
ããããã®åŸæåéã掻ãããŠåŠçãåæ ããŸãããã
- ååŠçã»åŸåŠç (Python): è€éãªããŒã¿æŽåœ¢ãããªããŒã·ã§ã³ãAPIããã®ããŒã¿ååŸãçµæã®éèšã»å¯èŠåãªã©ã¯PythonãåŸæã
- ã³ã¢åŠçã»äžŠåå®è¡ (ã·ã§ã«): æ¢åã®ã³ãã³ãã©ã€ã³ããŒã«ã®å©çšãåçŽãªãã¡ã€ã«æäœã®ç¹°ãè¿ãããã€ãã©ã€ã³ã«ããé£æºãxargsãªã©ã䜿ã£ãç°¡åãªäžŠååŠçã¯ã·ã§ã«ã¹ã¯ãªãããç°¡æœã«æžããå Žåãããã
äŸãã°ãPythonã§å€§éã®URLãªã¹ããçæããã·ã§ã«ã¹ã¯ãªããïŒwget
ãcurl
ãšxargs
ïŒã§äžŠåã«ããŠã³ããŒãããã®åŸPythonã§ããŠã³ããŒããããã¡ã€ã«ãåŠçããããšãã£ãæµããèããããŸãã
5. Pythonä»®æ³ç°å¢ãšã·ã§ã«ã¹ã¯ãªãã
Pythonãããžã§ã¯ãã§ä»®æ³ç°å¢ïŒvenv, condaãªã©ïŒã䜿ã£ãŠããå Žåãã·ã§ã«ã¹ã¯ãªãããããã®ç°å¢å ã®Pythonã€ã³ã¿ããªã¿ãã©ã€ãã©ãªã䜿ãããããšããããŸãã
- ã·ã§ã«ã¹ã¯ãªããã®åé ã§
source /path/to/your/venv/bin/activate
ãå®è¡ããŠä»®æ³ç°å¢ãæå¹åããã - ãããã¯ãä»®æ³ç°å¢å
ã®Pythonã€ã³ã¿ããªã¿ã®ãã«ãã¹ïŒäŸ:
/path/to/your/venv/bin/python
ïŒãçŽæ¥æå®ããŠPythonã¹ã¯ãªãããå®è¡ããã
#!/bin/bash
VENV_PATH="/path/to/your/project/venv" # å®éã®ãã¹ã«çœ®ãæãã
# æ¹æ³1: ä»®æ³ç°å¢ã activate
# source "$VENV_PATH/bin/activate"
# python my_project_script.py
# deactivate # å¿
èŠã§ããã°éã¢ã¯ãã£ãå
# æ¹æ³2: ä»®æ³ç°å¢å
ã® Python ãçŽæ¥æå®
PYTHON_EXEC="$VENV_PATH/bin/python"
if [ -f "$PYTHON_EXEC" ]; then
echo "ä»®æ³ç°å¢å
ã®Pythonã䜿ã£ãŠã¹ã¯ãªãããå®è¡ããŸã..."
"$PYTHON_EXEC" my_project_script.py --some-option
else
echo "ãšã©ãŒ: ä»®æ³ç°å¢ã®PythonãèŠã€ãããŸãã: $PYTHON_EXEC" >&2
exit 1
fi
6. ã·ã§ã«ã¹ã¯ãªããã®ãã¹ããã©ã¯ãã£ã¹
é£æºããã·ã§ã«ã¹ã¯ãªããèªäœã®å質ãé«ããããšãéèŠã§ãã
- Shebang: ã¹ã¯ãªããã®1è¡ç®ã«ã¯
#!/bin/bash
ã#!/usr/bin/env bash
ãèšè¿°ããã - ãšã©ãŒåŠç:
set -e
,set -u
,set -o pipefail
ãã¹ã¯ãªããåé ã§èšå®ããããšãæ€èšããïŒ-u
ã¯æªå®çŸ©å€æ°ã¢ã¯ã»ã¹ã§ãšã©ãŒïŒã - å€æ°å±é: å€æ°ã¯ããã«ã¯ã©ãŒãã§å²ã (
"$variable"
) ç¿æ £ãã€ããïŒã¹ããŒã¹çã«ããæå³ããªãåå²ãé²ãïŒã - ã³ãã³ã眮æ: ããã¯ã¯ã©ãŒã (
`command`
) ã§ã¯ãªã$(command)
ã䜿ãããã¹ããå¯èœã - å¯èªæ§: é¢æ°ã掻çšããé©åãªã€ã³ãã³ããšã³ã¡ã³ããå¿ãããã
- ããŒã«æŽ»çš: ShellCheck ãªã©ã®éç解æããŒã«ã䜿ã£ãŠæœåšçãªåé¡ãæ€åºããã
ãŸãšã
Pythonãšã·ã§ã«ã¹ã¯ãªããã¯ãããããç°ãªã匷ã¿ãæã€åŒ·åãªããŒã«ã§ããsubprocess
ã¢ãžã¥ãŒã«ãsh
ã©ã€ãã©ãªãpathlib
ãªã©ã掻çšããããšã§ããããäºã€ã®äžçãå¹æçã«é£æºãããããè€éã§é«åºŠãªã¿ã¹ã¯ãèªååããå¹çåããããšãå¯èœã«ãªããŸãã ð
é£æºã®éã«ã¯ã以äžã®ç¹ãæèããããšãéèŠã§ãã
- åèšèªã®åŸæãªåŠçãåæ ãããã
subprocess
ã¢ãžã¥ãŒã«ãåºæ¬ãšããå¿ èŠã«å¿ããŠsh
ã©ã€ãã©ãªãæ€èšããã- ã»ãã¥ãªãã£ïŒç¹ã«ã·ã§ã«ã€ã³ãžã§ã¯ã·ã§ã³ïŒã«åžžã«æ³šæãæããå®å
šãªã³ãŒãã£ã³ã°ãå¿ããã (
shell=False
, åŒæ°ãªã¹ã圢åŒ)ã - ãšã©ãŒãã³ããªã³ã°ãé©åã«è¡ããã¹ã¯ãªããã®ä¿¡é Œæ§ãé«ããã
- ç°å¢å€æ°ãã³ãã³ãã©ã€ã³åŒæ°ãäžæãã¡ã€ã«ãªã©ãç¶æ³ã«å¿ããæ å ±é£æºæ¹æ³ãéžæããã
- PythonåŽã ãã§ãªããé£æºããã·ã§ã«ã¹ã¯ãªããèªäœã®å質ã«ãæ°ãé ãã
ãã®ããã°ã§çŽ¹ä»ãããã¯ããã¯ãã©ã€ãã©ãªããçããã®éçºãèªååã®äžå©ãšãªãã°å¹žãã§ããHappy scripting! ð
æ¯èŒè¡š: Pythonããã·ã§ã«ã³ãã³ãå®è¡æ¹æ³ã®æŠèŠ
æ¹æ³ | æšå¥šåºŠ | äž»ãªç¹åŸŽ | ã¡ãªãã | ãã¡ãªãã/泚æç¹ |
---|---|---|---|---|
os.system() | éæšå¥š | æãåçŽãªã³ãã³ãå®è¡ | èšè¿°ãéåžžã«ç°¡å | ã»ãã¥ãªãã£ãªã¹ã¯(ã·ã§ã«ã€ã³ãžã§ã¯ã·ã§ã³)ãåºåååŸäžå¯ãæè»æ§äœã |
subprocess.run() | æšå¥š | åæçãªã³ãã³ãå®è¡ãå®äºåŸ ã¡ | å®å š(ãªã¹ãåŒæ°)ãåºå/ãšã©ãŒååŸå¯ãçµäºã³ãŒã確èªãã¿ã€ã ã¢ãŠããæè»æ§é«ã | Popenããã¯æ©èœéå®ç |
subprocess.Popen() | æšå¥š (é«åºŠ) | éåæå®è¡ããã€ãã©ã€ã³ãããã»ã¹ééä¿¡ | æãé«æ©èœã»æè»ã詳现ãªå¶åŸ¡ãå¯èœ | run() ããèšè¿°ãè€éã«ãªãå Žåããã |
sh ã©ã€ãã©ãª | ç¶æ³ã«ãã | ã³ãã³ããPythoné¢æ°ã®ããã«åŒã³åºã | çŽæçãèšè¿°ãç°¡æœããã€ã/ãªãã€ã¬ã¯ã容æ | Unixç³»å°çšãèŠã€ã³ã¹ããŒã«ãsubprocessçšã®äœã¬ãã«å¶åŸ¡ã¯äžåŸæãªå Žåã |
ã³ã¡ã³ã