This question already has answers here:
"OSError: [Errno 2] No such file or directory" while using python subprocess with command and arguments
(3 answers)
Closed 3 days ago.
I am trying to output the result of tree command using python
import subprocess
cmd = "tree /home/ubuntu/data"
# returns output as byte string
returned_output = subprocess.check_output(cmd)
print(returned_output)
what is get is
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.10/subprocess.py", line 420, in check_output
return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
File "/usr/lib/python3.10/subprocess.py", line 501, in run
with Popen(*popenargs, **kwargs) as process:
File "/usr/lib/python3.10/subprocess.py", line 969, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "/usr/lib/python3.10/subprocess.py", line 1845, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'tree /home/ubuntu/data'
>>>
I am expecting
/home/ubuntu/data
├── input
│ └── test.txt
└── output
└── test.txt
2 directories, 2 files
How can i achieve this.
You may want to try shell=True like below:
returned_output = subprocess.check_output(cmd, shell=True)
Also read about the usage of shell=True at https://docs.python.org/3/library/subprocess.html#
Related
I've been tying to solve this issue but had no luck so far:
I have a script that captures some WIFI statistics from a raspberry pi.
the script runs fine when I execute from the terminal when using python network_test.py
script fails when I schedule a cron job using another python script:
python script to schedule job
from crontab import CronTab
cron = CronTab(user=True)
job = cron.new(command='cd /home/pi4/Documents/WIFI_Scan && /usr/bin/python /home/pi4/Documents/WIFI_Scan/network_test.py >> /home/pi4/Documents/WIFI_Scan/out.txt 2>&1')
job.minute.every(1)
for job in cron:
print(job)
cron.write()
- the script runs but i get the error below when I look at the out.txt file:
Traceback (most recent call last):
File "/home/pi4/Documents/WIFI_Scan/network_test.py", line 57, in <module>
print(subprocess.check_output(['iwgetid']).decode())
File "/home/pi4/Documents/WIFI_Scan/subprocess.py", line 424, in check_output
return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
File "/home/pi4/Documents/WIFI_Scan/subprocess.py", line 505, in run
with Popen(*popenargs, **kwargs) as process:
File "/home/pi4/Documents/WIFI_Scan/subprocess.py", line 951, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "/home/pi4/Documents/WIFI_Scan/subprocess.py", line 1823, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'iwgetid'
here is the network_test.py script
import subprocess
output = subprocess.check_output(['iwgetid']).decode()
print(output)
I've tried many things but no luck..
Tried moving the script to the main python folder.
tried using a bash file to start the script from cron but nothing
This question already has answers here:
Calling the "source" command from subprocess.Popen
(9 answers)
Closed 8 months ago.
I am tasked with automating the process of running bash script using python. Unfortunately I am not responsible for the bash script itself, so I have no idea how it works. When I run the script directly in the terminal using source adastralrc.sh , it works perfectly and gives the desired output.
However when I try to get python to run the file by using subprocess and the exact same command as the argument:
import subprocess
commands = ['source' , 'adastralrc.sh']
p = subprocess.run(commands)
I get the following error:
Traceback (most recent call last):
File "test2.py", line 6, in <module>
p = subprocess.call(commands)
File "/usr/lib64/python3.6/subprocess.py", line 287, in call
with Popen(*popenargs, **kwargs) as p:
File "/usr/lib64/python3.6/subprocess.py", line 729, in __init__
restore_signals, start_new_session)
File "/usr/lib64/python3.6/subprocess.py", line 1364, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'source adastralrc.sh': 'source adastralrc.sh'
(venv-c3dns) [vivegab#adl20213d1bld01 vivegab] (cth01/dns_mano_dev)
I am fairly inexperienced with subprocess but I thought that it was just an improved version of os.system() and should just enter the commands as if they were being typed by a person. So why am I getting the error above and what can be done to fix this?
def shell_source(script):
"""Sometime you want to emulate the action of "source" in bash,
settings some environment variables. Here is a way to do it."""
import subprocess, os
pipe = subprocess.Popen(". %s; env" % script, stdout=subprocess.PIPE, shell=True)
output = pipe.communicate()[0]
env = dict((line.split("=", 1) for line in output.splitlines()))
os.environ.update(env)
shell_source(adastralrc.sh)
Looks like a duplicate
This question already has answers here:
Cannot find the file specified when using subprocess.call('dir') in Python
(2 answers)
Closed 27 days ago.
I'm trying to use the subprocess module in visual sutdio code but I keep getting an error. Here is the code:
import subprocess
subprocess.run("dir")
or
import subprocess
subprocess.run("dir","/p")
and the error is:
Traceback (most recent call last):
File "e:\Dropbox (Personal)\My Python\external\extrprg.py", line 2, in <module>
subprocess.run("dir")
File "E:\Users\klo\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py", line 472, in run
with Popen(*popenargs, **kwargs) as process:
File "E:\Users\klo\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py", line 775, in __init__
restore_signals, start_new_session)
File "E:\Users\klo\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py", line 1178, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified
I'd expect python to run dir and give me a list of the folders in the directory
dir is a command in cmd.exe, which means you want to do:
subprocess.run(['cmd.exe', '/c', 'dir'])
I'm currently building the source code for Adblock Plus for a school
project and I'm using the Autoinstall addon to easily deploy to my
browser, however the provided build tools in Python only seem to work
when I execute them in the Git Bash for some reason.
Here is the error message when I try to execute the command in the
Windows command line:
C:\Users\Evert\Documents\GitHub\adblockplus>python build.py autoinstall 8888
Traceback (most recent call last):
File "C:\Users\Evert\Documents\GitHub\adblockplus\ensure_dependencies.py", line 380, in <module>
resolve_deps(repo)
File "C:\Users\Evert\Documents\GitHub\adblockplus\ensure_dependencies.py", line 324, in resolve_deps
update_repo(target, vcs, rev)
File "C:\Users\Evert\Documents\GitHub\adblockplus\ensure_dependencies.py", line 272, in update_repo
resolved_revision = repo_types[type].get_revision_id(target, revision)
File "C:\Users\Evert\Documents\GitHub\adblockplus\ensure_dependencies.py", line 106, in get_revision_id
return subprocess.check_output(command, cwd=repo).strip()
File "C:\Python27\lib\subprocess.py", line 212, in check_output
process = Popen(stdout=PIPE, *popenargs, **kwargs)
File "C:\Python27\lib\subprocess.py", line 390, in __init__
errread, errwrite)
File "C:\Python27\lib\subprocess.py", line 640, in _execute_child
startupinfo)
WindowsError: [Error 2] The system cannot find the file specified
Command '['C:\\Python27\\python.exe', 'C:\\Users\\Evert\\Documents\\GitHub\\adblockplus\\ensure_dependencies.py', 'C:\\Users\\Evert\\Documents\\GitHub\\adblockplus']' returned non-zero exit status 1
Failed to ensure dependencies being up-to-date!
Traceback (most recent call last):
File "build.py", line 18, in <module>
buildtools.build.processArgs(BASE_DIR, sys.argv)
File "C:\Users\Evert\Documents\GitHub\adblockplus\buildtools\build.py", line 601, in processArgs
commands[command](baseDir, scriptName, opts, args, type)
File "C:\Users\Evert\Documents\GitHub\adblockplus\buildtools\build.py", line 55, in __call__
return self._handler(baseDir, scriptName, opts, args, type)
File "C:\Users\Evert\Documents\GitHub\adblockplus\buildtools\build.py", line 225, in runAutoInstall
packager.autoInstall(baseDir, type, host, port, multicompartment=multicompartment)
File "C:\Users\Evert\Documents\GitHub\adblockplus\buildtools\packagerGecko.py", line 334, in autoInstall
createBuild(baseDir, type=type, outFile=fileBuffer, multicompartment=multicompartment)
File "C:\Users\Evert\Documents\GitHub\adblockplus\buildtools\packagerGecko.py", line 294, in createBuild
version = getBuildVersion(baseDir, metadata, releaseBuild, buildNum)
File "C:\Users\Evert\Documents\GitHub\adblockplus\buildtools\packager.py", line 58, in getBuildVersion
buildNum = getBuildNum(baseDir)
File "C:\Users\Evert\Documents\GitHub\adblockplus\buildtools\packager.py", line 46, in getBuildNum
result = subprocess.check_output(['git', 'rev-list', 'HEAD'], cwd=baseDir)
File "C:\Python27\lib\subprocess.py", line 212, in check_output
process = Popen(stdout=PIPE, *popenargs, **kwargs)
File "C:\Python27\lib\subprocess.py", line 390, in __init__
errread, errwrite)
File "C:\Python27\lib\subprocess.py", line 640, in _execute_child
startupinfo)
WindowsError: [Error 2] The system cannot find the file specified
This isn't a huge problem for me since it does build, but I can't help but
wonder: what is the difference between these two environments that makes
this script work?
The issue appears to be that git.exe isn't in your Windows PATH, which it definitely is in Git Bash :) . You have two "not found" errors, both for git:
In ensure_dependencies.py, line 106, executing command. Per the source, the command is ['git', 'rev-parse', '--revs-only', rev + '^{commit}'].
In packager.py, line 46, executing ['git', 'rev-list', 'HEAD'].
Both of those are a missing git. To fix, before running python build.py, do
path %PATH%;c:\<wherever git.exe is located>
or add the location of git.exe to your system PATH using the Control Panel.
Edit If your Git installation is from GitHub, this answer gives details about adding Git to your PATH.
When i try to run the scan operation using the wifi library as mentioned in the documentation, i get the following error.
(lsbaws)Keshav:bin root# wifi scan
Traceback (most recent call last):
File "/Users/Keshav/Documents/Github/Webserver/webserver/lsbaws/bin/wifi", line 202, in <module>
args.func(args)
File "/Users/Keshav/Documents/Github/Webserver/webserver/lsbaws/bin/wifi", line 51, in scan_command
print_table([[cell.signal, cell.ssid, 'protected' if cell.encrypted else 'unprotected'] for cell in Cell.all(args.interface)])
File "/Users/Keshav/Documents/Github/Webserver/webserver/lsbaws/lib/python2.7/site-packages/wifi/scan.py", line 29, in all
stderr=subprocess.STDOUT)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 566, in check_output
process = Popen(stdout=PIPE, *popenargs, **kwargs)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 709, in __init__
errread, errwrite)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1326, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
I figured that this python wifi library does not work on mac.
An alternative to do wifi scanning is using the tool that comes in mac called airports.
To start using the tool -
$ cd /usr/sbin
$ sudo ln -s /System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport
The airports -I flag is useful
Also just typing airports will open up the partly explicit manual page
Refrence link - Airports Example