如何打开命令提示符以及使用python脚本运行的命令?

时间:2018-09-03 12:35:12

标签: python windows

我尝试了以下方法打开命令提示符并运行示例命令。但它立即关闭:

import os
# as of now i am just passing cd /../, later will be changing to a different command
os.system("start /wait cmd /c {cd /../}")

我也尝试过这种方法,但这会打开两个命令外壳:

import os
os.system("start /B start cmd.exe @cmd /k cd /d D:")

Two commands shell are being opened

是否可以仅打开一个命令提示符并运行该命令?

2 个答案:

答案 0 :(得分:3)

from google.oauth2 import service_account
import googleapiclient.discovery

SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']
SERVICE_ACCOUNT_FILE = '/path/to/service.json'

credentials = service_account.Credentials.from_service_account_file(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)
service = build('sheets', 'v4', http=creds.authorize(Http()))

# Call the Sheets API
SPREADSHEET_ID = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms'
RANGE_NAME = 'Class Data!A2:E'
result = service.spreadsheets().values().get(spreadsheetId=SPREADSHEET_ID,
                                            range=RANGE_NAME).execute()
values = result.get('values', [])

了解更多https://docs.python.org/3/library/subprocess.html#subprocess.Popen

答案 1 :(得分:2)

CMD窗口将运行您提供的命令,然后在完成时立即关闭,如果要保持窗口打开,则需要发送暂停命令:

  

os.system(“您的命令”)

     

os.system(“暂停”)