I get FileNotFound error while using psutil library - python

I'm trying to run and kill site.py python script every 5 minutes using webreset.py script.
webreset.py:
from psutil import Process, Popen
from time import sleep
pid = 0
while True:
if pid:
Process(pid).terminate()
process = Popen('python3 site.py')
pid = process.pid
sleep(300)
But when I run webreset.py on Ubuntu 20.04, I get the following Error:
Traceback (most recent call last):
File "webreset.py", line 7, in <module>
process = Popen('python3 site.py')
File "/usr/local/lib/python3.8/dist-packages/psutil/__init__.py", line 1316, in __init__
self.__subproc = subprocess.Popen(*args, **kwargs)
File "/usr/lib/python3.8/subprocess.py", line 858, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "/usr/lib/python3.8/subprocess.py", line 1704, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'python3 site.py'
I run the script using this command :
sudo python3 webreset.py

You need to separate the command and arguments.
process = Popen(['python3', 'site.py'])
Otherwise it is looking for a command with the filename "python3 site.py"

using this:
Popen(['python3', 'site.py'])
instead of:
process = Popen('python3 site.py')
fixed my problem.

Related

Error while running bash command in python using subprocess: [WinError 2] The system cannot find the file specified

I am trying to execute the following bash command in python using the subprocess python package but its throwing me an error.
the bashCommand variable in the following code stores the bash command i'm trying to execute
def desc_calc():
bashCommand = "java -Xms2G -Xmx2G -Djava.awt.headless=true -jar ./PaDEL-Descriptor/PaDEL-Descriptor.jar -removesalt -standardizenitro -fingerprints -descriptortypes ./PaDEL-Descriptor/PubchemFingerprinter.xml -dir ./ -file descriptors_output.csv"
process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)
output, error = process.communicate()
upon running the code, i get the following error:
2023-01-25 17:27:06.101 Uncaught app exception
Traceback (most recent call last):
File "C:\Users\oo_wa\.conda\envs\streamlit\lib\site-packages\streamlit\runtime\scriptrunner\script_runner.py", line 563, in _run_script
exec(code, module.__dict__)
File "C:\Users\oo_wa\OneDrive\Desktop\BUSI_Dashboard\pages\2_Drug Discovery.py", line 82, in <module>
desc_calc()
File "C:\Users\oo_wa\OneDrive\Desktop\BUSI_Dashboard\pages\2_Drug Discovery.py", line 44, in desc_calc
process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)
File "C:\Users\oo_wa\.conda\envs\streamlit\lib\subprocess.py", line 969, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "C:\Users\oo_wa\.conda\envs\streamlit\lib\subprocess.py", line 1438, in _execute_child
hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] The system cannot find the file specified

FileNotFoundError: [WinError 2] The system cannot find the file specified

I am trying to open a shortcut for Notepad called Notepad.lnk.
Because I want to learn how to open applications so I can use the pygui library to manipulate them.
Got FileNotFoundError
I got this error:
Traceback (most recent call last):
File "C:\Users\{my_name}\PycharmProjects\texture-gen\main.py", line 185, in <module>
subprocess.run(['start', shortcut_path], check=True)
File "C:\Users\{my_name}\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 505, in run
with Popen(*popenargs, **kwargs) as process:
File "C:\Users\{my_name}\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 951, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "C:\Users\{my_name}\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 1420, in _execute_child
hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] The system cannot find the file specified
Code
This is my python code:
if __name__ == '__main__':
import os
import subprocess
cwd = os.getcwd()
shortcut_path = os.path.join(cwd, 'Notepad.lnk')
if not os.path.exists(shortcut_path):
print('Error: "Notepad.lnk" shortcut not found')
subprocess.run(['start', shortcut_path], check=True)
Debugging
I have checked the name of the shortcut is Notepad.lnk and is in the current working directory.
Why is this not working?

FileNotFoundError in subprocess.check_output [duplicate]

This question already has answers here:
Subprocess.Call fails "The System Cannot Find the File Specified"
(2 answers)
Closed 25 days ago.
I want to connect and use the functions of adb in a python environment.
In the terminal, adb is connected well as shown below.
$ adb --version
Android Debug Bridge version 1.0.41
Version 31.0.3-7562133
Installed as /opt/homebrew/bin/adb
$ command -v adb
/opt/homebrew/bin/adb
To use this in the python environment, subprocess.check_output was used,
I wrote python code as below.
import subprocess
cmd = f"adb --version"
print(f"cmd:{cmd}")
res = subprocess.check_output(cmd).decode("utf-8")
print(f"res:{res}")
I got an error as below.
$ python test.py
cmd:adb --version
Traceback (most recent call last):
File "/Users/hhd/project/hhdpy/test.py", line 5, in <module>
res = subprocess.check_output(cmd).decode("utf-8")
File "/opt/homebrew/anaconda3/envs/hhdpy/lib/python3.9/subprocess.py", line 424, in check_output
return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
File "/opt/homebrew/anaconda3/envs/hhdpy/lib/python3.9/subprocess.py", line 505, in run
with Popen(*popenargs, **kwargs) as process:
File "/opt/homebrew/anaconda3/envs/hhdpy/lib/python3.9/subprocess.py", line 951, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "/opt/homebrew/anaconda3/envs/hhdpy/lib/python3.9/subprocess.py", line 1821, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'adb --version'
In my opinion, subprocess.check_output does not seem to be able to import the PATH environment variable,
How should I solve it?
As suggested by John, one possible solution would be to provide --version as an argument.
To do so, you have to split the cmd command into a list, for instance:
res = subprocess.check_output(["adb", "--version"]).decode("utf-8")
tested with Python3.

Running a python script via command in aws lambda

Lets say I have a python project, where using a command in my local terminal I can do something like:
python3 somePythonFile.py --someFlag True --someOtherFlag False -f https://www.somexmlfile/thefile.xml
If I wanted to run this in a python Lambda, would it be possible to run it the same way, without importing as a module.
For example, I have tried this:
import subprocess
from subprocess import Popen
cmd = "python3 somePythonFile.py --someFlag True --someOtherFlag False -f https://www.somexmlfile/thefile.xml"
returned_output = Popen(cmd)
# using decode() function to convert byte string to string
print('Converted result:', returned_output.decode("utf-8"))
However this gives me an error:
[ERROR] FileNotFoundError: [Errno 2] No such file or directory: 'python3 somePythonFile.py --someFlag True --someOtherFlag False -f https://www.somexmlfile/thefile.xml'
Traceback (most recent call last):
  File "/var/task/app.py", line 32, in lambda_handler
    returned_output = Popen(cmd)
  File "/var/lang/lib/python3.8/subprocess.py", line 854, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "/var/lang/lib/python3.8/subprocess.py", line 1702, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
The command for Popen() needs to have the command line parameters as separated in a list. https://docs.python.org/3/library/subprocess.html#popen-constructor
Change your line
returned_output = Popen(cmd)
to this
returned_output = Popen(cmd.split())
As far as the lambda goes. I would highly suggest you put this code in a module (might save you lots of money). The AWS Lambda environment will be terminated as soon as the handler function returns. You would need to code your Lambda function to wait for the subprocess to complete.
Thanks to Mark B's answer to this question Independent python subprocess from AWS Lambda function

Call shell script from python

Attempting to call a shell script with options from a python script.
The line ./dropbox_uploader.sh -s download /test/pictures pictures/ runs fine via SSH but errors when called from a python script:
import subprocess
subprocess.call(['./dropbox_uploader.sh -s download /test/pictures pictures/'])
Here is the error message:
Traceback (most recent call last):
File "sync.py", line 2, in <module>
subprocess.call(['./dropbox_uploader.sh -s download /test/pictures pictures/'])
File "/usr/lib/python2.7/subprocess.py", line 493, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1259, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
In case if the first argument of subprocess.call is a list, it must contain the executable and arguments as separate items:
subprocess.call(['./dropbox_uploader.sh', '-s',
'download', '/test/pictures', 'pictures/'])
or, maybe, more convenient:
import shlex
cmd = './dropbox_uploader.sh -s download /test/pictures pictures/'
subprocess.call(shlex.split(cmd))
There is also an option to delegate parsing and execution to the shell:
cmd = './dropbox_uploader.sh -s download /test/pictures pictures/'
subprocess.call(cmd, shell=True)
(But please note the security warning)

Categories

Resources