ã·ã§ã«ã¹ã¯ãªããããPython3ã«ç§»è¡ãã人ã®ããã« ï½æ¨æºå ¥åºåã»ãã¡ã¤ã«ç®¡çç·¨ï½
æ±ãã·ã§ã«ã¹ã¯ãªãããä¿å®ããä½æ¥ã«å«æ°ãããã¦ããã®ã§ãPython3ã«ä¹ãæããã ãã£ãããªã®ã§å¿ è¦ã«ãªã£ãç¥èãæ´çãã¦ããã åãããã«ã·ã§ã«ã¹ã¯ãªããããä¹ãæãã人ã®å½¹ã«ç«ã¤ã¨æãã
ã¨ãããã IO é¢é£ã¨ãã¡ã¤ã«åã®æä½ãéè¦ãªæ°ãããã®ã§ããã®ã¸ãããæ¸ãå§ããã
ç°å¢å¤æ°ã®åå¾
# Python import os home = os.environ.get('HOME', "")
ã«ã¬ã³ããã£ã¬ã¯ããªã®ãã¹ãåå¾
# Bash ... ãã¨ã㨠$PWDã«å ¥ã£ã¦ããã current_path=`pwd`
# Python import os current_path = os.getcwd() # ã¹ã¯ãªããã®ãããã£ã¬ã¯ããªã®çµ¶å¯¾ãã¹ã¯ script_path = os.path.abspath(os.path.dirname(__file__))
ãã¡ã¤ã«åã¨ãã£ã¬ã¯ããªåã®çµå
ã·ã§ã«ã¹ã¯ãªããã§ã¯ãã¡ã¤ã«ããã£ã¬ã¯ããªãæååã¨ãã¦æ±ãã é©å½ã«åã£ããè²¼ã£ãããã¦ããããã©ã Pythonã§ã¯ os.path.join ã使ã£ã¦è¡åããæ±ãå¿ è¦ãããã
# Bash tmp_dir="$HOME/tmp" tmp_file="${tmp_dir}/tmp.txt"
# Python import os home = os.environ.get('HOME', "") tmp_dir = os.path.join( home , "tmp" ) tmp_file = os.path.join( tmp_dir, "tmp.txt") # 諸äºæ ã§ãã¹ã®åºåãæåãå¤æ´ããããªã£ãã tmp_dir_unix = tmp_dir.replace(os.path.sep, '/') # /path/to/tmp_dir tmp_dir_win = tmp_dir.replace(os.path.sep, '\\') # path\to\tmpdir
ãã£ã¬ã¯ããªã®ä½æ
ãååã®ãã£ã¬ã¯ããªã®åå¨ã確èªãã¦ãç¡ããã°ä½æãã¨ããå®å½¢ä½æ¥
# Bash if [ ! -d ${tmp_dir} ] ;then mkdir ${tmp_dir} fi
# Python import os if not os.path.exists(tmp_dir): os.makedirs(tmp_dir) # å帰çä½æ
ãã£ã¬ã¯ããªã®åé¤
ããã¤ãæ¹æ³ãããããã©ãä¸çªå¼·åãªãã¤ã¯
# Bash rm -rf ${tmp_dir}
# Python import shutil shutil.rmtree(tmp_dir)
ãã¡ã¤ã«ã¸ã®æ¸ããã¿
# Bash echo "hoge\npiyo" > ${tmp_file}
#Python import codecs f_out = codecs.open(tmp_file, "w", "utf-8") print("hoge\npiyo", file=f_out) f_out.close()
ãã¡ã¤ã«ã®èªã¿ãã¿
# Bash cat ${tmp_file}
# Python import codecs f_in = codecs.open(tmp_file, "r", "utf-8") for line in f_in.readlines(): print(line) f_in.close()
å¤é¨ããã°ã©ã ã®å®è¡ã¨ãã¤ãå¦ç
# Bash cat ${tmp_file} | wc -l
# Python from subprocess import Popen, PIPE cat = Popen(["cat", tmp_file], stdout=PIPE) wc = Popen(["wc" , "-l"] , stdin=cat.stdout, stdout=PIPE) output = wc.stdout for line in output: print(line)