How to run python script on windows cmd
How to run python script on windows cmd
How do I run Python script using arguments in windows command line
This is my python hello.py script:
The problem is that it can’t be run from the windows command line prompt, I used this command:
But it didn’t work unfortunately, may somebody please help?
7 Answers 7
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
I found this thread looking for information about dealing with parameters; this easy guide was so cool:
Here are all of the previous answers summarized:
The code should look like this:
Then run the code with this command:
To execute your program from the command line, you have to call the python interpreter, like this :
If you code resides in another directory, you will have to set the python binary path in your PATH environment variable, to be able to run it, too. You can find detailed instructions here.
Your indentation is broken. This should fix it:
Obviously, if you put the if __name__ statement inside the function, it will only ever be evaluated if you run that function. The problem is: the point of said statement is to run the function in the first place.
Moreover see @thibauts answer about how to call python script.
There are more than a couple of mistakes in the code.
import sys def hello(a,b): print («hello and that’s your sum:») sum=float(a)+float(b) print (sum)
if __name__ == «__main__»: hello(sys.argv[1], sys.argv[2])
Also, using «C:\Python27>hello 1 1» to run the code looks fine but you have to make sure that the file is in one of the directories that Python knows about (PATH env variable). So, please use the full path to validate the code. Something like:
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).
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.
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?
24 Answers 24
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
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+:
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.
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.
Here’s a very specific variation, which is optional unless you need to specify a different version of the interpreter.
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
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.
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
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.
Запуск Python и python-скрипт на компьютере
Код, написанный на языке Python, может храниться в редакторе кода, IDE или файле. И он не будет работать, если не знать, как его правильно запускать.
В этом материале рассмотрим 7 способов запуска кода, написанного на Python. Они будут работать вне зависимости от операционной системы, среды Python или местоположения кода.
Где запускать Python-скрипты и как?
Python-код можно запустить одним из следующих способов:
Запуск Python-кода интерактивно
Для запуска интерактивной сессии нужно просто открыть терминал или командную строку и ввести python (или python3 в зависимости от версии). После нажатия Enter запустится интерактивный режим.
Вот как запустить интерактивный режим в разных ОС.
Интерактивный режим в Linux
Откройте терминал. Он должен выглядеть приблизительно вот так :
После нажатия Enter будет запущен интерактивный режим Python.
Интерактивный режим в macOS
На устройствах с macOS все работает похожим образом. Изображение ниже демонстрирует интерактивный режим в этой ОС.
Интерактивный режим в Windows
Запуск Python-скриптов в интерактивном режиме
В таком режиме можно писать код и исполнять его, чтобы получить желаемый результат или отчет об ошибке. Возьмем в качестве примера следующий цикл.
Для выхода из интерактивного режима нужно написать следующее:
И нажать Enter. Вы вернетесь в терминал, из которого и начинали.
Есть и другие способы остановки работы с интерактивным режимом Python. В Linux нужно нажать Ctrl + D, а в Windows — Ctrl + Z + Enter.
Стоит отметить, что при использовании этого режима Python-скрипты не сохраняются в локальный файл.
Как выполняются Python-скрипты?
Отличный способ представить, что происходит при выполнении Python-скрипта, — использовать диаграмму ниже. Этот блок представляет собой скрипт (или функцию) Python, а каждый внутренний блок — строка кода.
При запуске скрипта интерпретатор Python проходит сверху вниз, выполняя каждую из них. Именно таким образом происходит выполнение кода.
Но и это еще не все.
Блок-схема выполнения кода интерпретатором
Это набор инструкций, которые приводят к финальному результату.
Иногда полезно изучать байткод. Если вы планируете стать опытным Python-программистом, то важно уметь понимать его для написания качественного кода.
Это также пригодится для принятия решений в процессе. Можно обратить внимание на отдельные факторы и понять, почему определенные функции/структуры данных работают быстрее остальных.
Как запускать Python-скрипты?
Для запуска Python-скрипта с помощью командной строки сначала нужно сохранить код в локальный файл.
Возьмем в качестве примера файл, который был сохранен как python_script.py. Сохранить его можно вот так:
Сохранить скрипт в текстовом редакторе достаточно легко. Процесс ничем не отличается от сохранения простого текстового файла.
Но если использовать командную строку, то здесь нужны дополнительные шаги. Во-первых, в самом терминале нужно перейти в директорию, где должен быть сохранен файл. Оказавшись в нужной папке, следует выполнить следующую команду (на linux):
После нажатия Enter откроется интерфейс командной строки, который выглядит приблизительно следующим образом:
Теперь можно писать код и с легкостью сохранять его прямо в командной строке.
Как запускать скрипт в командной строке?
How to run a python file/script from sublime text 3 on cmd in windows 10?
I have been searching the internet up and down for a solution to this. I understand there is SublimeREPL which I can easily use to properly run python code in sublime text 3. However, it’s not sufficient for me. I want to run my python file on the cmd from sublime text 3.
There are many reasons for me. The biggest reason is that i need to test my python files often and I don’t want to cramp my sublime text workspace with thousands of tabs. There are several other reasons but at the moment I just want a solution. Almost everywhere on the internet it only talks about SublimeREPL, so I have been unable to find a solution.
I also understand I can use the cmd manually by going to the file directly and running it there, but its a pain in the back to keep switching to cmd and then to sublime text over and over again.
Therefore, I am looking for a neat solution where I can run my python file from sublime text 3 in cmd. Any help is deeply appreciated.
I am using python 3.7.3
1 Answer 1
The rule of thumb for build systems in Sublime Text is that if you can craft a command line that, when executed manually in the terminal/console, will give you the effect that you want (and that command doesn’t require interactive input), then you can turn it into a build system.
In this case, what you want to do is spawn a new cmd window and do something inside of it; the fact that you’re using Sublime is thus not interesting in the grand scheme of knowing how to do that, which might be why your search didn’t turn up any results.
However if you do that in an existing command prompt, the result is just to run the program in the current window; i.e. you’re telling cmd to run a command, but it’s still running in the current window, which is not what you want.
In order to run the program in a new window, you need to use the start command, which launches a new program. The general format of that would be something like this:
There are some general issues with this; the biggest one is that as soon as cmd finishes executing the command you give it, it quits. Similarly, Python also quits when the program is finished. The result of that is that as soon as your program is finished, the window immediately vanishes before you can see what it did.
In that case you need to modify the command you give to cmd to get it to also wait until you press a key.
All told, an example of that might look something like the following as a complete sublime-build file:
This is a version of the internal Python.sublime-build modified to extend the command as outlined above. In order for this to work, you need to be able to enter python at a terminal and have it launch the Python interpreter. If that’s not the case you need to adjust your PATH environment variable as appropriate.
If you’re using Python 3, you may need to replace python with python3 or similar in the command so that cmd knows what to execute.
We all know that nowadays Python is one of the most popular coding languages among all. While installing Python, one IDE named IDLE is also installed. Using the IDLE we can write and also run our programs. But we can also run python programs on CMD or command prompt as CMD is the default command-line interpreter on Windows.
But there’s a need to set up the environment variable in windows to use python on the command-line. Following are the steps to add Python Environment to Windows path:
Step 1: For setting up Python on CMD we must check whether Python is installed on your machine or not. For doing this go to the Windows search bar and search for python. If you find python in the result then you are good to go.
You can see Python3 is installed on my computer
If python is not installed on your computer, then it can be installed with How to install Python on Windows?.
Step 2: Now check whether python is already set up in Command Prompt or not. For doing this just open cmd and type python. If you see any python version then it is already setup.
You can see after typing python nothing happened. So, python is not set up on cmd yet.
Step 3: Now open the Windows search bar and search for “idle”. Without opening the app click on “Open file location”. If you didn’t get the option right click on the app and you will get it.
Now a file location will be opened on Windows explorer.
Step 4: Now right-click on “IDLE” and click on “open file location”
Click on “Open file location”
After opening the file location copy the path.
Copy the location
Step 5: Now go to the windows search bar and search for “Environment variables” and open it.
After opening the menu click on “Environment Variables”
Click on the “Environment Variables”
Now double click on the “path” in the “System Variables”
In the “Edit System Variable” menu click on “new”, then paste the file location you copied and click ok.
Now close the Environment menus by clicking ok and congratulation, we have set up the Command Prompt for python.
Step 6: Now check whether it works. Open Command Prompt and type “python” and hit enter. You will see a python version and now you can run your program there.
Источники информации:
- http://stackoverflow.com/questions/4621255/how-do-i-run-a-python-program-in-the-command-prompt-in-windows-7
- http://pythonru.com/osnovy/zapusk-python-i-python-skript-na-kompjutere
- http://stackoverflow.com/questions/58568205/how-to-run-a-python-file-script-from-sublime-text-3-on-cmd-in-windows-10
- http://www.geeksforgeeks.org/how-to-set-up-command-prompt-for-python-in-windows10/