컴퓨터/Python

python subprocess powershell

풍경소리^^ 2023. 11. 17. 11:29

정상 출력이 되게 하려면 VSCode에서 실행하세요

test.ps1--------------------

# Get-Process (dir명령)
# Get-ChildItem B:\python\jupyternotebook\pandas_엑셀투파이썬
# Get-ChildItem B:\python\jupyternotebook\pandas_엑셀투파이썬 -Recurse
# Recurse 상속되어있는 모든 파일 보기 옵션

Get-Process | Out-File B:\python\jupyternotebook\pandas_엑셀투파이썬\script_result.txt

Get-ChildItem B:\python\jupyternotebook\pandas_엑셀투파이썬 -Recurse | Out-File B:\python\jupyternotebook\pandas_엑셀투파이썬\script_result.txt -Append

python 외부파일 실행--------------------

import subprocess

subprocess.Popen(['powershell.exe', "-ExecutionPolicy", "unrestricted", r"B:\python\jupyternotebook\pandas_엑셀투파이썬\test.ps1"])

python 여기서 바로 실행--------------------

import subprocess

# 여기서 바로 실행
# subprocess.Popen(['powershell.exe', '-ExecutionPolicy', 'unrestricted', 'Get-Process']).communicate() # 정상실행
subprocess.Popen(['powershell.exe', 'Get-Process']).communicate() # 정상실행

Get-Process, Get-ChildItem 동시실행--------------------

import subprocess

subprocess.Popen(['powershell.exe', 'Get-Process;Get-ChildItem -Path B:\python\jupyternotebook\pandas_엑셀투파이썬']).communicate()

dos명령어 실행--------------------

import subprocess

subprocess.run('dir', shell=True)

실행결과 외부파일에 저장--------------------

import subprocess

# 정상 저장 ipconfig
# with open('output.txt','w') as f:
#     p1 = subprocess.run('ipconfig', stdout=f, text=True)

# 안됨
# with open('output.txt','w') as f:
#     p1 = subprocess.run('dir', stdout=f, text=True)

# 정상 저장 ping
# with open('output.txt','w') as f:
#     p1 = subprocess.run(['ping','192.168.1.1'], stdout=f, text=True)

# 시스템 명령어 https://wikidocs.net/124373
# with open('out.txt', 'wb') as f:
#     out = subprocess.run(['cmd', '/c', 'dir'], capture_output=True)
#     f.write(out.stdout)

with open('out.txt', 'wb') as f:
    out = subprocess.run(['cmd', '/c', 'dir/w'], capture_output=True) # /c 실행후 종료 /k 실행후 그대로 남아있음
    f.write(out.stdout)

명령 하나씩 - 실행결과 외부파일에 저장--------------------

import subprocess

# 하나씩은 정상
# powershell_commands = [
#     'Get-Process'
# ]

# 하나씩은 정상
powershell_commands = [
    'Get-ChildItem -Path \"B:\\python\\jupyternotebook\\pandas_엑셀투파이썬\"'
]

# Use subprocess.Popen to run the PowerShell commands
process = subprocess.Popen(['powershell.exe'] + powershell_commands, stdout=subprocess.PIPE, text=True)

# Capture the output and errors
output, errors = process.communicate()

# Check for errors
if errors:
    print(f"Error: {errors}")
else:
    # Save the output to a file (out.txt)
    with open('out.txt', 'w') as file:
        file.write(output)

    print("Output saved to out.txt")

명령 두 개 실행 for문 - 실행결과 외부파일에 저장--------------------

# 명령 두 개 실행 for문
import subprocess

# Define the PowerShell commands
powershell_commands = [
    'Get-Process',
    'Get-ChildItem -Path "B:\\python\\jupyternotebook\\pandas_엑셀투파이썬"'
]

# Use subprocess.Popen to run each PowerShell command separately
for command in powershell_commands:
    process = subprocess.Popen(['powershell.exe', command], stdout=subprocess.PIPE, text=True)
    
    # Capture the output and errors
    output, errors = process.communicate()

    # Check for errors
    if errors:
        print(f"Error: {errors}")
    else:
        # Save the output to a file (out.txt) or handle it as needed
        with open('out.txt', 'a') as file:
            file.write(f"Command: {command}\n")
            file.write(output)
            file.write("\n\n")

print("Output saved to out.txt")

기존에 파일이 있어도 덮어쓰기

# 명령 두 개 실행 for문
import subprocess

# Define the PowerShell commands
powershell_commands = [
    'Get-Process',
    'Get-ChildItem -Path "B:\\python\\jupyternotebook\\pandas_엑셀투파이썬"'
]

# Use subprocess.Popen to run each PowerShell command separately
for command in powershell_commands:
    process = subprocess.Popen(['powershell.exe', command], stdout=subprocess.PIPE, text=True)
    
    # Capture the output and errors
    output, errors = process.communicate()

    # Check for errors
    if errors:
        print(f"Error: {errors}")
    else:
        # Save the output to a file (out.txt) or handle it as needed
        if command == powershell_commands[0]:
            with open('out.txt', 'w') as file:
                file.write(f"Command: {command}\n")
                file.write(output)
                file.write("\n\n")
        else:
            with open('out.txt', 'a') as file:
                file.write(f"Command: {command}\n")
                file.write(output)
                file.write("\n\n")

print("Output saved to out.txt")