Errno 2 no such file or directory python linux

Python Script for Traceroute and printing the output in file shows error( OSError: [Errno 2] No such file or directory) in Linux Mint

I am trying to perform traceroute on google.com using python script and write the output to a file ie output.txt If I directly use subprocess.call(‘traceroute’,’google.com’) it works perfectly fine and the output gets printed on the screen. Since I want to get the output in a file, I am using subprocess.Popen([«tracert», ‘-w’, ‘100’, hostname],stdout=subprocess.PIPE, stderr=subprocess.STDOUT) and then writing the pipe data to file. However I get an error in this line i.e. OSError: [Errno 2] No such file or directory Code :

import urllib import time import datetime, threading from bs4 import BeautifulSoup import urllib2 import subprocess import socket fp2=open("output.txt",'w') #This function will be executed after every x minutes def TraceRoute(): hostname="google.com" fp2.write(hostname+" : ") print(hostname) #subprocess.call(['traceroute',hostname]) traceroute = subprocess.Popen(["tracert", '-w', '100', hostname],stdout=subprocess.PIPE, stderr=subprocess.STDOUT) while (True): hop = traceroute.stdout.readline() if not hop: break print '-->',hop fp2.write( hop ) threading.Timer(60*50, TraceRoute).start() #Ensures periodic execution of TraceRoute( ) x=60*50 seconds TraceRoute() 

Error : Traceback (most recent call last): File «./scr3.py», line 87, in TraceRoute() File «./scr3.py», line 76, in TraceRoute traceroute = subprocess.Popen([«tracert», ‘-w’, ‘100’, hostname],stdout=subprocess.PIPE, stderr=subprocess.STDOUT) File «/usr/lib/python2.7/subprocess.py», line 710, in init errread, errwrite) File «/usr/lib/python2.7/subprocess.py», line 1327, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory How to resolve this ? I am stuck on this since forever. Please help

Источник

Errno 2 no such file or directory python linux

Last updated: Feb 17, 2023
Reading time · 7 min

banner

# FileNotFoundError: [Errno 2] No such file or directory

The most common causes of the «FileNotFoundError: [Errno 2] No such file or directory» error are:

  1. Trying to open a file that doesn’t exist in the specified location.
  2. Misspelling the name of the file or a path component.
  3. Forgetting to specify the extension of the file. Note that Windows doesn’t display file extensions.

To solve the error, move the file to the directory where the Python script is located if using a local path, or use an absolute path.

filenotfounderror no such file or directory

Here is an example of how the error occurs.

Copied!
# ⛔️ FileNotFoundError: [Errno 2] No such file or directory: 'example-file.txt' with open('example-file.txt', 'r', encoding='utf-8') as f: lines = f.readlines() print(lines)

We tried to open a file called example-file.txt and it wasn’t found in the specified directory.

Читайте также:  How to unlock file in linux

This is a relative path, so Python looks for example-file.txt in the same directory as the Python script ( main.py ) in the example.

Copied!
# 👇️ relative path (the file has to be in the same directory) example.txt # 👇️ absolute path (Windows) 'C:\Users\Alice\Desktop\my-file.txt' # 👇️ absolute path (macOS or Linux) '/home/alice/Desktop/my-file.txt'

An absolute path is a complete path that points to the file (including the extension).

Note that Windows doesn’t display file extensions.

# Move the file to the same directory as your Python script

One way to solve the error is to move the file to the same directory as the Python script.

You can use the following 3 lines to print the current working directory (of your Python script) if you don’t know it.

Copied!
import os current_directory = os.getcwd() # 👇️ /home/borislav/Desktop/bobbyhadz_python print(current_directory)

For example, if you have a Python script called main.py , you would move the example.txt file right next to the main.py file.

Copied!
with open('example.txt', 'r', encoding='utf-8') as f: lines = f.readlines() print(lines)

The code sample assumes that you have an example.txt file in the same directory as the main.py file.

move file next to your python script

# Specifying an absolute path to the file

Alternatively, you can specify an absolute path to the file in the call to the open() function.

An absolute file that points to the file might look something like the following (depending on your operating system).

Copied!
# 👇️ on macOS or Linux my_str = r'/home/alice/Desktop/my-file.txt' # 👇️ on Windows my_str_2 = r'C:\Users\Alice\Desktop\my-file.txt'

Here is a complete example that uses an absolute path to open a file.

Copied!
absolute_path = r'/home/borislav/Desktop/bobbyhadz_python/example.txt' with open(absolute_path, 'r', encoding='utf-8') as f: lines = f.readlines() print(lines)

using an absolute path to a file

Make sure to specify the entire path to the file, including the extension.

On most operating systems, you can find the absolute path to a file by:

find absolute path to file

The path that is shown will likely not include the name of the file, but will point to the directory that contains the file.

Make sure to specify the name of the file and the extension at the end.

You can also open the file in finder and look at the path.

find path to file in finder

# Make sure to use a raw string if the path contains backslashes

If your path contains backslashes, e.g. ‘C:\Users\Alice\Desktop\my-file.txt’ , prefix the string with r to mark it as a raw string.

Copied!
my_path = r'C:\Users\Alice\Desktop\my-file.txt'

Backslashes are used as escape characters (e.g. \n or \t ) in Python, so by prefixing the string with an r , we treat backslashes as literal characters.

# Using a relative path to open the file

You can also use a relative path, even if the file is not located in the same directory as your Python script.

Assuming that you have the following folder structure.

Copied!
my_project/ main.py nested_folder/ example.txt

You can open the example.txt file from your main.py script as follows.

Copied!
with open(r'nested_dir/example.txt', 'r', encoding='utf-8') as f: lines = f.readlines() print(lines)

We first navigate to the nested_dir directory and then open the file.

Читайте также:  Все linux дистрибутивы 2020

If your file is located one or more directories up you have to prefix the path with ../ .

For example, assume that you have the following folder structure.

Copied!
Desktop/ my_project/ main.py example.txt

To open the example.txt file, navigate one directory up.

Copied!
with open(r'../example.txt', 'r', encoding='utf-8') as f: lines = f.readlines() print(lines)

The same syntax can be used to open a file that is located two directories up, e.g. ../../example.txt .

# Checking if the specified file exists before opening it

You can use the os module to print the current working directory and its contents.

Copied!
import os current_directory = os.getcwd() # 👇️ /home/borislav/Desktop/bobbyhadz_python print(current_directory) contents = os.listdir(current_directory) print(contents) # 👉️ ['main.py', 'example.py', . ] # 👇️ check if file in current directory print('example-file.txt' in contents) # 👉️ False

The os.getcwd method returns a string that represents the current working directory.

The os.listdir method returns a list that contains the names of the entries in the directory of the specified path.

The code sample prints the contents of the current working directory.

If you don’t see the file you are trying to open in the list, you shouldn’t try to open the file with a relative path (e.g. example.txt ).

Instead, you should use an absolute path (e.g. r’C:\Users\Alice\Desktop\my-file.txt’ ).

We used the in operator to check if a file with the specified name exists.

# Creating a file with the specified name if it doesn’t exist

You can use this approach to create a file with the specified name if it doesn’t already exist.

Copied!
import os current_directory = os.getcwd() contents = os.listdir(current_directory) filename = 'example.txt' if filename in contents: with open(filename, 'r', encoding='utf-8') as f: lines = f.readlines() print(lines) else: with open(filename, 'w', encoding='utf-8') as my_file: my_file.write('first line' + '\n') my_file.write('second line' + '\n') my_file.write('third line' + '\n')

We used the in operator to check if the file exists.

If it doesn’t exist, the else block runs where we create a file with the same name, adding 3 lines to it.

If you need to create the file name using variables, check out the following article.

# Make sure you have specified the correct filename

Make sure a file with the specified name exists and you haven’t misspelled the file’s name.

The name of the file shouldn’t contain any special characters, e.g. backslashes \ , forward slashes / or spaces.

If you need to generate unique file names, click on the following article.

# Changing to the directory that contains the file

An alternative solution is to change to the directory that contains the file you are trying to open using the os.chdir() method.

Copied!
import os dir_containing_file = r'/home/borislav/Desktop/bobbyhadz_python' # 👇️ change to the directory containing the file os.chdir(dir_containing_file) file_name = 'example.txt' with open(file_name, 'r', encoding='utf-8') as f: lines = f.readlines() print(lines)

The os.chdir method allows us to change the current working directory to the specified path.

Читайте также:  Linux файл с портами

Notice that I passed an absolute path to the method.

The example above assumes that there is an example.txt file in the /home/borislav/Desktop/bobbyhadz_python directory.

Once we use the os.chdir() method to change to the directory that contains the file, we can pass the filename directory to the open() function.

# Things to node when debugging

Make sure to specify the extension of the file. Note that Windows doesn’t display file extensions.

If your path contains backslashes, make sure to prefix it with an r to mark it as a raw string.

Copied!
my_path = r'C:\Users\Alice\Desktop\my-file.txt' print(my_path) # 👉️ C:\Users\Alice\Desktop\my-file.txt

Источник

Popen error: «[Errno 2] No such file or directory» when calling shell function

Maybe python is not on the PATH environment variable when your script runs. Try setting the full path to python, i.e. /usr/bin/python .

Can you explain what you’re trying to accomplish? I suspect that the child shell you’re launching with subprocess hasn’t «sourced» the virtualenv activation script, and it’s not inherited from the parent Python process (assuming that’s where you’re running it from).

5 Answers 5

Try add an extra parameter shell=True to the Popen call.

@YMomb: deactivate is a shell function. To run it, you need a shell. Though it is pointless to try to run it in a new shell (the new shell probably won’t have it defined until venv/bin/activate is called and the child normally can’t modify its parent environment anyway if OP hopes to deactivate the current virtualenv set in the parent shell. It is the same reason why subprocess.call(‘cd’) raises «No such file or directory» and it can be fixed using shell=True and it would be equally pointless.See Why is cd not a program?

It didn’t work for me. The same script is working fine when executed on shell, but gives error on subprocess. The error is : » python3: can’t open file ‘$SDE/install/lib/python3.6/site-packages/p4testutils/bf_switchd_dev_status.py’: [Errno 2] No such file or directory » What may be the issue?

Just a note. shell=True was likely the correct solution to the o.p., since they did not make the following mistake, but you can also get the «No such file or directory» error if you do not split up your executable from its arguments.

import subprocess as sp, shlex sp.Popen(['echo 1']) # FAILS with "No such file or directory" sp.Popen(['echo', '1']) # SUCCEEDS sp.Popen(['echo 1'], shell=True) # SUCCEEDS, but extra overhead sp.Popen(shlex.split('echo 1')) # SUCCEEDS, equivalent to #2 

Without shell=True , Popen expects the executable to be the first element of args, which is why it fails, there is no «echo 1» executable. Adding shell=True invokes your system shell and passes the first element of args to the shell. i.e. for linux, Popen([‘echo 1’], shell=True) is equivalent to Popen(‘/bin/sh’, ‘-c’, ‘echo 1’) which is more overhead than you may need. See Popen() documentation for cases when shell=True is actually useful.

Источник

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