Cmd'ye komut gönderme ve çıkan sonucu alma

Hepinize merhabalar. 3 gün önce ben de python öğrenmeye başladım. temel işlemlerde sorun yaşamıyorum ama pyCharm üzerinde aşağıdaki işlemi yaparken sorun yaşıyorum.

1- cmd.exe’yi çağır,
2- cmd ekranına komut yazdır (dir, cd …, calc.exe vb.)
3- çıkan sonucu kaydet.

İlginiz için şimdiden çok teşekkür ederim.

os.system(“calc.exe”) şeklinde cmd komutu çalıştırabilirsiniz. Ama bu durumda cmd konsolu işlem bitene kadar görünür olup sonrasında kapanacaktır. Görünmemesi için subprocess kütüphanesini kullanmıştım bir aralar.

CREATE_NO_WINDOW = 0x08000000
subprocess.call(“calc.exe”, creationflags=CREATE_NO_WINDOW)

Output meselesine de burada değilmiş: https://stackoverflow.com/questions/1996518/retrieving-the-output-of-subprocess-call

Burada da os.system için cevap verilmiş ama cevabı veren subprocess öneriyor: https://stackoverflow.com/questions/3503879/assign-output-of-os-system-to-a-variable-and-prevent-it-from-being-displayed-on

1 Beğeni

Öncelikle ilginiz için çok teşekkür ederim.

Uzun süre araştırdım ancak tam anlamıyla çalıştırabildiğim bir kod olmadı. Sanırım kodlamanın mantığını anlayamıyorum. Oysa 2 tane de kitap almıştım. :slight_smile:

calc.exe değil de örneğin dir komutunu yazdırsam ve çıkan sonucu çekebilsem yeterli olacak benim için.

1 Beğeni

Merhaba.

@LaAhad’ın da bahsettiği gibi subprocess modülü bunun için en iyi yol. Ancak os.system fonksiyonu ile de şu şekilde istediğiniz çıktıyı alabilirsiniz:

import os
import sys
import io

# Standard çıktıyı dosya benzeri bir yapıya atadık.
# Normalde sys.stdout'a bir dosya atanması gerekir.
# Ancak StringIO dosya benzeri hafızada tutulan bir yapıdır.
# Bu yapı sonucu doğrudan alıp kullanmak için uygun bir yapıdır.
stringIO = io.StringIO()
sys.stdout = stringIO

# Komutumuzu çalıştırıyoruz:
os.system('dir')

# Yukarıdaki komutun çıktısı sys.stdout'a yazdırılacaktır.
# Biz sys.stdout'u stringIO olarak belirlediğimiz için, sonucu alırken bu değişkeni kullanacağız.
# getvalue metodu stringIO'ya yazılmış değeri almamızı sağlar.
print(stringIO.getvalue())

İyi çalışmalar.

2 Beğeni
from subprocess import PIPE,Popen
komut='NETSH WLAN SHOW INTERFACE | findstr /r "^....SSID"'
p = Popen(komut,shell=True,stderr=PIPE,stdout=PIPE)
(out,err) = p.communicate()

out=str(out)
wifi_adi=out[31:-5]

Bunun için şuan yukarıdaki kodları kullanıyorum. Verdiğim örnekteki komut bağlı olduğum kablosuz ağın adını almamı sağlıyor.

1 Beğeni

Bu islem linux icinde gecerlimi?

Merhaba @ismailarilik


Komutunuzu denedim . Komutu gerçekleştiriyor ama benim fotoğraftaki print yazısının devam etmesini istiyorum .
Ne yapmalıyım ?

c3mcavus

Tabii, geçerli elbette.

Nasıl yani, anlayamadım.


print("Loading")

Yazısından sonra ‘cls’ komutu ile satırlar silinsin sonra tekrar


print("CEM")

Verdiğiniz komut siliyor devam etmiyor . Ben devam etmesini istiyorum . @ismailarilik

c3mcavus

Hocam os.system çıktıyı orijinal sys.stdout’a yönlendiriyor?

>>> import os, io, sys
>>> IO = io.StringIO()
>>> IO
<_io.StringIO object at 0x000001833FF6D8B8>
>>> sys.stdout = IO
>>> os.system("echo Python'u seviyorum!")
Python'u seviyorum!
>>> #!?

bunları çıkarman lazım gözükmesi için. while True içinde input var mı ? sonsuz döngü de ram’i bitirir.

e = io.StringIO()
sys.shdout = e

Var kodun tamamı böyle sıkıntı olur mu ?


import time
import socket
import sqlite3
import threading
import os
import sys
import io
from time import sleep

def degerekle():
    conn = sqlite3.connect("database.db")

    c = conn.cursor()
    isim = input("ADINIZ :")
    kullanici = input("Kullanıcı adı :")
    sifre = input("Parola :")
    c.execute("INSERT INTO CHATTEG VALUES(?,?,?)",(isim,kullanici,sifre))
    conn.commit()
    conn.close()
    return

def security():
    print("Center to account change!")
    r = input()
    conn = sqlite3.connect("database.db")
    c = conn.cursor()
    c.execute("SELECT parola FROM WHERE parola = '%s'"%(r))
    dataaa = c.fetchall()
    if dataaa:
        e = input("Enter new account name please :")
        c.execute("UPDATE CHATTEG SET kullanıcı_adı = {} WHERE kullanıcı_adı = {}".format(r,e))
        print("Upgrade is over!!!")
        return
    else:
        print("NOT FOUND THİS ACCOUNT!")
        print("You will be redirected to the homepage!")
        return

def password():
     print("Center to password change!")
     r = input("Please enter new password ::")
     return r

while True:
    print("Loading...")
    for i in range(101):
        sys.stdout.write('\r')
        sys.stdout.write("[%-10s] %d%%" % ('=' * i, 1 * i))
        sys.stdout.flush()
        sleep(0.06)

    print("""
       ___________________       ______________              __                   __
 - |                  |   3 |____________  | -3 _ -     /  \   _  - _     3  /  \     -  3 _     -        _3
_3- |  ________________|                |  | _  _ -    /    \   3      -    /    \         _
  _|  |    _  -  3_   -          _  -    |  | _ 3 -   /      \   _    -    /      \ _
- _ |  |                     ___________|  | _  -    /   /\   \   3      -/   /\   \      3  _    _
   |  |     3_     _ -      | __________   |   _ 3  /   /  \   \ _   -   /   /  \   \    3                _  -
 - |  |                      |___________   | _    /   /    \   \   3-  /   /    \   \   _   _  -
  3 |  |     -  3_               -  _   |  |   -_ /   /      \   \  -  /   /      \   \           3        _   _ -
_ -|  |_______________     3 _           |  | _  /   /        \   \ _ /   /        \   \  _   -       -
  _|                  |      ___________|  |    /   /          \   \_/   /          \___\           _       _    _
_  -|__________________|  3 |______________|   /___/            \       /
                                                                 \     /
                                                                  \   /
  163                                                              \ /                                        163
                                                                    |
 ___________________________________________________________________|
 |
 |
 |-->>CHATGET                 ----------------------->c
 |-->>Create a file           ----------------------->d
 |-->>Print text to a file    ----------------------->y
 |-->>Reading file            ----------------------->o
 |-->>OIASAS                  ----------------------->t
    """)
    f = input()
    if f == "c":
     print("                    ****       ****              CHATTEG              ****       ****          \n                    / /         / /                                    / /        / /\n                     / /      / /                                    / /        / /\n")
     print("                                           SIGN UP>>>>>1\n                                                 SIGN LOGIN>>>>>2\n")
     y = input()
     if y == "2":
        db = sqlite3.connect("database.db")
        cr = db.cursor()
        kullanici = input("User Name : ")
        sifre = input("Password : ")

        cr.execute("SELECT * FROM CHATTEG WHERE kullanıcı_adı = '%s' AND parola = '%s'"%(kullanici,sifre))
        dataa = cr.fetchone()
        print("Confirm entry...")
        time.sleep(2)

        if dataa:
            print("Entry approved.")
            time.sleep(4)
            print("                                    WELCOME to >>>>>CHATTEG<<<<< {} !!!".format(dataa[0]))

            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

            port = 1234

            uname = input("Enter user name::")

            ip = input('Enter the IP Address::')

            s.connect((ip, port))

            s.send(uname.encode('ascii'))

            clientRunning = True

            def receiveMsg(sock):

                serverDown = False

                while clientRunning and (not serverDown):

                    try:

                        msg = sock.recv(1024).decode('ascii')

                        print(msg)

                    except:

                        print('Server is Down. You are now Disconnected. Press enter to exit...')

                        serverDown = True

            threading.Thread(target=receiveMsg, args=(s,)).start()

            while clientRunning:

                tempMsg = input()

                msg = uname + '>>' + tempMsg

                if '**quit' in msg:

                    clientRunning = False

                    s.send('**quit'.encode('ascii'))

                else:

                    s.send(msg.encode('ascii'))

        elif kullanici:
            print("False password!!")
            h = input(">>>>>Change password::1 >>>>>Again try login::2\n")

            if h == "1":
                conn = sqlite3.connect("database.db")
                c = conn.cursor()
                c.execute("UPDATE CHATTEG SET  kullanıcı_adı = {} WHERE parola = {}".format(kullanici, password()))
                print("Upgrade is over!!!")
                print("PLease try login :)")
            elif h == "2":
                print("Loading...")
                time.sleep(3)
            else:
                print("Please enter a valid option.")
                print("You will be redirected to the homepage!")
                print("Caoo.              >>>>>CHATTEG<<<<<")

        elif sifre:
            print("False User!!")
     elif y == "1":
        degerekle()
        print("\nWelcome to the Club!!!")
        print("\nPlease try login.")
    elif  f == "d" or "D":
        print("\nLET's make File ")
        print("\nFirstly you decide what is name file name?")
        p = input("\nFile name ::")
        i = 0
        for i in range(101):
            sys.stdout.write('\r')
            sys.stdout.write("[%-10s] %d%%" % ('=' * i, 1 * i))
            sys.stdout.flush()
            time.sleep(0.06)
        file = open("{}".format(p),"a")
        print("\nFile is ready!!!")
        print("\nNow , İf you want , let's print the file. [Y/N]")
        m = input()

        if m == "Y" or "y":
            o = input("\nTell me what you want to write to the file>>>")
            filee = open("{}".format(p),"w")
            filee.write(o)
            i = 0
            for i in range(101):
                sys.stdout.write('\r')
                sys.stdout.write("[%-10s] %d%%" % ('=' * i, 1 * i))
                sys.stdout.flush()
                time.sleep(0.06)
            print("\nWriting Ready!!!")
            print("\nLet's read your file now. [Y/N]")
            b = input()

            if b == "Y" or "y":
                q = input("\nTo read your file , please enter (file_ismi.txt)>>>")

                if q == ("{}.txt".format(p)):
                    i = 0
                    for i in range(101):
                        sys.stdout.write('\r')
                        sys.stdout.write("[%-10s] %d%%" % ('=' * i, 1 * i))
                        sys.stdout.flush()
                        time.sleep(0.06)
                    print("\n{}.txt opened!!!".format(p))
                    print(o)
                    time.sleep(2)
                    print("\nYou are returning to the main page where you have done all the operations.")
            elif b == "N" or "n":
                print("\nYou are returning to the main page where you have done all the operations.")
            else:
                print("\nNot a valid command!!!")
                time.sleep(1)
                print("                       See you")
        elif m == "N" or "n":
            print("\nYou are returning to the main page where you have done all the operations.")
        else:
            print("\nNot a valid command!!!")
            time.sleep(1)
            print("                   See you")

@HKMDMR
def security() ve password() hatalı onlara aldırmayınız . Deneme amaçlı yapıyordum .

c3mcavus

İnput mevcut sıkıntı olmaz ama kodda bir kaç bişey belirtiyim.
1-
open ile dosya açtığında close ile kapatmalısın … yoksa açık kalır.
yada with open ("dosyaismi.txt","açmaModu") as file çalışırsan girinti bitiminde kendisi kapatacaktır.
2- kodda Create sql sorgusu ile bir tablo oluşturulmamış ama INSERT ile ekleme sorgusu var . oluşturulmadan ekleyemezsin.

1 Beğeni

Teşekkürler @HKMDMR
close komutunu kullanmayı unutmuşum .
Create ile önceden tablo oluşturmuştum o yüzden yazmak için gerek görmedim sadece bağlanıp okumak istedim .

c3mcavus

1 Beğeni
import os    
print(os.popen('ls').read())

image
Bu fonksiyon işini görücektir. (en basit şekilde…)

1 Beğeni