" sh:1:内置无法打开:没有这样的文件"在Raspberry pi Python上

时间:2015-08-27 16:06:56

标签: python file raspberry-pi

所以我得到了一个覆盆子pi,我已经玩了几天了。我制作了一台相机"程序,你按下面包板上的按钮,它使用fswebcam拍照,并将其保存到闪存驱动器。我在Raspbian。这是我的代码:

import os
import random
import RPi.GPIO as GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(2, GPIO.IN)
#I know this next part looks a little weird, but in Raspbian every time you take out a flash drive it keeps a folder, then when you put the drive back in it calls it a slightly renamed version which messes up my code, and this next part will erase all the weird folders that have no use so that the flash drive will still be called FLASHDRIVE.
os.system("cd /")
os.system("cd /media")
#I hope the previous line worked,
os.system("sudo rm -rf *")
#The following function will wait until the buton is pressed:
def waitforbutton():
    if(GPIO.input(2) == False):
        return True
temp = waitforButton()
#The program will save the image as a random number.jpg
imgname = str(random.random) + ".jpg"
os.system("fswebcam /media/FLASHDRIVE/" + imgname)
print("Picture taken")

但是,当我输入:

sudo python camera.py

进入终端,它会打印一条GPIO警告信息,然后输入:

sh: 1: cannot open built-in: No such file
picture taken

然后,如果我再次运行该程序,它会说:

python: can't open file 'camera.py': [Errno 2] No such file or directory

请帮忙!!!!!

2 个答案:

答案 0 :(得分:0)

每次调用os.system都会启动一个新的子进程。子进程中进行的环境更改不会传播到原始父进程。您在一次通话中执行的cd不会设置您进行下一次通话时所在的目录。因此,当您执行sudo rm -rf *时,您仍然在原始目录中,而不是/media,并且删除了所有内容(包括您正在执行的camera.py脚本)。

您可以调用os.chdir(),它会更改python进程本身的目录,这将由子代继承。

os.chdir('/media');
os.system('sudo rm -rf *')

您还应该向os.chdir()调用添加错误检查,因为sudo rm -rf *如果您不在目标目录中,则会非常具有破坏性。如果从系统目录中执行此操作,则可能会完全破坏系统。

答案 1 :(得分:0)

首先,永远不要使用sudo rm -rf *这太危险了。这也是为什么下次您尝试运行camera.py时失败的原因,因为您已将其删除。

调用os.system创建运行传递命令的子进程。这意味着os.system('cd /media')将更改子进程的当前工作目录,但不会更改python脚本的进程。

要更改python进程的工作目录,请使用os.chdir

顺便说一下,您的功能waitforbutton实际上不会等待按下按钮。您需要将该检查放在一个循环中,或者甚至可以更好地使用GPIO的中断。