PROBLEM
Attempts to truncate an ArcGIS Online hosted layer using a script in PyCharm fail, and the following error message is returned:
Traceback (most recent call last):
File "C:\Users\<Username>\PycharmProjects\PythonProject\idle_repro_test2.py", line 1, in <module>
import arcpy
ModuleNotFoundError: No module named 'arcpy'

The PyCharm project interpreter is set to use a Python environment that is not within the ArcGIS Pro conda environment. ArcPy is only installed within the ArcGIS Pro conda environment. This is required to run ArcGIS Pro geoprocessing tools such as the Truncate Table tool. Refer to ArcGIS Pro: Python and geoprocessing for more information.
Using IDLE prevents a mismatch in the Python environment when running the Truncate Table tool because launching it from the ArcGIS Pro Python Command Prompt activates the ArcGIS Pro Python environment and ensures the scripts are run using the same interpreter.
Prerequisites for the hosted layer URL: • Ensure the hosted layer supports Truncate. • Toggle Enable sync (required for offline use and collaboration) off. • Ensure the hosted layer has no attachments. Refer to ArcGIS Pro: Truncate Table (Data Management) for more information.


The URL below is an example of the saved URL.

python -c "import sys; print(sys.executable)"
python -m idlelib.idle
The window below is displayed after IDLE Shell is launched from the Python command prompt.


import arcpy
import datetime
import sys
import getpass
def log(msg):
ts = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(f"[{ts}] {msg}")
log("=== Truncate Repro Test Started ===")
log(f"Python executable: {sys.executable}")
try:
portal_url = "https://www.arcgis.com" #change this part if using organization account
username = "<portal_username>"
password = "<portal_password>"
arcpy.SignInToPortal(portal_url, username, password)
log(f"Active portal: {arcpy.GetActivePortalURL()}")
layer0_url = r"<hosted_layer_URL>"
log("Creating feature layer...")
lyr = arcpy.management.MakeFeatureLayer(layer0_url, "target_lyr").getOutput(0)
log("MakeFeatureLayer SUCCESS")
log("Running TruncateTable...")
arcpy.management.TruncateTable(lyr)
log("TruncateTable SUCCESS")
except Exception as ex:
log(f"FAILED: {ex}")
finally:
log("--- ArcPy Messages ---")
log(arcpy.GetMessages())
log("=== Truncate Repro Test Completed ===")

The IDLE Shell window below indicates the truncate operation is successful.

Article ID: 000036798
Get help from ArcGIS experts
Start chatting now