Python открыть файл через консоль

Как открыть текстовый файл hello.py через командную строку )при установленном питоне)?

К сути, программированием решил заняться для себя, просто хобби, начать решил с Python, купил книгу Саммерфилда, установил питон 3.7 с ориг. сайты, галочку со средой поставил при установке, как и в книге, я создал в блокноте файл и назвал его hello.py, зашел в cmd(запускаю файл не в командной строке интерпретатора), переменные среды Path я указал, и саму папку питона и скрипты:
C:\Users\finni\AppData\Local\Programs\Python\Python37-32> C:\py5eg\python hello.py
«C:\py5eg\python» не является внутренней или внешней
командой, исполняемой программой или пакетным файлом.
Второй вариант из книги:
C:\py5eg>C:\Users\finni\AppData\Local\Programs\Python\Python37-32\python.exe hello.py
C:\Users\finni\AppData\Local\Programs\Python\Python37-32\python.exe: can’t open file ‘hello.py’: [Errno 2] No such file or directory
Я понимаю, что можно запустить интепретатор в cmd и работать так, но почему у меня не получается просто через cmd?

NeiroNx

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

deepblack

C:\Users\finni\AppData\Local\Programs\Python\Python37-32\python.exe C:\Users\finni\Desktop\hello.py

Источник

How to Open and Run Python Files in the Terminal

A Python file or script is written in the Python language and saved with a «.py» extension. In this article, we focus on how to interact with Python files. We will learn how to create and open Python files in the terminal. We will also demonstrate how to run Python files in the terminal and redirect the output of the script to a file.

Читайте также:  Python примеры программ input

A Python file may contain a few up to several thousand lines of code that perform one or more tasks. For instance, we may have a Python file that reads data files from different locations, performs some manipulation on them, and writes the resulting data file to another location.

However, how to write Python code or scripts is a separate topic. Thankfully, Python is an easy-to-learn language that is popular for its simplicity.

LearnPython.com takes it one step further and makes the Python learning experience smooth and efficient. It offers several well-organized courses and tracks. Furthermore, the interactive console of LearnPython.com allows for practicing, a must in learning a programming language.

If you are new to Python, start learning with Python Basics. Part 1. By completing this course, you learn concepts such as variables, lists, conditional statements, loops, and functions, which are fundamental topics for programming and software development.

Let’s go back to our main topic of working with Python files in the terminal. We will use the text editor Vim to create a Python file. Vim comes pre-installed on macOS, but there are many different alternatives to choose from such as Sublime and Atom.

How to Create Python Files in the Terminal

Let’s start with opening a terminal and creating a project directory. Then, we change the working directory to the project folder using the «cd» command.

open python files in terminal

We create a Python file by typing «vim» along with the file name. My Python file is called «today.py.» You may name yours anything you’d like. Make sure it ends with the extension «.py».

open python files in terminal

After typing this command, hit enter. Vim opens up the following screen:

open python files in terminal

This is an empty Python file. To modify it, we need to hit «i», the command for switching to the insert or edit mode. When you hit «i», you see the following screen, and you can insert text into the file.

open python files in terminal

This Python file performs a very simple task. As its name suggests, it prints today’s date when executed. There are many different ways of doing this simple task; here, we use the built-in datetime module of Python.

open python files in terminal

In this first line, we import the datetime module. Modules and libraries make development processes easier because we can import and use their functionalities right away. Python also has numerous third-party libraries created by an active open-source community. Here is a list of top Python libraries if you’d like to discover more.

The today method of the datetime module returns a timestamp that contains the current date and time. Since we only need the date, we may also use the date method. The str constructor converts the date object to a string. Finally, we print today’s date using an f-string.

Our script is complete now. To exit the edit mode, hit ESC. Do not close the terminal yet because the file has not been saved. The command to save the file and close the editor is «:wq». The «w» is for «write», meaning we are writing to the file «today.py». The «q» is for «quit».

open python files in terminal

Once you type the «:wq» command, hit enter. The editor closes, and you see the following screen.

open python files in terminal

The file «today.py» has been saved in the «project-1» directory.

How to Open Python Files in the Terminal

We can view the content of existing files with a text editor. Let’s see an example using the file we just created.

The command «vim today.py» opens this Python file in the terminal. This command is the same as the one used for creating the file. Since the text editor knows the file exists, it opens the file instead of creating a new one.

Type the command «vim today.py» in the terminal and hit enter. Any other text editor, such as Sublime and Atom, works similarly. Then, you see the following screen:

open python files in terminal

How to Run Python Files in the Terminal

We have learned how to create Python files and how to open Python files in the terminal to view their contents. How about executing the file to see what it does? We can run Python files in the terminal as well.

First, we need to make sure the current working directory is the one in which the file is located. We open a terminal and change the directory to «project-1» since the «today.py» file was saved in that directory.

The command to execute a Python file is «python» or «python3» depending on how Python is installed on your computer. We type that along with the name of the file to be executed.

open python files in terminal

As we see in the output above, our script prints today’s date in the terminal.

Python scripts may be executed with arguments. Let’s write another script that gives us the date that is n number of days from today. The value of n is determined using a command-line argument.

Let’s name this script «from_today.py».

open python files in terminal

The next step is to open the Python file in the terminal using the command «vim from_today.py» and write the script that performs the task. To use command-line arguments, we need the sys module.

open python files in terminal

Once you write the Python code above in the file «from_today.py», exit the edit mode and save it.

We can now execute the file. Let’s ask the script to find the date 10 days from now:

open python files in terminal

Great! We have managed to execute a Python script with a command-line argument.

In the examples we have seen so far, the output of the file is displayed in the terminal. Let’s say we also want to write the output of this script to another file. Every time it is executed, the output is recorded in a text file. This is a very useful practice for keeping logs.

We can create a text file using Vim as follows:

  1. Open a terminal window and change the directory to «project-1» using the command «cd project-1».
  2. Type «vim logs.txt» and hit enter.
  3. The Vim editor opens a file. Press «i» and then hit ESC.
  4. Finally, type «:wq» to save the file in the directory «project-1».

In our Python Basics. Part 2 course, you learn much more about how to work with text files. In addition, this course covers two fundamental data structures in Python: lists and dictionaries.

The next step is to modify the «today.py» file so that it writes its output to the «logs.txt» file when it is executed. In the same terminal window, we open the file «today.py» by typing «vim today.py» and hitting «Enter». After the file is opened, hit «i» to switch to the edit mode and modify the script as shown below:

open python files in terminal

The last two lines open the «logs.txt» file and then write the value of the variable today in it. The «\n» is for writing a new line, so every output is in a separate line. I have also made a small change in the second line. The output is a datetime now instead of just the date. After making these changes, hit ESC and then type «:wq» to save them.

To learn more about date and time in Python, take our Python Basics. Part 3 course. It also covers two other important data structures in Python: sets and tuples.

We are not done yet! Always test your code. I execute the file «today.py» a couple of times.

open python files in terminalI then check the content of the file «logs.txt» to see if the output has been written there. Let’s open the file now by typing the command «vim logs.txt». open python files in terminal

As we see in the screenshot above, the output has been written in the «logs.txt» file as well.

Create, Open, and Run Python Files in the Terminal

We have seen how to create, open, and run Python files in the terminal. The «today.py» file we created is essentially a Python program, even though it is just 5 lines of code. It imports a built-in Python module to create a date object, then prints the value of the object in the console and writes it to another file. Learn more about how to work with files and directories in Python in this article.

What we have done in this article is only a very small part of what you can do with Python. It is one of the most popular programming languages and is used in a variety of areas, such as data science, web development, and mobile game development. Python is a great choice for a career in one of these fields.

Start with the Learn Programming with Python track. It introduces you to the fundamentals of programming. You do not need to have any prior experience with IT. This track consists of 5 fully interactive Python courses, carefully organized and presented for beginners.

There is a high demand for people with Python skills. Once you get comfortable with Python, there will be lots of jobs waiting for you!

Источник

Как запустить файл Python с помощью Командной строки Windows

В создании этой статьи участвовала наша опытная команда редакторов и исследователей, которые проверили ее на точность и полноту.

Команда контент-менеджеров wikiHow тщательно следит за работой редакторов, чтобы гарантировать соответствие каждой статьи нашим высоким стандартам качества.

Количество просмотров этой статьи: 140 499.

Из этой статьи вы узнаете, как открыть файл Python при помощи встроенной Командной строки на компьютере под управлением Windows. В большинстве случаев это можно сделать без каких-либо проблем — главное, чтобы на вашем компьютере был установлен Python. Если вы установили старую версию Python или использовали пользовательские настройки в ходе установки, из-за которых команда «python» не была добавлена в список переменных «Path» на компьютере, вам придется добавить Python в список переменных «Path», чтобы иметь возможность запускать файл Python через командную строку.

Найдите путь к файлу Python

Изображение с названием Use Windows Command Prompt to Run a Python File Step 1

Изображение с названием Use Windows Command Prompt to Run a Python File Step 2

Изображение с названием Use Windows Command Prompt to Run a Python File Step 3

Изображение с названием Use Windows Command Prompt to Run a Python File Step 4

Изображение с названием Use Windows Command Prompt to Run a Python File Step 5

  • Чтобы скопировать расположение, его необходимо выделить (зажмите и перетащите указатель мыши по значению в строке «Расположение»), а затем нажать Ctrl + C .

Источник

Запуск файла Python из командной строки Windows

Обложка статьи

В этой статье мы рассмотрим, как запустить файл Python с помощью командной строки в Windows. Это поможет вам выполнять ваш код Python, не открывая его в интерпретаторе или редакторе кода. Давайте приступим!

Для запуска файла Python в командной строке, у вас должен быть установлен Python. Если вы до сих пор этого не сделали, то вы можете воспользоваться нашем руководством: Установка Python на Windows.

Как открыть командную строку Windows

Для начала нам необходимо открыть командную строку Windows. Это можно сделать зажав одновременно клавиши WIN + R, в открывшемся окне введите «cmd» и нажмите клавишу Enter.

Картинка

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

Как перейти в директорию с файлом Python

Для запуска файла Python нам необходимо перейти в командной строке в директорию, где находится данный файл.

Для этого вы можете использовать команду cd (change directory). Например, если ваш файл Python находится в директории «C:\my_python_files», вы можете ввести команду «cd C:\my_python_files». После этого вы будете находиться в этой директории и готовы к запуску файла Python.»

Если ваш файл Python находится на другом диске, то вам необходимо сначала сменить диск в командной строке. Для этого вы можете ввести название диска, например, «D:», и нажать Enter. Затем вы можете использовать команду «cd», как в примере выше.

Более подробно о команде «cd» вы можете узнать из нашей статьи.

Запуск файла Python

После того, как в командной строке вы перешли в директорию, где находится ваш файл, вы можете использовать команду ‘python .py’, чтобы запустить файл. Например, если ваш файл называется ‘hello_world.py’, вы можете ввести ‘python hello_world.py’, чтобы запустить этот файл. После чего файл будет исполнен.

Источник

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