๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Lang/๐Ÿ Python

๐Ÿ Python * OS ๋ช…๋ น์–ด ๊ฒฐ๊ณผ๋ฅผ Python ์ฝ”๋“œ์—์„œ ์‚ฌ์šฉํ• ๋ž˜! ๐Ÿ˜

๋ฆฌ๋ˆ…์Šค ๋ช…๋ น์–ด๋ฅผ ํŒŒ์ด์ฌ ์ฝ”๋“œ์—์„œ os.system์„ ์ด์šฉํ•˜์—ฌ ์ข…์ข… ์‹คํ–‰ํ•˜๊ณค ํ•œ๋‹ค.

ํ•˜์ง€๋งŒ os.system์„ ์“ธ ๊ฒฝ์šฐ ๋ฌธ์ž์—ด ๊ฒฐ๊ณผ๊ฐ’์„ ๊ฐ€์ ธ์˜ค๊ธฐ๋ž€.. ๐Ÿ˜ซ

 

ํ•ด์„œ ์ธํ„ฐ๋„ท์œผ๋กœ ์ฐพ์•„๋ณด์•˜๋”๋‹ˆ Subprocess ๋ผ๋Š” ๊ธฐ๋ณธ ๋ชจ๋“ˆ์„ ์ด์šฉํ•˜์—ฌ ๋ฌธ์ž์—ด ๊ฒฐ๊ณผ๋ฅผ ์† ์‰ฝ๊ฒŒ ๋ณ€์ˆ˜ ๊ฐ’์œผ๋กœ ์ €์žฅ ํ•  ์ˆ˜ ์žˆ์—ˆ๋‹ค.

 

๋‚ด์šฉ์„ ๋ฐœ์ทŒ ํ•ด์˜จ ํฌ์ŠคํŒ…์—์„œ communicate๋Š” ํŒŒ์ผ์ด ํฌ๊ฑฐ๋‚˜ unlimitedํ•œ ๋ถ€๋ถ„์—์„œ๋Š” ์“ฐ์ง€ ๋ง๋ผ๊ณ  ํ•œ๋‹ค๋Š” ๋Œ“๊ธ€์„ ๋ณด์•˜๋‹ค.

์™œ ๊ทธ๋Ÿฐ์ง€๊นŒ์ง€๋Š” ์ž์„ธํžˆ ๋ณด์ง€ ์•Š์•˜์œผ๋‹ˆ ๊ทธ๋Ÿฐ ์ƒํ™ฉ์ด๋ผ๋ฉด ์ข€ ๋” ์ฐพ์•„๋ณด๊ณ  ์ ์šฉํ•˜๋„๋ก ํ•˜์ž.

 

ํŒŒ์ด์ฌ๋ฟ๋งŒ ์•„๋‹ˆ๋ผ ๋ญ๋“  ๋ฌธ์„œ๋ฅผ ๋ณผ ๋•Œ๋Š” ์ž์‹ ์˜ ๋ฒ„์ „๊ณผ ๋ฌธ์„œ์—์„œ ์„ค๋ช…ํ•˜๋Š” ๋ฒ„์ „์ด ๊ฐ™์€ ์ง€๋ฅผ ํ•ญ์ƒ ๋ณด์•„์•ผ ํ•œ๋‹ค.

 

 


 

 

Let's do this

1. check_output(...)

import subprocess
 
data = subprocess.check_output(['ls', '-al'])
print data

2. popen(...)

    - ์•„๋ž˜ ์˜ˆ์ œ๋Š” ์ฐธ๊ณ ํ•œ ํฌ์ŠคํŒ…์—์„œ ๋ฐœ์ทŒํ•˜์˜€์Šต๋‹ˆ๋‹ค.

import subprocess
 
def main():
  cmd = ['curl', '-s', '-F', 'cc=test', 'http://test.com']
  # ์ŠคํŽ˜์ด์Šค๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๋ช…๋ น์–ด๋ฅผ ์ž˜๋ผ์„œ list๋กœ ๋งŒ๋“ค์–ด์ฃผ๋ฉด ๋ฉ๋‹ˆ๋‹ค.
  # ์œ„ ๋ช…๋ น์–ด๋Š” terminal์—์„œ curl -s -F cc=test http://test.com ์ด ๋˜๊ฒ ์ฃ ?
  
  fd_popen = subprocess.Popen(cmd, stdout=subprocess.PIPE).stdout
  # ๋ช…๋ น์–ด ์‹คํ–‰ ํ›„ ๋ฐ˜ํ™˜๋˜๋Š” ๊ฒฐ๊ณผ๋ฅผ ํŒŒ์ผ์— ์ €์žฅํ•ฉ๋‹ˆ๋‹ค.
  
  # ์œ„ 4ํ–‰์„ ๋ฆฌ์ŠคํŠธ ํ˜•ํƒœ๋กœ ์“ฐ์ง€ ์•Š๊ณ  ๋ฌธ์ž์—ด ํ˜•ํƒœ๋กœ ์“ธ ์ˆ˜ ์žˆ๋Š” ๋ฐฉ๋ฒ•์„ ๊ณต์œ  ๋ฐ›์•„ ์ž‘์„ฑํ•ฉ๋‹ˆ๋‹ค.
  # ์•„๋ž˜์™€ ๊ฐ™์ด Popen์— shell=True ์˜ต์…˜์„ ์ถ”๊ฐ€ํ•ด์ฃผ๋ฉด cmd๋ฅผ ๋ฌธ์ž์—ด ํ˜•ํƒœ๋กœ ์ ์–ด ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค!
  # cmd = 'curl -s -F cc=text http://test.com'
  # fd_popen = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout
  
  data = fd_popen.read().strip()
  # ํŒŒ์ผ์—์„œ ์ €์žฅ๋œ ๊ฒฐ๊ณผ๋ฅผ ์ฝ์–ด data์— ์ €์žฅํ•ฉ๋‹ˆ๋‹ค.
  
  fd_popen.close()
  # ํŒŒ์ผ์„ ๋‹ซ์Šต๋‹ˆ๋‹ค.
  # ํŒŒ์ผ์„ ์—ด๊ณ  ๋‚œ ๋’ค ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” ๊ฒฝ์šฐ ๊ผญ! ๋‹ซ์•„์ฃผ์‹œ๋Š” ๊ฑฐ ์•„์‹œ์ฃ !?
  
  print data

 

data๋ฅผ ์ถœ๋ ฅํ•ด๋ณด๋ฉด ์•ž์— b''๊ฐ€ ๋ถ™์–ด ๋‚˜์˜จ๋‹ค.

์ด๋Š” ๊ธฐ๋ณธ์ ์œผ๋กœ binary ํ˜•์‹์œผ๋กœ ๋ฐ˜ํ™˜ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์ƒ๊ธฐ๋Š” ํ˜„์ƒ์ธ๋ฐ ๊ฒฐ๊ณผ(data)๋ฅผ ๋””์ฝ”๋“œํ•ด์„œ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค.

data.decode('utf-8')

 

 

 

More

์‚ฌ์šฉ์„ ํ•ด๋ดค์„ ๋•Œ, checkout_output ๋ฉ”์†Œ๋“œ๊ฐ€ ํ›จ์”ฌ ํŽธํ•˜๊ณ  ์ข‹์•˜๋‹ค.

์˜ต์…˜์„ ์‚ฌ์šฉํ•˜๋ฉด ์ข€ ๋” ํŽธ๋ฆฌํ•˜๊ฒŒ ์‚ฌ์šฉ ํ•  ์ˆ˜ ์žˆ์œผ๋‹ˆ ๋ฌธ์„œ๋ฅผ ์ฐธ๊ณ ํ•˜์ž!

 

 


Thank for