Питон закрывает консоль сразу после выполнения как исправить

I am very new to python.. I used the code x = input(" Hey what is your name " ) print(" Hey, " + x) input(" press close to exit ") Because i have looked for this problem on internet and ...

I am very new to python.. I used the code

x = input(" Hey what is your name " )       
print(" Hey, " + x)  
input(" press close to exit ")

Because i have looked for this problem on internet and came to know that you have to put some dummy input line at the end to stop the command prompt from getting closed but m still facing the problem.. pls Help

I am using python 3.3

Martijn Pieters's user avatar

asked Jan 3, 2013 at 16:01

Aakash's user avatar

4

On windows, it’s the CMD console that closes, because the Python process exists at the end.

To prevent this, open the console first, then use the command line to run your script. Do this by right-clicking on the folder that contains the script, select Open console here and typing in python scriptname.py in the console.

The alternative is, as you’ve found out, to postpone the script ending by adding a input() call at the end. This allows the user of the script to choose when the script ends and the console closes.

answered Jan 3, 2013 at 16:05

Martijn Pieters's user avatar

Martijn PietersMartijn Pieters

1.0m284 gold badges3977 silver badges3300 bronze badges

16

That can be done with os module. Following is the simple code :

import os
os.system("pause")

This will generate a pause and will ask user to press any key to continue.

[edit: The above method works well for windows os. It seems to give problem with mac (as pointed by ihue, in comments). The thing is that «os» library is operating system specific and some commands might not work with one operating system like they work in another one.]

answered Aug 5, 2013 at 4:56

Blaze's user avatar

BlazeBlaze

1,5922 gold badges21 silver badges20 bronze badges

3

For Windows Environments:

If you don’t want to go to the command prompt (or work in an environment where command prompt is restricted), I think the following solution is gooThe solution I use is to create a bat file.

Use notepad to create a text file. In the file the contents will look something like:

my_python_program.py
pause

Then save the file as «my_python_program.bat» — DO NOT FORGET TO SELECT «All Files!

When you run the bat file it will run the python program and pause at the end to allow you to read the output. Then if you press any key it will close the window.

answered Oct 13, 2019 at 15:17

Inter Mob's user avatar

Just Add Simple input At The End Of Your Program it Worked For Me

input()

Try it And It Will Work Correctly

answered May 2, 2021 at 17:12

Mohammed Ouedrhiri's user avatar

Try this,

import sys

status='idlelib' in sys.modules

# Put this segment at the end of code
if status==False:
    input()

This will only stop console window, not the IDLE.

answered Dec 25, 2020 at 14:41

yourson's user avatar

yoursonyourson

781 gold badge4 silver badges18 bronze badges

0

I couldn’t find anywhere on the internet a true non-script specific, double click and the window doesn’t close solution. I guess I’m too lazy to drag and drop or type when I don’t need to so after some experimentation I came up with a solution.

The basic idea is to reassociate .py files so they run a separate initial script before running the intended script. The initial script launches a new command prompt window with the /k parameter which keeps the command prompt open after completion and runs your intended script in the new window.

Maybe there are good reasons not to do this, those with more knowledge please comment if so, but I figure if I run into any it is easy to revert back if needed. One possibly undesirable side effect is dragging and dropping or typing and running from a command prompt now opens a second command prompt rather than running in the command prompt you dragged or typed in.

Now, for the implementation, I call the initial python script python_cmd_k.pyw. I’m using Python 3.7. The code required may differ for other versions. Change the path C:Python37python.exe to the location of your python installation. Associate .pyw files to pythonw.exe (not python.exe) through Windows if they aren’t already.

import subprocess
import sys

#Run a python script in a new command prompt that does not close
command = 'start cmd /k C:Python37python.exe "' + sys.argv[1] + '"'
subprocess.run(command, shell=True)

This runs every time you double click any .py script and launches a new command prompt to run the script you double clicked. Running through pythonw.exe suppresses the command prompt window when this initial script runs. Otherwise if you run it through python.exe an annoying blink of a command prompt appear as a result of the first window showing briefly each time. The intended script displays because the code in the initial script above runs the intended script with python.exe.

Now associate .py files with python.exe (not pythonw.exe) through Windows if they are not already and edit the registry entry for this association (Disclaimer: Always back up your registry before editing it if you are unsure of what you are doing). I do not know if there are different paths in the registry for file association for different versions of Windows but for me it is at:

HKEY_CURRENT_USERSoftwareClassesApplicationspython.exeshellopencommand

Change the data to the pythonw.exe path (not python.exe) and add the path to the ptyhon script above and «%1» as arguments («%1» passes the full path of the doubled clicked file). For example if pythonw.exe and python_cmd_k.pyw are at C:Python37 then:

"C:Python37pythonw.exe" "C:Python37python_cmd_k.pyw" "%1"

It is not necessary to put python_cmd_k.pyw in the same directory as pythonw.exe as long as you provide the correct path for both. You can put these in .reg files for easy switching back and forth between using the script and the default behavior. Change the paths as needed in the examples below (location in the registry, your installation of python, the location you put your python_cmd_k.pyw script).

With ptyhon_cmd_k.pyw (change paths as needed):

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USERSoftwareClassesApplicationspython.exeshellopencommand]
@=""C:\Python37\pythonw.exe" "C:\Python37\python_cmd_k.pyw" "%1""

Default version (change paths as needed):

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USERSoftwareClassesApplicationspython.exeshellopencommand]
@=""C:\Python37\python.exe" "%1""

I couldn’t find anywhere on the internet a true non-script specific, double click and the window doesn’t close solution. I guess I’m too lazy to drag and drop or type when I don’t need to so after some experimentation I came up with a solution.

The basic idea is to reassociate .py files so they run a separate initial script before running the intended script. The initial script launches a new command prompt window with the /k parameter which keeps the command prompt open after completion and runs your intended script in the new window.

Maybe there are good reasons not to do this, those with more knowledge please comment if so, but I figure if I run into any it is easy to revert back if needed. One possibly undesirable side effect is dragging and dropping or typing and running from a command prompt now opens a second command prompt rather than running in the command prompt you dragged or typed in.

Now, for the implementation, I call the initial python script python_cmd_k.pyw. I’m using Python 3.7. The code required may differ for other versions. Change the path C:Python37python.exe to the location of your python installation. Associate .pyw files to pythonw.exe (not python.exe) through Windows if they aren’t already.

import subprocess
import sys

#Run a python script in a new command prompt that does not close
command = 'start cmd /k C:Python37python.exe "' + sys.argv[1] + '"'
subprocess.run(command, shell=True)

This runs every time you double click any .py script and launches a new command prompt to run the script you double clicked. Running through pythonw.exe suppresses the command prompt window when this initial script runs. Otherwise if you run it through python.exe an annoying blink of a command prompt appear as a result of the first window showing briefly each time. The intended script displays because the code in the initial script above runs the intended script with python.exe.

Now associate .py files with python.exe (not pythonw.exe) through Windows if they are not already and edit the registry entry for this association (Disclaimer: Always back up your registry before editing it if you are unsure of what you are doing). I do not know if there are different paths in the registry for file association for different versions of Windows but for me it is at:

HKEY_CURRENT_USERSoftwareClassesApplicationspython.exeshellopencommand

Change the data to the pythonw.exe path (not python.exe) and add the path to the ptyhon script above and «%1» as arguments («%1» passes the full path of the doubled clicked file). For example if pythonw.exe and python_cmd_k.pyw are at C:Python37 then:

"C:Python37pythonw.exe" "C:Python37python_cmd_k.pyw" "%1"

It is not necessary to put python_cmd_k.pyw in the same directory as pythonw.exe as long as you provide the correct path for both. You can put these in .reg files for easy switching back and forth between using the script and the default behavior. Change the paths as needed in the examples below (location in the registry, your installation of python, the location you put your python_cmd_k.pyw script).

With ptyhon_cmd_k.pyw (change paths as needed):

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USERSoftwareClassesApplicationspython.exeshellopencommand]
@=""C:\Python37\pythonw.exe" "C:\Python37\python_cmd_k.pyw" "%1""

Default version (change paths as needed):

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USERSoftwareClassesApplicationspython.exeshellopencommand]
@=""C:\Python37\python.exe" "%1""

I am very new to python.. I used the code

x = input(" Hey what is your name " )       
print(" Hey, " + x)  
input(" press close to exit ")

Because i have looked for this problem on internet and came to know that you have to put some dummy input line at the end to stop the command prompt from getting closed but m still facing the problem.. pls Help

I am using python 3.3

Martijn Pieters's user avatar

asked Jan 3, 2013 at 16:01

Aakash's user avatar

4

On windows, it’s the CMD console that closes, because the Python process exists at the end.

To prevent this, open the console first, then use the command line to run your script. Do this by right-clicking on the folder that contains the script, select Open console here and typing in python scriptname.py in the console.

The alternative is, as you’ve found out, to postpone the script ending by adding a input() call at the end. This allows the user of the script to choose when the script ends and the console closes.

answered Jan 3, 2013 at 16:05

Martijn Pieters's user avatar

Martijn PietersMartijn Pieters

1.0m284 gold badges3977 silver badges3300 bronze badges

16

That can be done with os module. Following is the simple code :

import os
os.system("pause")

This will generate a pause and will ask user to press any key to continue.

[edit: The above method works well for windows os. It seems to give problem with mac (as pointed by ihue, in comments). The thing is that «os» library is operating system specific and some commands might not work with one operating system like they work in another one.]

answered Aug 5, 2013 at 4:56

Blaze's user avatar

BlazeBlaze

1,5922 gold badges21 silver badges20 bronze badges

3

For Windows Environments:

If you don’t want to go to the command prompt (or work in an environment where command prompt is restricted), I think the following solution is gooThe solution I use is to create a bat file.

Use notepad to create a text file. In the file the contents will look something like:

my_python_program.py
pause

Then save the file as «my_python_program.bat» — DO NOT FORGET TO SELECT «All Files!

When you run the bat file it will run the python program and pause at the end to allow you to read the output. Then if you press any key it will close the window.

answered Oct 13, 2019 at 15:17

Inter Mob's user avatar

Just Add Simple input At The End Of Your Program it Worked For Me

input()

Try it And It Will Work Correctly

answered May 2, 2021 at 17:12

Mohammed Ouedrhiri's user avatar

Try this,

import sys

status='idlelib' in sys.modules

# Put this segment at the end of code
if status==False:
    input()

This will only stop console window, not the IDLE.

answered Dec 25, 2020 at 14:41

yourson's user avatar

yoursonyourson

781 gold badge4 silver badges18 bronze badges

0

Уведомления

  • Начало
  • » Python для новичков
  • » Python: консоль исчезает сразу после выполнения

#1 Ноя. 20, 2011 15:12:44

Python: консоль исчезает сразу после выполнения

Пишу небольшие консольные программы на Python’e. Но после вывода данных при помощи print консоль сразу закрывается, и я даже неуспеваю увидеть результат. Что дописать в скрипте чтоб консоль не закрывалась, или хотябы закрывалась через некоторое время?

Офлайн

  • Пожаловаться

#2 Ноя. 20, 2011 15:22:38

Python: консоль исчезает сразу после выполнения

Офлайн

  • Пожаловаться

#3 Ноя. 20, 2011 15:38:07

Python: консоль исчезает сразу после выполнения

Punk_Joker
Пишу небольшие консольные программы на Python’e. Но после вывода данных при помощи print консоль сразу закрывается, и я даже неуспеваю увидеть результат. Что дописать в скрипте чтоб консоль не закрывалась, или хотябы закрывалась через некоторое время?

Просто открой консоль (CMD в Windows или Terminal в UNIX) в той папке, где у тебя есть скрипт.
Напиши в консоли python <название скрипта>.py. И после выполения программы консоль никуда не пропадёт.

Офлайн

  • Пожаловаться

#4 Ноя. 20, 2011 23:24:19

Python: консоль исчезает сразу после выполнения

Spectral
Просто открой консоль (CMD в Windows или Terminal в UNIX) в той папке, где у тебя есть скрипт.
Напиши в консоли python <название скрипта>.py. И после выполения программы консоль никуда не пропадёт.

можно создать ярлык для cmd.exe, удалив в его свойствах путь к system32
тогда он будет открывать в той папке, где находится
иногда удобнее raw_input()/input()

tags: cmd.exe

Отредактировано py.user.next (Сен. 8, 2022 01:16:02)

Офлайн

  • Пожаловаться

#5 Дек. 2, 2011 20:57:31

Python: консоль исчезает сразу после выполнения

Punk_Joker
Пишу небольшие консольные программы на Python’e. Но после вывода данных при помощи print консоль сразу закрывается, и я даже неуспеваю увидеть результат. Что дописать в скрипте чтоб консоль не закрывалась, или хотябы закрывалась через некоторое время?

ну если приложение совсем уж простое то можно помимо raw_input() сделать например так:

cod@coder-desktop ~ $ nano ololo.py

cod@coder-desktop ~ $ python ololo.py > olololo
cod@coder-desktop ~ $ cat ololo
ololo
cod@coder-desktop ~ $

ну это как вариант конечно =) ну и в том случае если у тебя *nix
но raw_input() все= както прощще =)

Офлайн

  • Пожаловаться

#6 Дек. 3, 2011 09:31:29

Python: консоль исчезает сразу после выполнения

ololo не поможет, вопрос касается уиндоус (когда щёлкаешь на скрипте, запуская его)
в лине то такой проблемы нет

Отредактировано (Дек. 3, 2011 09:32:56)

Офлайн

  • Пожаловаться

#7 Июль 13, 2021 16:48:09

Python: консоль исчезает сразу после выполнения

Здравствуйте!
Начала изучать Питон. Сделала первую программку, файл.ру
Хочу открыть этот файл, но он моментально закрывается. Можно ли сделать, чтобы этот файл не закрывался?

Прикреплённый файлы:
attachment Первая программа для Владика..py (411 байт)

Офлайн

  • Пожаловаться

#8 Июль 19, 2021 21:17:19

Python: консоль исчезает сразу после выполнения

я решаю эту проблему как мне кажется колхозным но крайне действенным методом
если мне нужно чтоб консоль осталась открыта я в конце добавляю

и она не закроется пока ты что нибудь не введешь

Офлайн

  • Пожаловаться

  • Начало
  • » Python для новичков
  • » Python: консоль исчезает сразу после выполнения

Is there any way I can stop python.exe from closing immediately after it completes? It closes faster than I can read the output.

Here is the program:

width = float(input("Enter the width: "))
height = float(input("Enter the height: "))
area = width * height
print("The area is", area, "square units.")

Kevin's user avatar

Kevin

74.1k12 gold badges128 silver badges163 bronze badges

asked Aug 28, 2010 at 17:53

Clinton's user avatar

1

You can’t — globally, i.e. for every python program. And this is a good thing — Python is great for scripting (automating stuff), and scripts should be able to run without any user interaction at all.

However, you can always ask for input at the end of your program, effectively keeping the program alive until you press return. Use input("prompt: ") in Python 3 (or raw_input("promt: ") in Python 2). Or get used to running your programs from the command line (i.e. python mine.py), the program will exit but its output remains visible.

answered Aug 28, 2010 at 18:01

0

Just declare a variable like k or m or any other you want, now just add this piece of code at the end of your program

k=input("press close to exit") 

Here I just assumed k as variable to pause the program, you can use any variable you like.

Alexis Pigeon's user avatar

answered Oct 21, 2012 at 15:27

kranthi kumar's user avatar

2

For Windows Environments:

If you don’t want to go to the command prompt (or work in an environment where command prompt is restricted), I think the following solution is better than inserting code into python that asks you to press any key — because if the program crashes before it reaches that point, the window closes and you lose the crash info. The solution I use is to create a bat file.

Use notepad to create a text file. In the file the contents will look something like:

my_python_program.py
pause

Then save the file as «my_python_program.bat»

When you run the bat file it will run the python program and pause at the end to allow you to read the output. Then if you press any key it will close the window.

answered May 22, 2014 at 6:21

sarasimple's user avatar

sarasimplesarasimple

3471 gold badge3 silver badges11 bronze badges

1

Auxiliary answer

Manoj Govindan’s answer is correct but I saw that comment:

Run it from the terminal.

And got to thinking about why this is so not obvious to windows users and realized it’s because CMD.EXE is such a poor excuse for a shell that it should start with:

Windows command interpreter copyright 1999 Microsoft
Mein Gott!! Whatever you do, don’t use this!!
C:>

Which leads me to point at https://stackoverflow.com/questions/913912/bash-shell-for-windows

Community's user avatar

answered Aug 28, 2010 at 18:22

msw's user avatar

mswmsw

42.4k9 gold badges85 silver badges112 bronze badges

4

It looks like you are running something in Windows by double clicking on it. This will execute the program in a new window and close the window when it terminates. No wonder you cannot read the output.

A better way to do this would be to switch to the command prompt. Navigate (cd) to the directory where the program is located and then call it using python. Something like this:

C:> cd C:my_programs
C:my_programs> python area.py

Replace my_programs with the actual location of your program and area.py with the name of your python file.

answered Aug 28, 2010 at 17:59

Manoj Govindan's user avatar

Manoj GovindanManoj Govindan

70.8k21 gold badges132 silver badges140 bronze badges

4

Python files are executables, which means that you can run them directly from command prompt(assuming you have windows). You should be able to just enter in the directory, and then run the program.
Also, (assuming you have python 3), you can write:

input("Press enter to close program")

and you can just press enter when you’ve read your results.

answered Jan 2, 2014 at 4:06

Jester's user avatar

In windows, if Python is installed into the default directory (For me it is):

cd C:Python27

You then proceed to type

"python.exe "[FULLPATH][name].py" 

to run your Python script in Command Prompt

Harry's user avatar

Harry

86.2k25 gold badges195 silver badges208 bronze badges

answered Oct 17, 2013 at 6:18

usr72927328's user avatar

0

Is there any way I can stop python.exe from closing immediately after it completes? It closes faster than I can read the output.

Here is the program:

width = float(input("Enter the width: "))
height = float(input("Enter the height: "))
area = width * height
print("The area is", area, "square units.")

Kevin's user avatar

Kevin

74.1k12 gold badges128 silver badges163 bronze badges

asked Aug 28, 2010 at 17:53

Clinton's user avatar

1

You can’t — globally, i.e. for every python program. And this is a good thing — Python is great for scripting (automating stuff), and scripts should be able to run without any user interaction at all.

However, you can always ask for input at the end of your program, effectively keeping the program alive until you press return. Use input("prompt: ") in Python 3 (or raw_input("promt: ") in Python 2). Or get used to running your programs from the command line (i.e. python mine.py), the program will exit but its output remains visible.

answered Aug 28, 2010 at 18:01

0

Just declare a variable like k or m or any other you want, now just add this piece of code at the end of your program

k=input("press close to exit") 

Here I just assumed k as variable to pause the program, you can use any variable you like.

Alexis Pigeon's user avatar

answered Oct 21, 2012 at 15:27

kranthi kumar's user avatar

2

For Windows Environments:

If you don’t want to go to the command prompt (or work in an environment where command prompt is restricted), I think the following solution is better than inserting code into python that asks you to press any key — because if the program crashes before it reaches that point, the window closes and you lose the crash info. The solution I use is to create a bat file.

Use notepad to create a text file. In the file the contents will look something like:

my_python_program.py
pause

Then save the file as «my_python_program.bat»

When you run the bat file it will run the python program and pause at the end to allow you to read the output. Then if you press any key it will close the window.

answered May 22, 2014 at 6:21

sarasimple's user avatar

sarasimplesarasimple

3471 gold badge3 silver badges11 bronze badges

1

Auxiliary answer

Manoj Govindan’s answer is correct but I saw that comment:

Run it from the terminal.

And got to thinking about why this is so not obvious to windows users and realized it’s because CMD.EXE is such a poor excuse for a shell that it should start with:

Windows command interpreter copyright 1999 Microsoft
Mein Gott!! Whatever you do, don’t use this!!
C:>

Which leads me to point at https://stackoverflow.com/questions/913912/bash-shell-for-windows

Community's user avatar

answered Aug 28, 2010 at 18:22

msw's user avatar

mswmsw

42.4k9 gold badges85 silver badges112 bronze badges

4

It looks like you are running something in Windows by double clicking on it. This will execute the program in a new window and close the window when it terminates. No wonder you cannot read the output.

A better way to do this would be to switch to the command prompt. Navigate (cd) to the directory where the program is located and then call it using python. Something like this:

C:> cd C:my_programs
C:my_programs> python area.py

Replace my_programs with the actual location of your program and area.py with the name of your python file.

answered Aug 28, 2010 at 17:59

Manoj Govindan's user avatar

Manoj GovindanManoj Govindan

70.8k21 gold badges132 silver badges140 bronze badges

4

Python files are executables, which means that you can run them directly from command prompt(assuming you have windows). You should be able to just enter in the directory, and then run the program.
Also, (assuming you have python 3), you can write:

input("Press enter to close program")

and you can just press enter when you’ve read your results.

answered Jan 2, 2014 at 4:06

Jester's user avatar

In windows, if Python is installed into the default directory (For me it is):

cd C:Python27

You then proceed to type

"python.exe "[FULLPATH][name].py" 

to run your Python script in Command Prompt

Harry's user avatar

Harry

86.2k25 gold badges195 silver badges208 bronze badges

answered Oct 17, 2013 at 6:18

usr72927328's user avatar

0

как сделать, чтобы моя консоль в питоне не закрывалась?

Я делаю приложение на питоне из Windows. Когда я запускаю его в консоли, он останавливается, показывает ошибку и закрывается. Я не вижу ошибку, потому что она слишком быстрая, и я не могу ее прочитать. Я редактирую код с помощью IDLE (программа, которая пришла с python, когда я ее установил), и когда я запускаю ее с оболочкой python, ошибок нет. Я бы запускал его из IDLE, но когда я использую консоль, у него больше возможностей.

Я не знаю, почему это происходит. Мне требуется ваша помощь.

Запустите программу из командной строки Windows. Это не закроется автоматически, когда программа завершит работу.

Если вы запустите программу, дважды щелкнув на .py значок файла, то Windows закроет окно, когда ваша программа завершит работу (независимо от того, была ли она успешной или нет).

ответ дан 09 авг.

Создайте текстовый файл в каталоге программы, т.е. там, где находится ваш скрипт. Измените расширение на .bat например text.bat. Затем отредактируйте текстовый файл и напишите:

python main.exe
pause

Теперь вы можете запустить программу, не вводя ее в командную консоль, дважды щелкнув файл bat, и окно консоли не закрывается.

Создан 29 ноя.

Запускаем программу с уже открытого терминала. Откройте командную строку и введите:

python myscript.py

Для этого вам нужен исполняемый файл python на вашем пути. Просто проверьте, как редактировать переменные среды в окнах, и добавьте C:PYTHON26 (или любой другой каталог, в который вы установили python). Когда программа завершится, она вернет вас к приглашению Windows CMD вместо закрытия окна. Добавить код для ожидания в конце вашего скрипта. Добавление…

raw_input()

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

ответ дан 09 авг.

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками

windows
python-2.7

or задайте свой вопрос.

Вопрос:

Я только что начал колледж, и мы будем использовать python. Мы действительно ничего не сделали, поэтому я загрузил программу и выполнил некоторые команды печати, и что она.

Когда я запускаю свой .py файл (команда print), он сразу же закрывается после появления. Я понимаю, почему он это делает – он дал результат, поэтому он сделал то, что ему нужно сделать, но я также понимаю, что вы можете остановить это.

Я просмотрел этот веб-сайт, и ни одно из решений, предоставленных этому вопросу, не работало, либо я их не понимал.

Есть ли простая команда, которую я могу внести в редактор IDLE, который заставит программу приостановиться или что-то еще? Я пробовал input("prompt: "), как предложил кто-то, и это не имело никакого значения.

Если для этого нет команды, есть ли способ изменить настройки на компьютере, чтобы программы не закрывались автоматически?

Ответ №1

В Python 3 добавьте следующее в конец вашего кода:

input('Press ENTER to exit')

Это заставит программу ждать ввода пользователя, нажав ENTER, заставляя программу закончить.

Вы можете дважды щелкнуть по файлу script.py в Windows таким образом.

Ответ №2

Откройте командную строку cmd и запустите команды Python.
(в Windows идут запускать или искать и набирать cmd)
Он должен выглядеть следующим образом:

python yourprogram.py

Это приведет к выполнению вашего кода в cmd, и он останется открытым.
Однако, чтобы использовать команду python, Python должен быть правильно установлен, поэтому cmd распознает его как команду. Проверьте правильность установки и регистрации переменных для вашей ОС, если этого не произойдет

Ответ №3

Единственное, что сработало для меня – аргумент командной строки.

Просто поместите весь свой код python внутри .py файла, а затем запустите следующую команду:

python -i script.py

Это означает, что если вы установите переменную -i и запустите свой модуль, тогда python не выйдет из SystemExit.
Подробнее читайте в этой ссылке.

Ответ №4

Запустите команду, используя командную строку Windows из основного источника библиотеки Python.
Пример.

C:Python27python.exe directoryToFileyourprogram.py

Ответ №5

Если вам просто нужна задержка

from time import *

sleep(20)

Ответ №6

В Python 2.7 добавление этого в конец моего файла py (if __name__ == '__main__':) работает:

closeInput = raw_input("Press ENTER to exit")
print "Closing..."

Ответ №7

В зависимости от того, для чего я его использую, или если я делаю то, что другие будут использовать, я обычно просто input("Do eighteen backflips to continue"), если он только для меня, если другие будут использовать, я просто создаю пакетный файл и приостанавливаю после

cd '/file/path/here'
python yourfile.py
pause

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

python '/path/to/file/yourfile.py'
pause

Ответ №8

Я думаю, что я слишком поздно, чтобы ответить на этот вопрос, но в любом случае ничего не происходит.

Я уже сталкивался с той же проблемой, и я думаю, что есть два альтернативных решения, которые вы можете выбрать.

  • с помощью sleep (_someime)

from time import *
sleep(10)

  1. с помощью приглашения (обратите внимание, что я использую python 2.7)

exit_now = raw_input("Do you like to exit now (Y)es (N)o ? ")'

if exit_now.lower() = 'n'

//more processing here

В качестве альтернативы вы можете использовать гибрид этих двух методов, где вы можете запросить сообщение и использовать сон (когда-то), чтобы задержать закрытие окна. выбор за вами.

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

Ответ №9

Ну, у меня такая же проблема,
Он решается добавлением переменной среды.

Добавить системные переменные в окне

Имя: PYTHONPATH

Значение: C:Python27;

Ваш путь к Python.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Питон деление на ноль ошибка
  • Питон memory error
  • Пжд камаз 6520 коды ошибок
  • Пжд камаз 5490 коды ошибок
  • Пжд газовый камаз ошибки

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии