Pythonプログラムでdateコマンドを実行する方法

Pythonプログラムでdateコマンドを実行する方法

コードは次のとおりです。

import os
#f=os.popen('date -d @1358193598 +%m/%d/%y')
f=os.popen('date')
print(f)

私はそれを双方向に結び、「壊れたパイプ」エラーが発生しました。この状況を処理する方法を知っていますか?また、サブプロセスモジュールを試しましたが、うまくいきませんでした。エラーメッセージは次のとおりです。

Traceback (most recent call last):
  File "t_2.py", line 23, in <module>
    dates.append(transfer_date_format(raw_date))
  File "t_2.py", line 6, in transfer_date_format
    stdin=subprocess.PIPE)
  File "/usr/lib64/python2.6/subprocess.py", line 639, in __init__
    errread, errwrite)
  File "/usr/lib64/python2.6/subprocess.py", line 1228, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

ベストアンサー1

試してみることができますos.system

f=os.system('date')

exitここではコードを変数に保存します。f

コマンドの実行結果を変数に保存するには、次のようにします。

f=os.popen('date').read()
print f

おすすめ記事