Python windows cmd exe

Содержание
  1. Running cmd in python — Stack Overflow
  2. Основные моменты
  3. How to open a program with cmd.exe from python?
  4. Python — запуск cmd.exe с аргументом, и последующим сохранением ответа в .txt файл
  5. Running cmd in python
  6. Блок-схема выполнения кода интерпретатором
  7. Где запускать python-скрипты и как?
  8. Запуск python-кода интерактивно
  9. Запуск python-скриптов в интерактивном режиме
  10. Запуск кода динамически
  11. Запуск кода из ide
  12. Запуск кода из файлового менеджера
  13. Запуск кода с помощью runpy
  14. Запуск скриптов python из текстового редактора
  15. Интерактивный режим в linux
  16. Интерактивный режим в macos
  17. Интерактивный режим в windows
  18. Использование import для запуска скриптов
  19. Использование importlib для запуска кода
  20. Как выполнять код интерактивно
  21. Как выполняются python-скрипты?
  22. Как запускать python-скрипты?
  23. Как запускать скрипт в командной строке?
  24. Как запустить python-скрипт из другого кода
  25. How do I run a Python program in the Command Prompt in Windows 7?
  26. 23 Answers 23
  27. Running Python scripts conveniently under Windows
  28. Making sure Windows can find the Python interpreter
  29. Associating Python with .py and .pyc
  30. Omitting the .py extension (editing PATHEXT)
  31. Adding scripts to the system PATH
  32. Running directly without tweaking the PATH
  33. Creating shortcuts or batch files
  34. Advanced: appending to PYTHONPATH

Running cmd in python — Stack Overflow

Основные моменты

  1. Python-код можно писать в интерактивном и не-интерактивном режимах. При выходе из интерактивного режима вы теряете данные. Поэтому лучше использовать sudo nano your_python_filename.py .
  2. Код можно запускать с помощью IDE, редактора кода или командной строки.
  3. Есть разные способы импорта кода и использования его из другого скрипта. Выбирайте вдумчиво, рассматривая все преимущества и недостатки.
  4. Python читает написанный код, транслирует его в байткод, который затем используется как инструкция — все это происходит при запуске скрипта. Поэтому важно учиться использовать байткод для оптимизации Python-кода.

How to open a program with cmd.exe from python?

I am using python 3.3 and in my code I need something to open cmd.exe with the following arguments and run it. The desired line in cmd.exe should be:

I saw different answers but the most I managed with subprocess.call is to open either cmd.exe, or global_mapper.exe. I did not manage to obtain the line above in cmd.exe.

Neither of them worked well.

Of course, it would be great if the line would be also executed. Can anyone help me make this happen?

Python — запуск cmd.exe с аргументом, и последующим сохранением ответа в .txt файл

Если команда не является внутренней (вроде ASSOC ) , то нет нужды как правило запускать cmd.exe , чтобы получить вывод внешней программы в Питоне.

Вместо этого напрямую запускайте программу. К примеру, чтобы перенаправить стандартный вывод arp -a команды в txt файл:

На Windows, команда и её аргументы передаются как строка (родной интерфейс). Переносимый код должен использовать список: каждый аргумент как отдельный элемент следовало бы передать: [‘arp’, ‘-a’] . Если возникли проблемы с кодировкой, то см. Python Взаимодействие с cmd.exe .

Обратите внимание, что cmd.exe не используется для запуска arp.exe .

Если вы хотите запустить команду, которая требует cmd.exe , к примеру dir , то достаточно shell=True передать:

Running cmd in python

It is better to call subprocess.call in another way.

args is required for all calls and should be a string, or a sequence
of program arguments. Providing a sequence of arguments is generally
preferred, as it allows the module to take care of any required
escaping and quoting of arguments (e.g. to permit spaces in file
names). If passing a single string, either shell must be True (see
below) or else the string must simply name the program to be executed
without specifying any arguments.

Блок-схема выполнения кода интерпретатором

  • Шаг 1: скрипт или .py-файл компилируется, и из него генерируются бинарные данные. Готовый файл имеет расширение .pyc или .pyo.
  • Шаг 2: генерируется бинарный файл. Он читается интерпретатором для выполнения инструкций.

Это набор инструкций, которые приводят к финальному результату.

Иногда полезно изучать байткод. Если вы планируете стать опытным Python-программистом, то важно уметь понимать его для написания качественного кода.

Это также пригодится для принятия решений в процессе. Можно обратить внимание на отдельные факторы и понять, почему определенные функции/структуры данных работают быстрее остальных.

Где запускать python-скрипты и как?

Python-код можно запустить одним из следующих способов:

  1. С помощью командной строки операционной системы (shell или терминал);
  2. С помощью конкретной версии Python или Anaconda ;
  3. Использовать Crontab;
  4. Запустить код с помощью другого Python-скрипта;
  5. С помощью файлового менеджера;
  6. Использовать интерактивный режим Python;
  7. Использовать IDE или редактор кода.

Запуск python-кода интерактивно

Для запуска интерактивной сессии нужно просто открыть терминал или командную строку и ввести python (или python3 в зависимости от версии). После нажатия Enter запустится интерактивный режим.

Вот как запустить интерактивный режим в разных ОС.

Запуск python-скриптов в интерактивном режиме

В таком режиме можно писать код и исполнять его, чтобы получить желаемый результат или отчет об ошибке. Возьмем в качестве примера следующий цикл.

Этот код должен выводить целые числа от 0 до 5. В данном случае вывод — все, что появилось после print(i).

Для выхода из интерактивного режима нужно написать следующее:

И нажать Enter. Вы вернетесь в терминал, из которого и начинали.

Есть и другие способы остановки работы с интерактивным режимом Python. В Linux нужно нажать Ctrl D, а в Windows — Ctrl Z Enter.

Стоит отметить, что при использовании этого режима Python-скрипты не сохраняются в локальный файл.

Запуск кода динамически

Рассмотрим функцию exec(), которая также используется для динамического выполнения скриптов. В Python2 эта функция была инструкцией.

Вот как она помогает выполнять код динамически на примере строки.

Однако этот способ уже устарел. Он медленный и непредсказуемый, а Python предлагает массу других вариантов.

Запуск кода из ide

IDE можно использовать не только для запуска Python-кода, но также для выбора среды и отладки.

Читайте также:  Как убрать общедоступную сеть windows

Интерфейс этих программ может отличаться, но список возможностей должен совпадать: сохранение, запуск и редактирование кода.

Запуск кода из файлового менеджера

Что если бы был способ запустить Python-скрипт двойным кликом по файлу с ним. Это можно сделать, создав исполняемый файл. Например, в случае с Windows для этого достаточно создать файл с расширением .exe и запустить его двойным кликом.

Запуск кода с помощью runpy

Модуль runpy ищет и исполняет Python-скрипт без импорта. Он также легко используется, ведь достаточно просто вызывать имя модуля в run_module().

Вот как, например, выполнить code1.py с помощью runpy.

Запуск скриптов python из текстового редактора

Для запуска кода с помощью текстового редактора можно использовать команду по умолчанию (run) или горячие клавиши (Function F5 или просто F5 в зависимости от ОС).

Вот пример того, как код выполняется в IDLE.

Но стоит обратить внимание на то, что в данном случае нет контроля над виртуальной средой, как это бывает при исполнении с помощью интерфейса командной строки.

Поэтому IDE и продвинутые редакторы текста куда лучше базовых редакторов.

Интерактивный режим в linux

Откройте терминал. Он должен выглядеть приблизительно вот так :

После нажатия Enter будет запущен интерактивный режим Python.

Интерактивный режим в macos

На устройствах с macOS все работает похожим образом. Изображение ниже демонстрирует интерактивный режим в этой ОС.

Интерактивный режим в windows

В Windows нужно открыть командную строку и ввести python. После нажатия Enter появится приблизительно следующее:

Использование import для запуска скриптов

Импорт модулей для загрузки скриптов и библиотек используется постоянно. Можно даже написать собственный скрипт (например code1.py) и импортировать его в другой файл без необходимости повторять то же самое.

Вот как нужно импортировать code1.py в новом скрипте.

Но таким образом импортируется все содержимое файла code1.py. Это не проблема до тех пор, пока не появляется необходимость, в том, чтобы код был оптимизирован и быстро работал.

Предположим, что внутри файла есть маленькая функция, например chart_code1(), которая рисует красивый график. И нужна только она. Вместо того чтобы взывать весь скрипт целиком, можно вызвать ее.

Вот как это обычно делается.

Теперь появляется возможность использовать chart_code1 в новом файле так, будто бы эта функция была написана здесь.

Использование importlib для запуска кода

import_module() из importlib позволяет импортировать и исполнять другие Python-скрипты.

Это работает очень просто. Для скрипта code1.py нужно сделать следующее:

И нет необходимости добавлять .py в import_module().

Разберем случай, когда есть сложная структура папок, и нужно использовать importlib. Предположим, что структура следующая:

В таком случае, написав, например, importlib.import_module(«level3»), вы получите ошибку. Это называется относительным импортом и работает за счет явного использования относительного пути.

Так, для запуска скрипта level3.py можно написать так:

Как выполнять код интерактивно

Есть больше 4 способов запустить Python-скрипт интерактивно. Рассмотрим их все подробно.

Как выполняются python-скрипты?

Отличный способ представить, что происходит при выполнении Python-скрипта, — использовать диаграмму ниже. Этот блок представляет собой скрипт (или функцию) Python, а каждый внутренний блок — строка кода.

При запуске скрипта интерпретатор Python проходит сверху вниз, выполняя каждую из них. Именно таким образом происходит выполнение кода.

Но и это еще не все.

Как запускать python-скрипты?

Для запуска Python-скрипта с помощью командной строки сначала нужно сохранить код в локальный файл.

Возьмем в качестве примера файл, который был сохранен как python_script.py. Сохранить его можно вот так:

  • Создать Python-скрипт из командной строки и сохранить его,
  • Создать Python-скрипт с помощью текстового редактора или IDE и сохранить его. Просто создайте файл, добавьте код и сохраните как «python_script.py»

Сохранить скрипт в текстовом редакторе достаточно легко. Процесс ничем не отличается от сохранения простого текстового файла.

Но если использовать командную строку, то здесь нужны дополнительные шаги. Во-первых, в самом терминале нужно перейти в директорию, где должен быть сохранен файл. Оказавшись в нужной папке, следует выполнить следующую команду (на linux):

После нажатия Enter откроется интерфейс командной строки, который выглядит приблизительно следующим образом:

Теперь можно писать код и с легкостью сохранять его прямо в командной строке.

Как запускать скрипт в командной строке?

Скрипты можно запустить и с помощью команды Python прямо в интерфейсе терминала. Для этого нужно убедиться, что вы указали путь до него или находитесь в той же папке. Для выполнения скрипта (python_script.py) откройте командную строку и напишите python3 python_script.py.

Замените python3 на python, если хотите использовать версию Python2.x.

Вот что будет храниться в самом файле python_script.py:

Вывод в командной строке будет следующим:

Предположим, что нужно сохранить вывод этого года (0, 1, 2, 3, 4). Для этого можно использовать оператор pipe.

Это делается вот так:

После этого будет создан файл «newfile.txt» с сохраненным выводом.

Как запустить python-скрипт из другого кода

Хотя об этом явно не говорилось, можно прийти к выводу, что в случае с Python есть возможность:

  • Запустить скрипт в командной строке, и этот скрипт будет вызывать другой код;
  • Использовать модуль для загрузки другого скрипта.

How do I run a Python program in the Command Prompt in Windows 7?

I’m trying to figure out how to run Python programs with the Command Prompt on Windows 7. (I should have figured this out by now. )

When I typed «python» into the command prompt, I got the following error:

‘python’ is not recognized as an internal or external command, operable program or batch file.

It was somewhat helpful, but the tutorial was written for Windows 2000 and older, so it was minimally helpful for my Windows 7 machine. I attempted the following:

For older versions of Windows the easiest way to do this is to edit the C:\AUTOEXEC.BAT >file. You would want to add a line like the following to AUTOEXEC.BAT:

This file did not exist on my machine (unless I’m mistaken).

Читайте также:  Драйвер для сидирома windows

In order to run programs, your operating system looks in various places, and tries to match the name of the program / command you typed with some programs along the way.

control panel > system > advanced > |Environmental Variables| > system variables -> Path

this needs to include: C:\Python26; (or equivalent). If you put it at the front, it will be the first place looked. You can also add it at the end, which is possibly saner.

Then restart your prompt, and try typing ‘python’. If it all worked, you should get a «>>>» prompt.

This was relevant enough for Windows 7, and I made my way to the System Variables. I added a variable «python» with the value «C:\Python27»

I continued to get the error, even after restarting my computer.

Anyone know how to fix this?

23 Answers 23

You need to add C:\Python27 to your system PATH variable, not a new variable named «python».

Find the system PATH environment variable, and append to it a ; (which is the delimiter) and the path to the directory containing python.exe (e.g. C:\Python27 ). See below for exact steps.

The PATH environment variable lists all the locations that Windows (and cmd.exe ) will check when given the name of a command, e.g. «python» (it also uses the PATHEXT variable for a list of executable file extensions to try). The first executable file it finds on the PATH with that name is the one it starts.

Note that after changing this variable, there is no need to restart Windows, but only new instances of cmd.exe will have the updated PATH. You can type set PATH at the command prompt to see what the current value is.

Exact steps for adding Python to the path on Windows 7+:

  1. Computer -> System Properties (or Win+Break ) -> Advanced System Settings
  2. Click the Environment variables. button (in the Advanced tab)
  3. Edit PATH and append ;C:\Python27 to the end (substitute your Python version)
  4. Click OK. Note that changes to the PATH are only reflected in command prompts opened after the change took place.

Assuming you have Python2.7 installed

Goto the Start Menu

Right Click «Computer»

A dialog should pop up with a link on the left called «Advanced system settings». Click it.

In the System Properties dialog, click the button called «Environment Variables».

In the Environment Variables dialog look for «Path» under the System Variables window.

Add «;C:\Python27» to the end of it. The semicolon is the path separator on windows.

Click Ok and close the dialogs.

Now open up a new command prompt and type «python»

It has taken me some effort looking for answers here, on the web, and and in the Python documentation, and testing on my own, to finally get my Python scripts working smoothly on my Windows machines (WinXP and Win7). So, I just blogged about it and am pasting that below in case it’s useful to others. Sorry it’s long, and feel free to improve it; I’m no expert.

[UPDATE: Python 3.3 now includes the Python Launcher for Windows, which allows you to type py (rather than python) to invoke the default interpreter, or py -2, py -3, py -2.7, etc. It also supports shebang lines, allowing the script itself to specify. For versions prior to 3.3, the launcher is available as a separate download. http://docs.python.org/3/whatsnew/3.3.html ]

Running Python scripts conveniently under Windows

Maybe you’re creating your own Python scripts, or maybe someone has given you one for doing something with your data files. Say you’ve acquired a Python script and have saved it to «D:\my scripts\ApplyRE.py». You want to run it conveniently by either double-clicking it or typing it into the command line from any location, with the option of passing parameters to it like this (-o means «overwrite the output file if it already exists»):

Say you also have a data file, «C:\some files\some lexicon.txt». The simplest option is to move the file or the script so they’re in the same location, but that can get messy, so let’s assume that they’ll stay separate.

Making sure Windows can find the Python interpreter

After installing Python, verify that typing python into a command prompt works (and then type exit() to get back out of the Python interpreter).

If this doesn’t work, you’ll need to append something like «;C:\Python32» (without quotes) to the PATH environment variable. See PATHEXT below for instructions.

Associating Python with .py and .pyc

Verify that double-clicking on ApplyRE.py runs it. (It should also have a Python logo as its icon and be labeled «Python File», by the way.) If this isn’t already done, right-click on a .py file, choose Open With, Choose Program, and check «Always use. » This association improves convenience but isn’t strictly necessary—you can specify «python» every time you want to run a script, like this:

Here’s a very specific variation, which is optional unless you need to specify a different version of the interpreter.

But that’s a pain. Fortunately, once Python is installed, in the PATH, and associated with .py, then double-clicking a .py file or directly typing it as a command should work fine. Here, we seem to be running the script directly—it’s nice and simple to run it on a sample file that’s located in the «my scripts» folder along with the script.

Читайте также:  Установка новой версии mac os

Omitting the .py extension (editing PATHEXT)

To further reduce typing, you can tell Windows that .py (and perhaps .pyc files) are executable. To do this, right-click Computer and choose Properties, Advanced, Environment Variables, System Variables. Append «;.PY;.PYC» (without quotes) to the existing PATHEXT variable, or else create it if you’re certan it doesn’t exist yet. Close and reopen the command prompt. You should now be able to omit the .py (FYI, doing so would cause ApplyRE.exe or ApplyRE.bat to run instead, if one existed).

Adding scripts to the system PATH

If you’re going to use your scripts often from the command prompt (it’s less important if doing so via using BAT files), then you’ll want to add your scripts’ folder to the system PATH. (Next to PATHEXT you should see a PATH variable; append «;D:\my scripts» to it, without quotes.) This way you can run a script from some other location against the files in current location, like this:

Success! That’s pretty much all you need to do to streamline the command-line.

Running directly without tweaking the PATH

If you’re a fast typist or don’t mind creating a batch file for each situation, you can specify full paths (for the script, or for the parameters) instead of tweaking PATH.

Creating shortcuts or batch files

If .py is associated with an installed Python, you can just double-click ApplyRE.py to run it, but the console may appear and disappear too quickly to read its output (or failure!). And to pass parameters, you’d need to first do one of the following. (a) Right-click and create a shortcut. Right-click the shortcut to edit properties and append parameters to Target. (b) Create a batch file—a plain text file with a distinct name such as ApplyRErun.bat. This option is probably better because you can ask it to pause so you can see the output. Here is a sample BAT file’s contents, written to be located and run from c:\some files .

Advanced: appending to PYTHONPATH

This usually isn’t necessary, but one other environment variable that may be relevant is PYTHONPATH. If we were to append d:\my scripts to that variable, then other Python scripts in other locations could make use of those via import statements.

Python comes with a script that takes care of setting up the windows path file for you.

After installation, open command prompt

Go to the directory you installed Python in

Run python and the win_add2path.py script in Tools\Scripts

Now you can use python as a command anywhere.

You have to put the python path in the PATH variable.

In the System Variables section, you should have User Variables and System Variables. Search for the PATH variable and edit its value, adding at the end ;C:\python27 .

The ; is to tell the variable to add a new path to this value, and the rest, is just to tell which path that is.

On the other hand, you can use ;%python% to add the variable you created.

You don’t add any variables to the System Variables. You take the existing ‘Path’ system variable, and modify it by adding a semi-colon after, then c:\Python27

So after 30 min of R&D i realized that after setup the PATH at environment variable

C:> cd Python27 C:\ Python27> python.exe

USE python.exe with extension

alternative option is :

if the software is installed properly directly run Python program, your command line screen will automatically appear without cmd.

Go to the Start Menu

Right Click «Computer»

A dialog should pop up with a link on the left called «Advanced system settings». Click it.

In the System Properties dialog, click the button called «Environment Variables».

In the Environment Variables dialog look for «Path» under the System Variables window.

Add «;C:\Python27» to the end of it. The semicolon is the path separator on windows.

Click Ok and close the dialogs.

Now open up a new command prompt and type «python» or if it says error type «py» instead of «python»

Even after going through many posts, it took several hours to figure out the problem. Here is the detailed approach written in simple language to run python via command line in windows.

1. Download executable file from python.org
Choose the latest version and download Windows-executable installer. Execute the downloaded file and let installation complete.

2. Ensure the file is downloaded in some administrator folder

  1. Search file location of Python application.
  2. Right click on the .exe file and navigate to its properties. Check if it is of the form, «C:\Users. «. If NO, you are good to go and jump to step 3. Otherwise, clone the Python37 or whatever version you downloaded to one of these locations, «C:\», «C:\Program Files», «C:\Program Files (x86)».

3. Update the system PATH variable This is the most crucial step and there are two ways to do this:- (Follow the second one preferably)

1. MANUALLY
— Search for ‘Edit the system Environment Variables’ in the search bar.(WINDOWS 10)
— In the System Properties dialog, navigate to «Environment Variables».
— In the Environment Variables dialog look for «Path» under the System Variables window. (# Ensure to click on Path under bottom window named System Variables and not under user variables)
— Edit the Path Variable by adding location of Python37/ PythonXX folder. I added following line:-
» ;C:\Program Files (x86)\Python37;C:\Program Files (x86)\Python37\Scripts »
— Click Ok and close the dialogs.

Оцените статью