简体   繁体   中英

Python RPi - File not found when running script from another script

I'm trying to run a python script from another python script on a Raspberry Pi 3 with Raspbian. I've been trying to find ways to do this for some hours and didn't find anything that worked. I've tried some ways but it either says that has not permission to execute the file or it can't find it. I don't know what I'm doing wrong. I need to run multiple instances of the other script through the main script in a new console (new processes) and keep them running (I don't expect them to return anything to the main script). Can anyone help me? Because with Windows it was really easy as the program was working fine until I tried to run it on Linux (with Windows, I used os.startfile).

In test.py:

print("test1")
input()

In main.py:

import os
import subprocess
print("main")
os.system("python test.py")
input()

In the console: main python: can't open file 'test.py': [Errno 2] No such file or directory

In main.py:

import os
import subprocess
print("main")
subprocess.Popen("python test.py",shell=True)
input()

In the console: main python: can't open file 'test.py': [Errno 2] No such file or directory

In main.py:

import os
import subprocess
print("main")
subprocess.call("python test.py",shell=True)
input()

In the console: main python: can't open file 'test.py': [Errno 2] No such file or directory

I tried more ways but I don't remember them. Maybe I'm doing something wrong?

EDIT: I can now run the scripts without any problems with os.chdir (thanks to JH). My problem now is that it prints test in the same console window as the main.py and I needed it to create another process for the test.py. Any solutions?

EDIT 2: Finally I could start a new processes of the test.py from the main.py! I used os.system('xdg-open "test.py"') to open test.py with the default application. Anyway thanks to JH, otherwise it would continue to say file not found.

Final main.py:

import os
print("main")
os.chdir('/home/pi/Desktop/')
os.system('xdg-open test.py')
input()

Thanks in advance!

Printing out os.getcwd() will help you to debug this.

Either supply a fully qualified pathname, /some/where/test.py, or use os.chdir('/some/where') before executing test.py.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM