2017-12-17 16 views
-2

プロンプトでPythonプログラムを "ls"のように書き、コマンドの出力を読み込み(.txtファイルに保存する)ためには何が必要ですか? ?Pythonプログラムでのcmdプロンプトへの書き込みと読み込み

+0

私はlinuxとPython 3.6を使用しています –

+1

[Pythonでの外部コマンドの呼び出し]の可能な複製(https://stackoverflow.com/questions/89228/calling-an-external-command-in-python) – Jerfov2

答えて

0

Pythonは(Linuxの& Windowsの場合)はbashとバッチコマンドを実行するために使用することができ、を利用することによって:

subprocess.check_call([ "LS"、 "-l"])

1

することができますsubprocessモジュールを使用してコマンドを呼び出す:

import subprocess 

# Call the command with the subprocess module 
# Be sure to change the path to the path you want to list 
proc = subprocess.Popen(["ls", "/your/path/here"], stdout=subprocess.PIPE) 

# Read stdout from the process 
result = proc.stdout.read().decode() 

# Be safe and close the stdout. 
proc.stdout.close() 

# Write the results to a file. 
with open("newfile.txt", "w") as f: 
    f.write(result) 

..あなただけのディレクトリを一覧表示したい場合はしかし、ノートを行い、osモジュールはlistdir()方法があります

import os 

with open("newfile.txt", "w") as f: 
    for filename in os.listdir("/your/path/here"): 
     f.write(filename) 
関連する問題