Popen giving error in python when trying to execute a script - python

Have having issues with Popen in python. Code in question:
from subprocess import Popen
Popen(["nohup", "/usr/local/bin/python2.7 /somescript.py"])
With following error:
failed to run command `/usr/local/bin/python2.7 /somescript.py': No such file or directory
Thing is that when I run the same command in a terminal, it works and the file definitely exists.

You are missing 2 " and a , Popen takes a list of arguments. Try this:
from subprocess import Popen
Popen(["nohup", "/usr/local/bin/python2.7", "/somescript.py"])

Related

Subprocess can't find module when not run with shell=True (Python)

When I use Popen to start a subprocess, if shell=True isn't set I get the following error message:
Traceback (most recent call last):
File "C:\Users\Student01\PycharmProjects\yolov5-master\detect.py", line 37, in <module>
import torch
ModuleNotFoundError: No module named 'torch'
I don't get this error message if shell=True.
I don't want to need to set shell=True because it causes problems when I then try to call communicate or stdout on the subprocess (It just runs the subprocess into the shell without executing anything bellow the communicate call).
Here is the code (In case it can help):
#!/usr/bin/env python
import subprocess
detectPath = "C:\\Users\\Student01\\PycharmProjects\\yolov5-master\\detect.py"
print("First Print Passed")
process = subprocess.Popen("python {} --source 0".format(detectPath), stdout=subprocess.PIPE, shell=False)
# output = str(process.communicate())
while process.poll() is None:
process.stdout.readline()
print("Poll is None")
I am using Pycharm
I tried adding the yolov5 project files into the included files of my pycharm project (since I'm working in a venv) but still get the error.
The only solution to the moduleNotFound error seems to be to set shell=True in the Popen but that creates other problems.

Opening a program through the terminal in Kali Linux

Trying to make it not a hassle to open pyCharm in Kali Linux. I've been following an online class, and the way to open pyCharm is to navigate to the .sh file and open it. I tried automating the process using the subprocess module, but it gives the error:
no such file or directory: 'cd': 'cd'
My code:
import subprocess
subprocess.call("cd")
subprocess.call("cd", "Downloads/pycharm-community-2019.2.3/bin")
subprocess.call("/.pycharm.sh")
set the shell to True:
import subprocess
subprocess.call("cd", shell=True)
subprocess.call("cd", "Downloads/pycharm-community-2019.2.3/bin", shell=True)
subprocess.call("/.pycharm.sh", shell=True)
#it is "./pycharm.sh"

Python subprocess error: Popen, call, run "No such file or directory: error

I'm having issues with the subprocess module. I'm trying to run a terminal command in Python, which works perfectly fine in the terminal. The command is:
hrun SomeAction LogFile
I've tried a variety of options, including call(), run(), check_output(), and Popen(). No matter which method I use, I get the error:
FileNotFoundError: [Errno 2] No such file or directory: 'hrun': 'hrun'
My code is:
output = Popen(["hrun", "SomeAction", log_file_name], stdout=PIPE, stderr=PIPE)
where "hrun" and "SomeAction" are strings and log_file_name is a string variable.
I found other SO issues and, most (if not all) were resolved with either shell=True (which I dont want), or because the issue was due to a string instead of a list argument.
Thanks!
If you are just trying to run a command from a prompt within a script why not use something like
import os
os.system("your command")
You should be able to just run it like
os.system("hrun SomeAction LogFile")

python: how to run a program with a command line call (that takes a user's keystroke as input) from within another program?

I can run one program by typing: python enable_robot.py -e in the command line, but I want to run it from within another program.
In the other program, I imported subprocess and had subprocess.Popen(['enable_robot', 'baxter_tools/scripts/enable_robot.py','-e']), but I get an error message saying something about a callback.
If I comment out this line, the rest of my program works perfectly fine.
Any suggestions on how I could change this line to get my code to work or if I shouldn't be using subprocess at all?
If enable_robot.py requires user input, probably it wasn't meant to run from another python script. you might want to import it as a module: import enable_robot and run the functions you want to use from there.
If you want to stick to the subprocess, you can pass input with communicate:
p = subprocess.Popen(['enable_robot', 'baxter_tools/scripts/enable_robot.py','-e'])
p.communicate(input=b'whatever string\nnext line')
communicate documentation, example.
Your program enable_robot.py should meet the following requirements:
The first line is a path indicating what program is used to interpret
the script. In this case, it is the python path.
Your script should be executable
A very simple example. We have two python scripts: called.py and caller.py
Usage: caller.py will execute called.py using subprocess.Popen()
File /tmp/called.py
#!/usr/bin/python
print("OK")
File /tmp/caller.py
#!/usr/bin/python
import subprocess
proc = subprocess.Popen(['/tmp/called.py'])
Make both executable:
chmod +x /tmp/caller.py
chmod +x /tmp/called.py
caller.py output:
$ /tmp/caller.py
$ OK

os.system(<command>) execution through Python :: Limitations?

I'm writing a python (ver 2.7) script to automate the set of commands in this Getting Started example for INOTOOL.
Problem: When I run this entire script, I repeatedly encounter these errors:
Current Directory is not empty
No project is found in this directory
No project is found in this directory
But, when I run a first script only up till the code line marked, and manually type in the next three lines, or when I run these last three lines (starting from the "ino init -t blink" line) after manually accessing the beep folder, then I am able to successfully execute the same code.
Is there a limitation with os.system() that I'm encountering?
My code:
import os,sys
def upload()
os.system("cd /home/pi/Downloads")
os.system("mkdir beep")
os.system("cd beep") #will refer to this code junction in question description
os.system("ino init -t blink")
os.system("ino build")
os.system("ino upload")
sys.exit(0)
Yes, when os.system() commands are run for cd , it does not actually change the current directory for the python process' context. From documentation -
os.system(command)
Execute the command (a string) in a subshell. This is implemented by calling the Standard C function system(), and has the same limitations. Changes to sys.stdin, etc. are not reflected in the environment of the executed command.
So even though you are changing directory in os.system() call, the next os.system call still occurs in same directory. Which could be causing your issue.
You shoud try using os.chdir() to change the directory instead of os.system() calls.
The Best would be to use subprocess module as #PadraicCunningham explains in his answer.
You can use the subprocess module and os.mkdir to make the directory, you can pass the current working directory cwd to check_callso you actually execute the command in the directory:
from subprocess import check_call
import os
def upload():
d = "/home/pi/Downloads/beep"
os.mkdir(d)
check_call(["ino", "init", "-t", "blink"],cwd=d)
check_call(["ino", "build"],cwd=d)
check_call(["ino", "upload"],cwd=d)
A non-zero exit status will raise CalledProcessError which you may want to catch but once successful you know the commands all returned a 0 exit status.

Categories

Resources